blob: d3de6035d3fd9c32b71d1ea9416269cad52a85f9 [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 Chartier357e9be2012-08-01 11:00:14 -0700142 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700143 total_bytes_freed_(0),
144 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700145 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800146 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700147 verify_missing_card_marks_(false),
148 verify_system_weaks_(false),
149 verify_pre_gc_heap_(false),
150 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700151 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700152 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700153 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700154 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700155 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700156 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),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700164 total_paused_time_(0),
165 total_wait_time_(0),
166 measure_allocation_time_(false),
167 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700168 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800169 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800170 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700171 }
172
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700173 live_bitmap_.reset(new HeapBitmap(this));
174 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700175
Ian Rogers30fab402012-01-23 15:43:46 -0800176 // Requested begin for the alloc space, to follow the mapped image and oat files
177 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800178 std::string image_file_name(original_image_file_name);
179 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700180 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700181
Brian Carlstrom5643b782012-02-05 12:32:53 -0800182 if (OS::FileExists(image_file_name.c_str())) {
183 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700184 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800185 } else {
186 // If the /system file didn't exist, we need to use one from the art-cache.
187 // If the cache file exists, try to open, but if it fails, regenerate.
188 // If it does not exist, generate.
189 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
190 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700191 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800192 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700193 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700194 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700195 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800196 }
197 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700198
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700199 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700200 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800201 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
202 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700203 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
204 CHECK_GT(oat_end_addr, image_space->End());
205
206 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
207 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
208 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
209 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
210 reinterpret_cast<byte*>(reserve_begin),
211 reserve_end - reserve_begin, PROT_READ));
212
Ian Rogers30fab402012-01-23 15:43:46 -0800213 if (oat_end_addr > requested_begin) {
214 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700215 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700216 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700217 }
218
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700219 // Allocate the large object space.
220 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700221 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
222 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
223
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700224 UniquePtr<AllocSpace> alloc_space(AllocSpace::Create("alloc space", initial_size, growth_limit,
225 capacity, requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700226 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700227 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700228 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700229
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700230 // Spaces are sorted in order of Begin().
231 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700232 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
233 if (spaces_.back()->IsAllocSpace()) {
234 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
235 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700236
Ian Rogers30fab402012-01-23 15:43:46 -0800237 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700238 // TODO: C++0x
239 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
240 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800241 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700242 ImageSpace* image_space = space->AsImageSpace();
243 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800244 }
245 }
246
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800247 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700248 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
249 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700250
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700251 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
252 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700253
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700254 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
255 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700256
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700257 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700258 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700259
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700260 // Max stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700261 static const size_t default_mark_stack_size = 64 * KB;
262 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
263 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700264 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700265 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
266 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700267
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800268 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700269 // but we can create the heap lock now. We don't create it earlier to
270 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700271 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700272 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700273
Mathieu Chartier0325e622012-09-05 14:22:51 -0700274 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700275 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
276 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700277 std::ostringstream name;
278 name << static_cast<GcType>(i);
279 cumulative_timings_.Put(static_cast<GcType>(i),
280 new CumulativeLogger(name.str().c_str(), true));
281 }
282
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800283 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800284 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700285 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700286}
287
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700288// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700289struct SpaceSorter {
290 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700291 return a->Begin() < b->Begin();
292 }
293};
294
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700295void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700296 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700297 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700298 DCHECK(space->GetLiveBitmap() != NULL);
299 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700300 DCHECK(space->GetMarkBitmap() != NULL);
301 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800302 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700303 if (space->IsAllocSpace()) {
304 alloc_space_ = space->AsAllocSpace();
305 }
306
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700307 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
308 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700309
310 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
311 // avoid redundant marking.
312 bool seen_zygote = false, seen_alloc = false;
313 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
314 Space* space = *it;
315 if (space->IsImageSpace()) {
316 DCHECK(!seen_zygote);
317 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700318 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700319 DCHECK(!seen_alloc);
320 seen_zygote = true;
321 } else if (space->IsAllocSpace()) {
322 seen_alloc = true;
323 }
324 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800325}
326
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700327void Heap::DumpGcPerformanceInfo() {
328 // Dump cumulative timings.
329 LOG(INFO) << "Dumping cumulative Gc timings";
330 uint64_t total_duration = 0;
331 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
332 it != cumulative_timings_.end(); ++it) {
333 CumulativeLogger* logger = it->second;
334 if (logger->GetTotalNs() != 0) {
335 logger->Dump();
336 total_duration += logger->GetTotalNs();
337 }
338 }
339 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
340 size_t total_objects_allocated = GetTotalObjectsAllocated();
341 size_t total_bytes_allocated = GetTotalBytesAllocated();
342 if (total_duration != 0) {
343 const double total_seconds = double(total_duration / 1000) / 1000000.0;
344 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
345 LOG(INFO) << "Mean GC size throughput: "
346 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
347 LOG(INFO) << "Mean GC object throughput: " << GetTotalObjectsFreed() / total_seconds << "/s";
348 }
349 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
350 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
351 if (measure_allocation_time_) {
352 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
353 LOG(INFO) << "Mean allocation time: "
354 << PrettyDuration(allocation_time / total_objects_allocated);
355 }
356 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time_);
357 LOG(INFO) << "Total waiting for Gc to complete time: " << PrettyDuration(total_wait_time_);
358}
359
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800360Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700361 // If we don't reset then the mark stack complains in it's destructor.
362 allocation_stack_->Reset();
363 live_stack_->Reset();
364
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800365 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800366 // We can't take the heap lock here because there might be a daemon thread suspended with the
367 // heap lock held. We know though that no non-daemon threads are executing, and we know that
368 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
369 // 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 -0700370 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700371 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700372 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700373}
374
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700375ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700376 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700377 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
378 if ((*it)->Contains(obj)) {
379 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700380 }
381 }
382 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
383 return NULL;
384}
385
386ImageSpace* Heap::GetImageSpace() {
387 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700388 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
389 if ((*it)->IsImageSpace()) {
390 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700391 }
392 }
393 return NULL;
394}
395
396AllocSpace* Heap::GetAllocSpace() {
397 return alloc_space_;
398}
399
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700400static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700401 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700402 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700403 size_t chunk_free_bytes = chunk_size - used_bytes;
404 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
405 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700406 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700407}
408
Ian Rogers50b35e22012-10-04 10:09:15 -0700409Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700410 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
411 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
412 strlen(ClassHelper(c).GetDescriptor()) == 0);
413 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700414
415 Object* obj = NULL;
416 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700417 uint64_t allocation_start = 0;
418 if (measure_allocation_time_) {
419 allocation_start = NanoTime();
420 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700421
422 // We need to have a zygote space or else our newly allocated large object can end up in the
423 // Zygote resulting in it being prematurely freed.
424 // We can only do this for primive objects since large objects will not be within the card table
425 // range. This also means that we rely on SetClass not dirtying the object's card.
426 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700427 size = RoundUp(byte_count, kPageSize);
Ian Rogers50b35e22012-10-04 10:09:15 -0700428 obj = Allocate(self, NULL, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700429 // Make sure that our large object didn't get placed anywhere within the space interval or else
430 // it breaks the immune range.
431 DCHECK(obj == NULL ||
432 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
433 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700434 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700435 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700436
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700437 // Ensure that we did not allocate into a zygote space.
438 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
439 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700440 }
441
Mathieu Chartier037813d2012-08-23 16:44:59 -0700442 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700443 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700444
445 // Record allocation after since we want to use the atomic add for the atomic fence to guard
446 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700447 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700448
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700449 if (Dbg::IsAllocTrackingEnabled()) {
450 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700451 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700452 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700453 // We already have a request pending, no reason to start more until we update
454 // concurrent_start_bytes_.
455 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700456 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700457 SirtRef<Object> ref(self, obj);
458 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700459 }
460 VerifyObject(obj);
461
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700462 if (measure_allocation_time_) {
463 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
464 }
465
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466 return obj;
467 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700468 int64_t total_bytes_free = GetFreeMemory();
469 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700471 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
472 if ((*it)->IsAllocSpace()) {
473 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700474 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700475 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700476
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700477 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 -0700478 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700479 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700480 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700481}
482
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700483bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700484 // Note: we deliberately don't take the lock here, and mustn't test anything that would
485 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700486 if (obj == NULL) {
487 return true;
488 }
489 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700490 return false;
491 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800492 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800493 if (spaces_[i]->Contains(obj)) {
494 return true;
495 }
496 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700497 // TODO: Find a way to check large object space without using a lock.
498 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700499}
500
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700501bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700502 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700503 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700504}
505
Elliott Hughes3e465b12011-09-02 18:26:12 -0700506#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700507void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700508 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700509 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700510 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700511 return;
512 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700513 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700514}
515#endif
516
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700517void Heap::DumpSpaces() {
518 // TODO: C++0x auto
519 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700520 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700521 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
522 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
523 LOG(INFO) << space << " " << *space << "\n"
524 << live_bitmap << " " << *live_bitmap << "\n"
525 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700526 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700527 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700528}
529
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700530void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700531 if (!IsAligned<kObjectAlignment>(obj)) {
532 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700533 }
534
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700535 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
536 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700537 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700538 // Check the allocation stack / live stack.
539 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
540 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
541 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700542 if (large_object_space_->GetLiveObjects()->Test(obj)) {
543 DumpSpaces();
544 LOG(FATAL) << "Object is dead: " << obj;
545 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700546 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700547 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700548
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700549 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700550 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700551 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
552 Object::ClassOffset().Int32Value();
553 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
554 if (c == NULL) {
555 LOG(FATAL) << "Null class in object: " << obj;
556 } else if (!IsAligned<kObjectAlignment>(c)) {
557 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
558 } else if (!GetLiveBitmap()->Test(c)) {
559 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
560 }
561 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
562 // Note: we don't use the accessors here as they have internal sanity checks
563 // that we don't want to run
564 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
565 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
566 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
567 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
568 CHECK_EQ(c_c, c_c_c);
569 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700570}
571
Brian Carlstrom78128a62011-09-15 17:21:19 -0700572void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700573 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700574 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700575}
576
577void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700578 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700579 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700580}
581
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700582void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700583 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700584 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700585 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700586
587 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700588 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700589 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700590 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700591
592 // TODO: Update these atomically.
593 RuntimeStats* global_stats = Runtime::Current()->GetStats();
594 ++global_stats->allocated_objects;
595 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700596 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700597
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700598 // This is safe to do since the GC will never free objects which are neither in the allocation
599 // stack or the live bitmap.
600 while (!allocation_stack_->AtomicPushBack(obj)) {
601 Thread* self = Thread::Current();
602 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
603 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
604 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
605 self->TransitionFromSuspendedToRunnable();
606 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700607}
608
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700609void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700610 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
611 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700612
613 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700614 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700615 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700616 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700617
618 // TODO: Do this concurrently.
619 RuntimeStats* global_stats = Runtime::Current()->GetStats();
620 global_stats->freed_objects += freed_objects;
621 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700622 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700623}
624
Ian Rogers50b35e22012-10-04 10:09:15 -0700625Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700626 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
627 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
628 return NULL;
629 }
630
Mathieu Chartier83cf3282012-09-26 17:54:27 -0700631 if (UNLIKELY(space == NULL)) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700632 return large_object_space_->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700633 } else if (grow) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700634 return space->AllocWithGrowth(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700635 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700636 return space->AllocWithoutGrowth(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700637 }
638}
639
Ian Rogers50b35e22012-10-04 10:09:15 -0700640Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700641 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
642 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700643 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700644 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700645
Ian Rogers50b35e22012-10-04 10:09:15 -0700646 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700647 if (ptr != NULL) {
648 return ptr;
649 }
650
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700651 // The allocation failed. If the GC is running, block until it completes, and then retry the
652 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700653 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700654 if (last_gc != kGcTypeNone) {
655 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700656 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700657 if (ptr != NULL) {
658 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700659 }
660 }
661
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700662 // Loop through our different Gc types and try to Gc until we get enough free memory.
663 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
664 bool run_gc = false;
665 GcType gc_type = static_cast<GcType>(i);
666 switch (gc_type) {
667 case kGcTypeSticky: {
668 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700669 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
670 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700671 break;
672 }
673 case kGcTypePartial:
674 run_gc = have_zygote_space_;
675 break;
676 case kGcTypeFull:
677 run_gc = true;
678 break;
679 default:
680 break;
681 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700682
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700683 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700684 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
685
686 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700687 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700688 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
689 i = static_cast<size_t>(gc_type_ran);
690 self->TransitionFromSuspendedToRunnable();
691
692 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700693 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700694 if (ptr != NULL) {
695 return ptr;
696 }
697 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700698 }
699
700 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700701 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700702 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700703 if (ptr != NULL) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700704 if (space != NULL) {
705 size_t new_footprint = space->GetFootprintLimit();
706 // OLD-TODO: may want to grow a little bit more so that the amount of
707 // free space is equal to the old free space + the
708 // utilization slop for the new allocation.
709 VLOG(gc) << "Grow alloc space (frag case) to " << PrettySize(new_footprint)
710 << " for a " << PrettySize(alloc_size) << " allocation";
711 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700712 return ptr;
713 }
714
Elliott Hughes81ff3182012-03-23 20:35:56 -0700715 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
716 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
717 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700718
Elliott Hughes418dfe72011-10-06 18:56:27 -0700719 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700720 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
721 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700722
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700723 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700724 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700725 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700726 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700727 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700728}
729
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700730float Heap::GetTargetHeapUtilization() const {
731 return target_utilization_;
732}
733
734void Heap::SetTargetHeapUtilization(float target) {
735 DCHECK_GT(target, 0.0f); // asserted in Java code
736 DCHECK_LT(target, 1.0f);
737 target_utilization_ = target;
738}
739
740int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700741 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700742}
743
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700744int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700745 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700746}
747
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700748int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700749 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700750}
751
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700752size_t Heap::GetTotalBytesFreed() const {
753 return total_bytes_freed_;
754}
755
756size_t Heap::GetTotalObjectsFreed() const {
757 return total_objects_freed_;
758}
759
760size_t Heap::GetTotalObjectsAllocated() const {
761 size_t total = large_object_space_->GetTotalObjectsAllocated();
762 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
763 Space* space = *it;
764 if (space->IsAllocSpace()) {
765 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
766 }
767 }
768 return total;
769}
770
771size_t Heap::GetTotalBytesAllocated() const {
772 size_t total = large_object_space_->GetTotalBytesAllocated();
773 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
774 Space* space = *it;
775 if (space->IsAllocSpace()) {
776 total += space->AsAllocSpace()->GetTotalBytesAllocated();
777 }
778 }
779 return total;
780}
781
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700782class InstanceCounter {
783 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700784 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700785 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700786 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700787
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700788 }
789
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700790 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
791 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700792 if (count_assignable_) {
793 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700794 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700795 }
796 } else {
797 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700798 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700799 }
800 }
801 }
802
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700803 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700804 Class* class_;
805 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700806 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700807};
808
809int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700810 size_t count = 0;
811 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700812 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700813 GetLiveBitmap()->Visit(counter);
814 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700815}
816
Ian Rogers30fab402012-01-23 15:43:46 -0800817void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700818 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
819 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700820 Thread* self = Thread::Current();
821 WaitForConcurrentGcToComplete(self);
822 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700823 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
824 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700825}
826
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700827void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700828 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700829 Thread* self = Thread::Current();
830 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700831
832 // Try to see if we have any Zygote spaces.
833 if (have_zygote_space_) {
834 return;
835 }
836
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700837 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
838
839 {
840 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700841 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700842 FlushAllocStack();
843 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700844
845 // Replace the first alloc space we find with a zygote space.
846 // TODO: C++0x auto
847 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
848 if ((*it)->IsAllocSpace()) {
849 AllocSpace* zygote_space = (*it)->AsAllocSpace();
850
851 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
852 // of the remaining available heap memory.
853 alloc_space_ = zygote_space->CreateZygoteSpace();
854
855 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700856 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700857 AddSpace(alloc_space_);
858 have_zygote_space_ = true;
859 break;
860 }
861 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700862
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700863 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700864 // TODO: C++0x
865 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
866 it != cumulative_timings_.end(); ++it) {
867 it->second->Reset();
868 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700869}
870
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700871void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700872 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
873 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700874 allocation_stack_->Reset();
875}
876
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700877size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700878 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700879}
880
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700881void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
882 Object** limit = stack->End();
883 for (Object** it = stack->Begin(); it != limit; ++it) {
884 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700885 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700886 if (LIKELY(bitmap->HasAddress(obj))) {
887 bitmap->Set(obj);
888 } else {
889 large_objects->Set(obj);
890 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700891 }
892}
893
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700894void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
895 Object** limit = stack->End();
896 for (Object** it = stack->Begin(); it != limit; ++it) {
897 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700898 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700899 if (LIKELY(bitmap->HasAddress(obj))) {
900 bitmap->Clear(obj);
901 } else {
902 large_objects->Clear(obj);
903 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700904 }
905}
906
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700907GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700908 Thread* self = Thread::Current();
909 Locks::mutator_lock_->AssertNotHeld(self);
910 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700911
Ian Rogers120f1c72012-09-28 17:17:10 -0700912 if (self->IsHandlingStackOverflow()) {
913 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
914 }
915
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700916 // Ensure there is only one GC at a time.
917 bool start_collect = false;
918 while (!start_collect) {
919 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700920 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700921 if (!is_gc_running_) {
922 is_gc_running_ = true;
923 start_collect = true;
924 }
925 }
926 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700927 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700928 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
929 // Not doing at the moment to ensure soft references are cleared.
930 }
931 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700932 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700933
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700934 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
935 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
936 ++Thread::Current()->GetStats()->gc_for_alloc_count;
937 }
938
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700939 // We need to do partial GCs every now and then to avoid the heap growing too much and
940 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700941 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700942 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700943 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700944 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700945 sticky_gc_count_ = 0;
946 }
947
Mathieu Chartier637e3482012-08-17 10:41:32 -0700948 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700949 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700950 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700951 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700952 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700953 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700954
Ian Rogers15bf2d32012-08-28 17:33:04 -0700955 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700956 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700957 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700958 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700959 // Wake anyone who may have been waiting for the GC to complete.
960 gc_complete_cond_->Broadcast();
961 }
962 // Inform DDMS that a GC completed.
963 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700964 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700965}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700966
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700967void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
968 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700969 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700970
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700971 std::stringstream gc_type_str;
972 gc_type_str << gc_type << " ";
973
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700974 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700975 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700976 ThreadList* thread_list = Runtime::Current()->GetThreadList();
977 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700978 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700979 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700980
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700981 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700982 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700983 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700984 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700985 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700986 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700987
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700988 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700989 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700990 if (!VerifyHeapReferences()) {
991 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
992 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700993 timings.AddSplit("VerifyHeapReferencesPreGC");
994 }
995
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700996 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700997 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700998
999 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1000 // TODO: Investigate using a mark stack instead of a vector.
1001 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001002 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001003 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1004 card_table_->GetDirtyCards(*it, dirty_cards);
1005 }
1006 }
1007
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001008 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001009 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001010
Ian Rogers120f1c72012-09-28 17:17:10 -07001011 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001012 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001013 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1014 // accidentally un-mark roots.
1015 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001016 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001017 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1018 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001019 }
1020 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001021 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001022
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001023 // We can assume that everything from the start of the first space to the alloc space is marked.
1024 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1025 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001026 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001027 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001028 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1029 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001030 }
1031 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001032 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001033 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001034 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001035 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1036 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001037 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001038 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001039
Carl Shapiro58551df2011-07-24 03:09:51 -07001040 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001041 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001042
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001043 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001044 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -07001045
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001046 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1047
1048 if (gc_type != kGcTypeSticky) {
1049 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1050 live_stack_.get());
1051 timings.AddSplit("MarkStackAsLive");
1052 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001053
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001054 if (verify_mod_union_table_) {
1055 zygote_mod_union_table_->Update();
1056 zygote_mod_union_table_->Verify();
1057 mod_union_table_->Update();
1058 mod_union_table_->Verify();
1059 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001060
1061 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001062 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001063 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001064 } else {
1065 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1066 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001067 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001068
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001069 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001070 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001071 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001072
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001073#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001074 // Verify that we only reach marked objects from the image space
1075 mark_sweep.VerifyImageRoots();
1076 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001077#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001078
Mathieu Chartier0325e622012-09-05 14:22:51 -07001079 if (gc_type != kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001080 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1081 timings.AddSplit("Sweep");
1082 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001083 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001084 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001085 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001086 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001087 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001088 live_stack_->Reset();
1089
1090 // Unbind the live and mark bitmaps.
1091 mark_sweep.UnBindBitmaps();
1092
1093 const bool swap = true;
1094 if (swap) {
1095 if (gc_type == kGcTypeSticky) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001096 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001097 } else {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001098 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001099 }
1100 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001101
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001102 if (verify_system_weaks_) {
1103 mark_sweep.VerifySystemWeaks();
1104 timings.AddSplit("VerifySystemWeaks");
1105 }
1106
Elliott Hughesadb460d2011-10-05 17:02:34 -07001107 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001108 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001109 total_bytes_freed_ += bytes_freed;
1110 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001111 }
1112
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001113 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001114 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001115 if (!VerifyHeapReferences()) {
1116 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1117 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001118 timings.AddSplit("VerifyHeapReferencesPostGC");
1119 }
1120
Carl Shapiro58551df2011-07-24 03:09:51 -07001121 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001122 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001123
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001124 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001125 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001126
1127 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001128 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001129 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001130
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001131 // If the GC was slow, then print timings in the log.
1132 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001133 total_paused_time_ += duration / kTimeAdjust;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001134 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001135 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001136 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001137 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001138 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001139 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001140 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001141 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001142 if (VLOG_IS_ON(heap)) {
1143 timings.Dump();
1144 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001145 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001146
Mathieu Chartier0325e622012-09-05 14:22:51 -07001147 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1148 logger->Start();
1149 logger->AddLogger(timings);
1150 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001151}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001152
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001153void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001154 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001155 // 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 -07001156 // cards.
1157 return;
1158 }
1159
1160 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001161 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001162 zygote_mod_union_table_->Update();
1163 timings.AddSplit("UpdateZygoteModUnionTable");
1164
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001165 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001166 timings.AddSplit("ZygoteMarkReferences");
1167 }
1168
1169 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1170 mod_union_table_->Update();
1171 timings.AddSplit("UpdateModUnionTable");
1172
1173 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001174 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001175 timings.AddSplit("MarkImageToAllocSpaceReferences");
1176}
1177
1178void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1179 Object* obj = reinterpret_cast<Object*>(arg);
1180 if (root == obj) {
1181 LOG(INFO) << "Object " << obj << " is a root";
1182 }
1183}
1184
1185class ScanVisitor {
1186 public:
1187 void operator ()(const Object* obj) const {
1188 LOG(INFO) << "Would have rescanned object " << obj;
1189 }
1190};
1191
1192class VerifyReferenceVisitor {
1193 public:
1194 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001195 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1196 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001197 : heap_(heap),
1198 failed_(failed) {
1199 }
1200
1201 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1202 // analysis.
1203 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1204 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1205 // Verify that the reference is live.
1206 if (ref != NULL && !IsLive(ref)) {
1207 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001208 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1209 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001210
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001211 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001212 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1213 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1214 << "Obj type " << PrettyTypeOf(obj) << "\n"
1215 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001216 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001217 void* cover_begin = card_table->AddrFromCard(card_addr);
1218 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001219 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001220 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001221 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001222 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1223
1224 // Print out how the object is live.
1225 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001226 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1227 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001228 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1229 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1230 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001231 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1232 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001233 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001234 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001235 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001236 }
1237
1238 // Attempt to see if the card table missed the reference.
1239 ScanVisitor scan_visitor;
1240 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001241 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1242 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001243
1244 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001245 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001246 MarkSweep ms(mark_stack);
1247 ms.Init();
1248 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001249 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001250
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001251 // All the references should end up in the mark stack.
1252 ms.ScanRoot(obj);
1253 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001254 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001255 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001256 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001257 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001258 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001259 }
1260 }
1261 mark_stack->Reset();
1262
1263 // Search to see if any of the roots reference our object.
1264 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1265 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1266 *failed_ = true;
1267 }
1268 }
1269
1270 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1271 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1272 if (bitmap != NULL) {
1273 if (bitmap->Test(obj)) {
1274 return true;
1275 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001276 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001277 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001278 } else {
1279 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001280 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001281 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001282 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001283 // At this point we need to search the allocation since things in the live stack may get swept.
1284 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1285 return true;
1286 }
1287 // Not either in the live bitmap or allocation stack, so the object must be dead.
1288 return false;
1289 }
1290
1291 private:
1292 Heap* heap_;
1293 bool* failed_;
1294};
1295
1296class VerifyObjectVisitor {
1297 public:
1298 VerifyObjectVisitor(Heap* heap)
1299 : heap_(heap),
1300 failed_(false) {
1301
1302 }
1303
1304 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001305 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001306 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1307 MarkSweep::VisitObjectReferences(obj, visitor);
1308 }
1309
1310 bool Failed() const {
1311 return failed_;
1312 }
1313
1314 private:
1315 Heap* heap_;
1316 bool failed_;
1317};
1318
1319// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001320bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001321 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001322 // Lets sort our allocation stacks so that we can efficiently binary search them.
1323 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1324 std::sort(live_stack_->Begin(), live_stack_->End());
1325 // Perform the verification.
1326 VerifyObjectVisitor visitor(this);
1327 GetLiveBitmap()->Visit(visitor);
1328 // We don't want to verify the objects in the allocation stack since they themselves may be
1329 // pointing to dead objects if they are not reachable.
1330 if (visitor.Failed()) {
1331 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001332 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001333 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001334 return true;
1335}
1336
1337class VerifyReferenceCardVisitor {
1338 public:
1339 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1340 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1341 Locks::heap_bitmap_lock_)
1342 : heap_(heap),
1343 failed_(failed) {
1344 }
1345
1346 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1347 // analysis.
1348 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1349 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001350 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001351 CardTable* card_table = heap_->GetCardTable();
1352 // If the object is not dirty and it is referencing something in the live stack other than
1353 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001354 if (!card_table->AddrIsInCardTable(obj)) {
1355 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1356 *failed_ = true;
1357 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001358 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001359 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1360 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1361 LOG(ERROR) << "Object " << obj << " found in live stack";
1362 }
1363 if (heap_->GetLiveBitmap()->Test(obj)) {
1364 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1365 }
1366 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1367 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1368
1369 // Print which field of the object is dead.
1370 if (!obj->IsObjectArray()) {
1371 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1372 CHECK(klass != NULL);
1373 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1374 CHECK(fields != NULL);
1375 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1376 const Field* cur = fields->Get(i);
1377 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1378 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1379 << PrettyField(cur);
1380 break;
1381 }
1382 }
1383 } else {
1384 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1385 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1386 if (object_array->Get(i) == ref) {
1387 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1388 }
1389 }
1390 }
1391
1392 *failed_ = true;
1393 }
1394 }
1395 }
1396 }
1397
1398 private:
1399 Heap* heap_;
1400 bool* failed_;
1401};
1402
1403class VerifyLiveStackReferences {
1404 public:
1405 VerifyLiveStackReferences(Heap* heap)
1406 : heap_(heap),
1407 failed_(false) {
1408
1409 }
1410
1411 void operator ()(const Object* obj) const
1412 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1413 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1414 MarkSweep::VisitObjectReferences(obj, visitor);
1415 }
1416
1417 bool Failed() const {
1418 return failed_;
1419 }
1420
1421 private:
1422 Heap* heap_;
1423 bool failed_;
1424};
1425
1426bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001427 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001428
1429 VerifyLiveStackReferences visitor(this);
1430 GetLiveBitmap()->Visit(visitor);
1431
1432 // We can verify objects in the live stack since none of these should reference dead objects.
1433 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1434 visitor(*it);
1435 }
1436
1437 if (visitor.Failed()) {
1438 DumpSpaces();
1439 return false;
1440 }
1441 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001442}
1443
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001444void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001445 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001446 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1447 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001448 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1449 ContinuousSpace* space = *it;
1450 // We never allocate into zygote spaces.
1451 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1452 (gc_type == kGcTypeFull &&
1453 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
1454 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1455 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1456 space->AsAllocSpace()->SwapBitmaps();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001457 }
1458 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001459 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001460}
1461
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001462void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001463 large_object_space_->SwapBitmaps();
1464 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1465 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001466}
1467
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001468void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001469 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001470 allocation_stack_.reset(live_stack_.release());
1471 live_stack_.reset(temp);
1472
1473 // Sort the live stack so that we can quickly binary search it later.
1474 if (VERIFY_OBJECT_ENABLED) {
1475 std::sort(live_stack_->Begin(), live_stack_->End());
1476 }
1477}
1478
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001479void Heap::ClearCards(TimingLogger& timings) {
1480 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1481 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1482 ContinuousSpace* space = *it;
1483 if (space->IsImageSpace()) {
1484 mod_union_table_->ClearCards(*it);
1485 timings.AddSplit("ModUnionClearCards");
1486 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1487 zygote_mod_union_table_->ClearCards(space);
1488 timings.AddSplit("ZygoteModUnionClearCards");
1489 } else {
1490 card_table_->ClearSpaceCards(space);
1491 timings.AddSplit("ClearCards");
1492 }
1493 }
1494}
1495
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001496void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1497 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001498 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1499 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001500 std::stringstream gc_type_str;
1501 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001502
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001503 // Suspend all threads are get exclusive access to the heap.
1504 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1505 thread_list->SuspendAll();
1506 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001507 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001508
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001509 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001510 Object* cleared_references = NULL;
1511 {
1512 MarkSweep mark_sweep(mark_stack_.get());
1513 timings.AddSplit("ctor");
1514
1515 mark_sweep.Init();
1516 timings.AddSplit("Init");
1517
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001518 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001519 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001520 if (!VerifyHeapReferences()) {
1521 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1522 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001523 timings.AddSplit("VerifyHeapReferencesPreGC");
1524 }
1525
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001526 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1527 SwapStacks();
1528
1529 // Check that all objects which reference things in the live stack are on dirty cards.
1530 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001531 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001532 // Sort the live stack so that we can quickly binary search it later.
1533 std::sort(live_stack_->Begin(), live_stack_->End());
1534 if (!VerifyMissingCardMarks()) {
1535 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1536 }
1537 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001538
1539 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1540 // TODO: Investigate using a mark stack instead of a vector.
1541 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001542 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001543 dirty_cards.reserve(4 * KB);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001544 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1545 card_table_->GetDirtyCards(*it, dirty_cards);
1546 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001547 timings.AddSplit("GetDirtyCards");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001548 }
1549
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001550 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001551 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001552
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001553 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001554 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001555
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001556 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001557 DCHECK(!GetLiveBitmap()->Test(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001558 }
1559
Mathieu Chartier0325e622012-09-05 14:22:51 -07001560 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001561 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1562 // accidentally un-mark roots.
1563 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001564 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001565 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1566 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001567 }
1568 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001569 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001570 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1571 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001572 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001573 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001574 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1575 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001576 }
1577 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001578 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001579 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001580 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001581 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1582 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001583 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001584 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001585
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001586 // Marking roots is not necessary for sticky mark bits since we only actually require the
1587 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001588 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001589 mark_sweep.MarkRoots();
1590 timings.AddSplit("MarkRoots");
1591 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001592
1593 if (verify_mod_union_table_) {
1594 zygote_mod_union_table_->Update();
1595 zygote_mod_union_table_->Verify();
1596 mod_union_table_->Update();
1597 mod_union_table_->Verify();
1598 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001599 }
1600
1601 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001602 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001603
1604 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1605 thread_list->ResumeAll();
1606 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001607 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001608 root_end = NanoTime();
1609 timings.AddSplit("RootEnd");
1610
Ian Rogers81d425b2012-09-27 16:03:43 -07001611 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001612 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001613
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001614 if (gc_type != kGcTypeSticky) {
1615 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1616 // knowing that new allocations won't be marked as live.
1617 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1618 live_stack_.get());
1619 timings.AddSplit("MarkStackAsLive");
1620 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001621
Mathieu Chartier0325e622012-09-05 14:22:51 -07001622 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001623 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001624 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001625 } else {
1626 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001627 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001628 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001629 }
1630 // Release share on mutator_lock_ and then get exclusive access.
1631 dirty_begin = NanoTime();
1632 thread_list->SuspendAll();
1633 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001634 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001635
1636 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001637 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001638
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001639 // Re-mark root set.
1640 mark_sweep.ReMarkRoots();
1641 timings.AddSplit("ReMarkRoots");
1642
1643 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001644 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001645 timings.AddSplit("RecursiveMarkDirtyObjects");
1646 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001647
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001649 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001650
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001651 mark_sweep.ProcessReferences(clear_soft_references);
1652 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001653 }
1654
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001655 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1656 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001657 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001658 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001659 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001660 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001661 // We only sweep over the live stack, and the live stack should not intersect with the
1662 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001663 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1664 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001665 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001666#ifndef NDEBUG
1667 if (gc_type == kGcTypeSticky) {
1668 // Make sure everything in the live stack isn't something we unmarked.
1669 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1670 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001671 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1672 << "Unmarked object " << *it << " in the live stack";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001673 }
1674 } else {
1675 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001676 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001677 }
1678 }
1679#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001680 }
1681
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001682 if (kIsDebugBuild) {
1683 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001684 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001685 mark_sweep.VerifyImageRoots();
1686 timings.AddSplit("VerifyImageRoots");
1687 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001688
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001689 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001690 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1691 SwapBitmaps(gc_type);
1692 if (!VerifyHeapReferences()) {
1693 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001694 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001695 SwapBitmaps(gc_type);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001696 timings.AddSplit("VerifyHeapReferencesPostGC");
1697 }
1698
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001699 thread_list->ResumeAll();
1700 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001701 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001702
1703 {
1704 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001705 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001706 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001707 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1708 timings.AddSplit("Sweep");
1709 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001710 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001711 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001712 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001713 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001714 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001715 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001716 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001717 }
1718
1719 {
1720 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1721 // Unbind the live and mark bitmaps.
1722 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001723
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001724 // Swap the live and mark bitmaps for each space which we modified space. This is an
1725 // optimization that enables us to not clear live bits inside of the sweep.
1726 const bool swap = true;
1727 if (swap) {
1728 if (gc_type == kGcTypeSticky) {
1729 SwapLargeObjects();
1730 } else {
1731 SwapBitmaps(gc_type);
1732 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001733 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001734 }
1735
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001736 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001737 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001738 mark_sweep.VerifySystemWeaks();
1739 timings.AddSplit("VerifySystemWeaks");
1740 }
1741
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001742 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001743 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001744 total_bytes_freed_ += bytes_freed;
1745 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001746 }
1747
1748 GrowForUtilization();
1749 timings.AddSplit("GrowForUtilization");
1750
1751 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001752 timings.AddSplit("EnqueueClearedReferences");
1753
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001754 RequestHeapTrim();
1755 timings.AddSplit("Finish");
1756
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001757 // If the GC was slow, then print timings in the log.
1758 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1759 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001760 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001761 total_paused_time_ += (pause_roots + pause_dirty) / kTimeAdjust;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001762 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001763 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001764 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001765 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001766 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001767 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001768 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001769 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1770 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001771 if (VLOG_IS_ON(heap)) {
1772 timings.Dump();
1773 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001774 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001775
Mathieu Chartier0325e622012-09-05 14:22:51 -07001776 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1777 logger->Start();
1778 logger->AddLogger(timings);
1779 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001780}
1781
Ian Rogers81d425b2012-09-27 16:03:43 -07001782GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001783 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001784 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001785 bool do_wait;
1786 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001787 {
1788 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001789 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001790 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001791 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001792 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001793 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001794 // We must wait, change thread state then sleep on gc_complete_cond_;
1795 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1796 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001797 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001798 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001799 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001800 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001801 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001802 wait_time = NanoTime() - wait_start;;
1803 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001804 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001805 if (wait_time > MsToNs(5)) {
1806 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1807 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001809 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001810 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001811}
1812
Elliott Hughesc967f782012-04-16 10:23:15 -07001813void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001814 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1815 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001816 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001817}
1818
1819size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001820 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001821}
1822
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001823void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001824 AllocSpace* alloc_space = alloc_space_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001825 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001826 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001827 << PrettySize(GetMaxMemory());
1828 max_allowed_footprint = GetMaxMemory();
1829 }
1830 // We want to update the footprint for just the alloc space.
1831 max_allowed_footprint -= large_object_space_->GetNumBytesAllocated();
1832 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1833 if ((*it)->IsAllocSpace()) {
1834 AllocSpace* alloc_space = (*it)->AsAllocSpace();
1835 if (alloc_space != alloc_space_) {
1836 max_allowed_footprint -= alloc_space->GetNumBytesAllocated();
1837 }
1838 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001839 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001840 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001841}
1842
Ian Rogers3bb17a62012-01-27 23:56:44 -08001843// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001844static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001845// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1846// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001847static const size_t kHeapMinFree = kHeapIdealFree / 4;
1848
Carl Shapiro69759ea2011-07-21 18:13:35 -07001849void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001850 // We know what our utilization is at this moment.
1851 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1852 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
1853 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1854 target_size = num_bytes_allocated_ + kHeapIdealFree;
1855 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1856 target_size = num_bytes_allocated_ + kHeapMinFree;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001857 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001858
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001859 // Calculate when to perform the next ConcurrentGC.
1860 if (GetFreeMemory() < concurrent_min_free_) {
1861 // Not enough free memory to perform concurrent GC.
1862 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1863 } else {
1864 // Start a concurrent Gc when we get close to the target size.
1865 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001866 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001867
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001868 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001869}
1870
jeffhaoc1160702011-10-27 15:48:45 -07001871void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001872 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001873 alloc_space_->ClearGrowthLimit();
1874}
1875
Elliott Hughesadb460d2011-10-05 17:02:34 -07001876void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001877 MemberOffset reference_queue_offset,
1878 MemberOffset reference_queueNext_offset,
1879 MemberOffset reference_pendingNext_offset,
1880 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001881 reference_referent_offset_ = reference_referent_offset;
1882 reference_queue_offset_ = reference_queue_offset;
1883 reference_queueNext_offset_ = reference_queueNext_offset;
1884 reference_pendingNext_offset_ = reference_pendingNext_offset;
1885 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1886 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1887 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1888 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1889 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1890 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1891}
1892
1893Object* Heap::GetReferenceReferent(Object* reference) {
1894 DCHECK(reference != NULL);
1895 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1896 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1897}
1898
1899void Heap::ClearReferenceReferent(Object* reference) {
1900 DCHECK(reference != NULL);
1901 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1902 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1903}
1904
1905// Returns true if the reference object has not yet been enqueued.
1906bool Heap::IsEnqueuable(const Object* ref) {
1907 DCHECK(ref != NULL);
1908 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1909 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1910 return (queue != NULL) && (queue_next == NULL);
1911}
1912
1913void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1914 DCHECK(ref != NULL);
1915 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1916 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1917 EnqueuePendingReference(ref, cleared_reference_list);
1918}
1919
1920void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1921 DCHECK(ref != NULL);
1922 DCHECK(list != NULL);
1923
1924 if (*list == NULL) {
1925 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1926 *list = ref;
1927 } else {
1928 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1929 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1930 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1931 }
1932}
1933
1934Object* Heap::DequeuePendingReference(Object** list) {
1935 DCHECK(list != NULL);
1936 DCHECK(*list != NULL);
1937 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1938 Object* ref;
1939 if (*list == head) {
1940 ref = *list;
1941 *list = NULL;
1942 } else {
1943 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1944 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1945 ref = head;
1946 }
1947 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1948 return ref;
1949}
1950
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001951void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001952 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001953 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001954 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001955 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1956 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001957}
1958
1959size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001960 return num_bytes_allocated_;
1961}
1962
1963size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001964 size_t total = 0;
1965 // TODO: C++0x
1966 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1967 Space* space = *it;
1968 if (space->IsAllocSpace()) {
1969 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1970 }
1971 }
1972 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001973}
1974
1975size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001976 return concurrent_start_size_;
1977}
1978
1979size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001980 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001981}
1982
1983void Heap::EnqueueClearedReferences(Object** cleared) {
1984 DCHECK(cleared != NULL);
1985 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001986 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001987 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001988 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001989 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1990 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001991 *cleared = NULL;
1992 }
1993}
1994
Ian Rogers1f539342012-10-03 21:09:42 -07001995void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001996 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001997 Runtime* runtime = Runtime::Current();
1998 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1999 !runtime->IsConcurrentGcEnabled()) {
2000 return;
2001 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002002 {
2003 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2004 if (runtime->IsShuttingDown()) {
2005 return;
2006 }
2007 }
2008 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002009 return;
2010 }
2011
2012 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07002013 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002014 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2015 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002016 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2017 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002018 CHECK(!env->ExceptionCheck());
2019 requesting_gc_ = false;
2020}
2021
Ian Rogers81d425b2012-09-27 16:03:43 -07002022void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002023 {
2024 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2025 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2026 return;
2027 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002028 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002029
Ian Rogers81d425b2012-09-27 16:03:43 -07002030 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002031 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002032 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002033 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002034 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002035 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002036 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002037 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002038 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002039}
2040
Ian Rogers81d425b2012-09-27 16:03:43 -07002041void Heap::Trim(Thread* self) {
2042 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002043 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002044}
2045
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002046void Heap::RequestHeapTrim() {
2047 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2048 // because that only marks object heads, so a large array looks like lots of empty space. We
2049 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2050 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2051 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2052 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002053 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002054 float utilization =
2055 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2056 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2057 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2058 // heap trim occurred in the last two seconds.
2059 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002060 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002061
2062 Thread* self = Thread::Current();
2063 {
2064 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2065 Runtime* runtime = Runtime::Current();
2066 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2067 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2068 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2069 // as we don't hold the lock while requesting the trim).
2070 return;
2071 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002072 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002073 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002074 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002075 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2076 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002077 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2078 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002079 CHECK(!env->ExceptionCheck());
2080}
2081
Carl Shapiro69759ea2011-07-21 18:13:35 -07002082} // namespace art