blob: 6c13563338cf3b6e2b9d78ece90084b217e361f3 [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"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070029#include "gc/large_object_space.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070030#include "gc/mark_sweep.h"
31#include "gc/mod_union_table.h"
32#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070033#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080035#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080036#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070037#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070038#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070039#include "sirt_ref.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070040#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070041#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070042#include "timing_logger.h"
43#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070044#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070045
46namespace art {
47
Elliott Hughesae80b492012-04-24 10:43:17 -070048static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080049 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080050 std::vector<std::string> boot_class_path;
51 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070052 if (boot_class_path.empty()) {
53 LOG(FATAL) << "Failed to generate image because no boot class path specified";
54 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080055
56 std::vector<char*> arg_vector;
57
58 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070059 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080060 const char* dex2oat = dex2oat_string.c_str();
61 arg_vector.push_back(strdup(dex2oat));
62
63 std::string image_option_string("--image=");
64 image_option_string += image_file_name;
65 const char* image_option = image_option_string.c_str();
66 arg_vector.push_back(strdup(image_option));
67
68 arg_vector.push_back(strdup("--runtime-arg"));
69 arg_vector.push_back(strdup("-Xms64m"));
70
71 arg_vector.push_back(strdup("--runtime-arg"));
72 arg_vector.push_back(strdup("-Xmx64m"));
73
74 for (size_t i = 0; i < boot_class_path.size(); i++) {
75 std::string dex_file_option_string("--dex-file=");
76 dex_file_option_string += boot_class_path[i];
77 const char* dex_file_option = dex_file_option_string.c_str();
78 arg_vector.push_back(strdup(dex_file_option));
79 }
80
81 std::string oat_file_option_string("--oat-file=");
82 oat_file_option_string += image_file_name;
83 oat_file_option_string.erase(oat_file_option_string.size() - 3);
84 oat_file_option_string += "oat";
85 const char* oat_file_option = oat_file_option_string.c_str();
86 arg_vector.push_back(strdup(oat_file_option));
87
88 arg_vector.push_back(strdup("--base=0x60000000"));
89
Elliott Hughes48436bb2012-02-07 15:23:28 -080090 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080091 LOG(INFO) << command_line;
92
Elliott Hughes48436bb2012-02-07 15:23:28 -080093 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -080094 char** argv = &arg_vector[0];
95
96 // fork and exec dex2oat
97 pid_t pid = fork();
98 if (pid == 0) {
99 // no allocation allowed between fork and exec
100
101 // change process groups, so we don't get reaped by ProcessManager
102 setpgid(0, 0);
103
104 execv(dex2oat, argv);
105
106 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
107 return false;
108 } else {
109 STLDeleteElements(&arg_vector);
110
111 // wait for dex2oat to finish
112 int status;
113 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
114 if (got_pid != pid) {
115 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
116 return false;
117 }
118 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
119 LOG(ERROR) << dex2oat << " failed: " << command_line;
120 return false;
121 }
122 }
123 return true;
124}
125
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700126void Heap::UnReserveOatFileAddressRange() {
127 oat_file_map_.reset(NULL);
128}
129
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800130Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700131 const std::string& original_image_file_name, bool concurrent_gc)
132 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800133 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700134 concurrent_gc_(concurrent_gc),
135 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800136 card_marking_disabled_(false),
137 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700138 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700139 enforce_heap_growth_rate_(false),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700140 growth_limit_(growth_limit),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700141 max_allowed_footprint_(kInitialSize),
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700142 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700143 concurrent_start_size_(128 * KB),
144 concurrent_min_free_(256 * KB),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700145 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700146 total_bytes_freed_(0),
147 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700148 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800149 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700150 verify_missing_card_marks_(false),
151 verify_system_weaks_(false),
152 verify_pre_gc_heap_(false),
153 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700154 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700155 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700156 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700157 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700158 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700159 requesting_gc_(false),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700160 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800161 reference_referent_offset_(0),
162 reference_queue_offset_(0),
163 reference_queueNext_offset_(0),
164 reference_pendingNext_offset_(0),
165 finalizer_reference_zombie_offset_(0),
166 target_utilization_(0.5),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700167 total_paused_time_(0),
168 total_wait_time_(0),
169 measure_allocation_time_(false),
170 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700171 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800172 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800173 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700174 }
175
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700176 live_bitmap_.reset(new HeapBitmap(this));
177 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700178
Ian Rogers30fab402012-01-23 15:43:46 -0800179 // Requested begin for the alloc space, to follow the mapped image and oat files
180 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800181 std::string image_file_name(original_image_file_name);
182 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700183 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700184
Brian Carlstrom5643b782012-02-05 12:32:53 -0800185 if (OS::FileExists(image_file_name.c_str())) {
186 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700187 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800188 } else {
189 // If the /system file didn't exist, we need to use one from the art-cache.
190 // If the cache file exists, try to open, but if it fails, regenerate.
191 // If it does not exist, generate.
192 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
193 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700194 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800195 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700196 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700197 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700198 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800199 }
200 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700201
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700202 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700203 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800204 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
205 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700206 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
207 CHECK_GT(oat_end_addr, image_space->End());
208
209 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
210 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
211 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
212 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
213 reinterpret_cast<byte*>(reserve_begin),
214 reserve_end - reserve_begin, PROT_READ));
215
Ian Rogers30fab402012-01-23 15:43:46 -0800216 if (oat_end_addr > requested_begin) {
217 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700218 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700219 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700220 }
221
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700222 // Allocate the large object space.
223 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700224 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
225 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
226
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700227 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
228 growth_limit, capacity,
229 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700230 alloc_space_ = alloc_space.release();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700231 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700232 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700233 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700234
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700235 // Spaces are sorted in order of Begin().
236 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700237 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
238 if (spaces_.back()->IsAllocSpace()) {
239 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
240 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700241
Ian Rogers30fab402012-01-23 15:43:46 -0800242 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700243 // TODO: C++0x
244 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
245 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800246 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700247 ImageSpace* image_space = space->AsImageSpace();
248 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800249 }
250 }
251
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800252 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700253 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
254 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700255
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700256 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
257 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700258
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700259 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
260 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700261
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700262 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700263 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700264
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700265 // Max stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700266 static const size_t default_mark_stack_size = 64 * KB;
267 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
268 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700269 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700270 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
271 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700272
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800273 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700274 // but we can create the heap lock now. We don't create it earlier to
275 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700276 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700277 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700278
Mathieu Chartier0325e622012-09-05 14:22:51 -0700279 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700280 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
281 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700282 std::ostringstream name;
283 name << static_cast<GcType>(i);
284 cumulative_timings_.Put(static_cast<GcType>(i),
285 new CumulativeLogger(name.str().c_str(), true));
286 }
287
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800288 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800289 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700290 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700291}
292
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700293// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700294struct SpaceSorter {
295 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700296 return a->Begin() < b->Begin();
297 }
298};
299
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700300void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700301 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700302 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700303 DCHECK(space->GetLiveBitmap() != NULL);
304 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700305 DCHECK(space->GetMarkBitmap() != NULL);
306 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800307 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700308 if (space->IsAllocSpace()) {
309 alloc_space_ = space->AsAllocSpace();
310 }
311
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700312 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
313 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700314
315 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
316 // avoid redundant marking.
317 bool seen_zygote = false, seen_alloc = false;
318 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
319 Space* space = *it;
320 if (space->IsImageSpace()) {
321 DCHECK(!seen_zygote);
322 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700323 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700324 DCHECK(!seen_alloc);
325 seen_zygote = true;
326 } else if (space->IsAllocSpace()) {
327 seen_alloc = true;
328 }
329 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800330}
331
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700332void Heap::DumpGcPerformanceInfo() {
333 // Dump cumulative timings.
334 LOG(INFO) << "Dumping cumulative Gc timings";
335 uint64_t total_duration = 0;
336 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
337 it != cumulative_timings_.end(); ++it) {
338 CumulativeLogger* logger = it->second;
339 if (logger->GetTotalNs() != 0) {
340 logger->Dump();
341 total_duration += logger->GetTotalNs();
342 }
343 }
344 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
345 size_t total_objects_allocated = GetTotalObjectsAllocated();
346 size_t total_bytes_allocated = GetTotalBytesAllocated();
347 if (total_duration != 0) {
348 const double total_seconds = double(total_duration / 1000) / 1000000.0;
349 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
350 LOG(INFO) << "Mean GC size throughput: "
351 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
352 LOG(INFO) << "Mean GC object throughput: " << GetTotalObjectsFreed() / total_seconds << "/s";
353 }
354 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
355 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
356 if (measure_allocation_time_) {
357 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
358 LOG(INFO) << "Mean allocation time: "
359 << PrettyDuration(allocation_time / total_objects_allocated);
360 }
361 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time_);
362 LOG(INFO) << "Total waiting for Gc to complete time: " << PrettyDuration(total_wait_time_);
363}
364
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800365Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700366 // If we don't reset then the mark stack complains in it's destructor.
367 allocation_stack_->Reset();
368 live_stack_->Reset();
369
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800370 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800371 // We can't take the heap lock here because there might be a daemon thread suspended with the
372 // heap lock held. We know though that no non-daemon threads are executing, and we know that
373 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
374 // 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 -0700375 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700376 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700377 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700378}
379
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700380ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700381 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700382 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
383 if ((*it)->Contains(obj)) {
384 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700385 }
386 }
387 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
388 return NULL;
389}
390
391ImageSpace* Heap::GetImageSpace() {
392 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700393 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
394 if ((*it)->IsImageSpace()) {
395 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700396 }
397 }
398 return NULL;
399}
400
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700401DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700402 return alloc_space_;
403}
404
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700405static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700406 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700407 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700408 size_t chunk_free_bytes = chunk_size - used_bytes;
409 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
410 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700411 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700412}
413
Ian Rogers50b35e22012-10-04 10:09:15 -0700414Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700415 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
416 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
417 strlen(ClassHelper(c).GetDescriptor()) == 0);
418 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700419
420 Object* obj = NULL;
421 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700422 uint64_t allocation_start = 0;
423 if (measure_allocation_time_) {
424 allocation_start = NanoTime();
425 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700426
427 // We need to have a zygote space or else our newly allocated large object can end up in the
428 // Zygote resulting in it being prematurely freed.
429 // We can only do this for primive objects since large objects will not be within the card table
430 // range. This also means that we rely on SetClass not dirtying the object's card.
431 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700432 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700433 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700434 // Make sure that our large object didn't get placed anywhere within the space interval or else
435 // it breaks the immune range.
436 DCHECK(obj == NULL ||
437 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
438 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700439 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700440 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700441
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700442 // Ensure that we did not allocate into a zygote space.
443 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
444 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700445 }
446
Mathieu Chartier037813d2012-08-23 16:44:59 -0700447 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700449
450 // Record allocation after since we want to use the atomic add for the atomic fence to guard
451 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700452 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700453
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454 if (Dbg::IsAllocTrackingEnabled()) {
455 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700456 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700457 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700458 // We already have a request pending, no reason to start more until we update
459 // concurrent_start_bytes_.
460 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700462 SirtRef<Object> ref(self, obj);
463 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 }
465 VerifyObject(obj);
466
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700467 if (measure_allocation_time_) {
468 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
469 }
470
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700471 return obj;
472 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700473 int64_t total_bytes_free = GetFreeMemory();
474 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700475 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700476 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
477 if ((*it)->IsAllocSpace()) {
478 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700479 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700480 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700481
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700482 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 -0700483 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700484 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700485 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700486}
487
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700488bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700489 // Note: we deliberately don't take the lock here, and mustn't test anything that would
490 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700491 if (obj == NULL) {
492 return true;
493 }
494 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700495 return false;
496 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800497 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800498 if (spaces_[i]->Contains(obj)) {
499 return true;
500 }
501 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700502 // TODO: Find a way to check large object space without using a lock.
503 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700504}
505
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700506bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700507 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700508 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700509}
510
Elliott Hughes3e465b12011-09-02 18:26:12 -0700511#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700512void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700513 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700514 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700515 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700516 return;
517 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700518 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700519}
520#endif
521
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700522void Heap::DumpSpaces() {
523 // TODO: C++0x auto
524 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700525 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700526 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
527 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
528 LOG(INFO) << space << " " << *space << "\n"
529 << live_bitmap << " " << *live_bitmap << "\n"
530 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700531 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700532 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700533}
534
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700535void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700536 if (!IsAligned<kObjectAlignment>(obj)) {
537 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700538 }
539
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700540 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
541 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700542 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700543 // Check the allocation stack / live stack.
544 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
545 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
546 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700547 if (large_object_space_->GetLiveObjects()->Test(obj)) {
548 DumpSpaces();
549 LOG(FATAL) << "Object is dead: " << obj;
550 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700551 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700552 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700553
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700554 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700555 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700556 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
557 Object::ClassOffset().Int32Value();
558 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
559 if (c == NULL) {
560 LOG(FATAL) << "Null class in object: " << obj;
561 } else if (!IsAligned<kObjectAlignment>(c)) {
562 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
563 } else if (!GetLiveBitmap()->Test(c)) {
564 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
565 }
566 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
567 // Note: we don't use the accessors here as they have internal sanity checks
568 // that we don't want to run
569 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
570 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
571 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
572 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
573 CHECK_EQ(c_c, c_c_c);
574 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700575}
576
Brian Carlstrom78128a62011-09-15 17:21:19 -0700577void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700578 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700579 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700580}
581
582void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700583 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700584 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700585}
586
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700587void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700588 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700589 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700590 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700591
592 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700593 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700594 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700595 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700596
597 // TODO: Update these atomically.
598 RuntimeStats* global_stats = Runtime::Current()->GetStats();
599 ++global_stats->allocated_objects;
600 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700601 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700602
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700603 // This is safe to do since the GC will never free objects which are neither in the allocation
604 // stack or the live bitmap.
605 while (!allocation_stack_->AtomicPushBack(obj)) {
606 Thread* self = Thread::Current();
607 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
608 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
609 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
610 self->TransitionFromSuspendedToRunnable();
611 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700612}
613
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700614void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700615 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
616 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700617
618 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700619 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700620 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700621 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700622
623 // TODO: Do this concurrently.
624 RuntimeStats* global_stats = Runtime::Current()->GetStats();
625 global_stats->freed_objects += freed_objects;
626 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700627 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700628}
629
Ian Rogers50b35e22012-10-04 10:09:15 -0700630Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700631 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700632 if (enforce_heap_growth_rate_ && num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
633 if (grow) {
634 // Grow the heap by alloc_size extra bytes.
635 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
636 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
637 << " for a " << PrettySize(alloc_size) << " allocation";
638 } else {
639 return NULL;
640 }
641 }
642
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700643 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700644 // Completely out of memory.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700645 return NULL;
646 }
647
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700648 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700649}
650
Ian Rogers50b35e22012-10-04 10:09:15 -0700651Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700652 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
653 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700654 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700655 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700656
Ian Rogers50b35e22012-10-04 10:09:15 -0700657 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700658 if (ptr != NULL) {
659 return ptr;
660 }
661
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700662 // The allocation failed. If the GC is running, block until it completes, and then retry the
663 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700664 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700665 if (last_gc != kGcTypeNone) {
666 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700667 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700668 if (ptr != NULL) {
669 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700670 }
671 }
672
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700673 // Loop through our different Gc types and try to Gc until we get enough free memory.
674 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
675 bool run_gc = false;
676 GcType gc_type = static_cast<GcType>(i);
677 switch (gc_type) {
678 case kGcTypeSticky: {
679 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700680 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
681 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700682 break;
683 }
684 case kGcTypePartial:
685 run_gc = have_zygote_space_;
686 break;
687 case kGcTypeFull:
688 run_gc = true;
689 break;
690 default:
691 break;
692 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700693
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700694 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700695 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
696
697 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700698 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700699 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
700 i = static_cast<size_t>(gc_type_ran);
701 self->TransitionFromSuspendedToRunnable();
702
703 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700704 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700705 if (ptr != NULL) {
706 return ptr;
707 }
708 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700709 }
710
711 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700712 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700713 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700714 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700715 return ptr;
716 }
717
Elliott Hughes81ff3182012-03-23 20:35:56 -0700718 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
719 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
720 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700721
Elliott Hughes418dfe72011-10-06 18:56:27 -0700722 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700723 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
724 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700725
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700726 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700727 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700728 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700729 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700730 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700731}
732
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700733float Heap::GetTargetHeapUtilization() const {
734 return target_utilization_;
735}
736
737void Heap::SetTargetHeapUtilization(float target) {
738 DCHECK_GT(target, 0.0f); // asserted in Java code
739 DCHECK_LT(target, 1.0f);
740 target_utilization_ = target;
741}
742
743int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700744 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700745}
746
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700747int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700748 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700749}
750
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700751int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700752 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700753}
754
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700755size_t Heap::GetTotalBytesFreed() const {
756 return total_bytes_freed_;
757}
758
759size_t Heap::GetTotalObjectsFreed() const {
760 return total_objects_freed_;
761}
762
763size_t Heap::GetTotalObjectsAllocated() const {
764 size_t total = large_object_space_->GetTotalObjectsAllocated();
765 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
766 Space* space = *it;
767 if (space->IsAllocSpace()) {
768 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
769 }
770 }
771 return total;
772}
773
774size_t Heap::GetTotalBytesAllocated() const {
775 size_t total = large_object_space_->GetTotalBytesAllocated();
776 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
777 Space* space = *it;
778 if (space->IsAllocSpace()) {
779 total += space->AsAllocSpace()->GetTotalBytesAllocated();
780 }
781 }
782 return total;
783}
784
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700785class InstanceCounter {
786 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700787 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700788 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700789 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700790
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700791 }
792
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700793 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
794 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700795 if (count_assignable_) {
796 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700797 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700798 }
799 } else {
800 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700801 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700802 }
803 }
804 }
805
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700806 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700807 Class* class_;
808 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700809 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700810};
811
812int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700813 size_t count = 0;
814 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700815 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700816 GetLiveBitmap()->Visit(counter);
817 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700818}
819
Ian Rogers30fab402012-01-23 15:43:46 -0800820void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700821 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
822 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700823 Thread* self = Thread::Current();
824 WaitForConcurrentGcToComplete(self);
825 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700826 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
827 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700828}
829
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700830void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700831 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700832 Thread* self = Thread::Current();
833 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700834
835 // Try to see if we have any Zygote spaces.
836 if (have_zygote_space_) {
837 return;
838 }
839
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700840 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
841
842 {
843 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700844 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700845 FlushAllocStack();
846 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700847
848 // Replace the first alloc space we find with a zygote space.
849 // TODO: C++0x auto
850 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
851 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700852 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700853
854 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
855 // of the remaining available heap memory.
856 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700857 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700858
859 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700860 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700861 AddSpace(alloc_space_);
862 have_zygote_space_ = true;
863 break;
864 }
865 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700866
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700867 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700868 // TODO: C++0x
869 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
870 it != cumulative_timings_.end(); ++it) {
871 it->second->Reset();
872 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700873}
874
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700875void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700876 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
877 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700878 allocation_stack_->Reset();
879}
880
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700881size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700882 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700883}
884
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700885void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
886 Object** limit = stack->End();
887 for (Object** it = stack->Begin(); it != limit; ++it) {
888 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700889 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700890 if (LIKELY(bitmap->HasAddress(obj))) {
891 bitmap->Set(obj);
892 } else {
893 large_objects->Set(obj);
894 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700895 }
896}
897
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700898void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
899 Object** limit = stack->End();
900 for (Object** it = stack->Begin(); it != limit; ++it) {
901 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700902 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700903 if (LIKELY(bitmap->HasAddress(obj))) {
904 bitmap->Clear(obj);
905 } else {
906 large_objects->Clear(obj);
907 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700908 }
909}
910
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700911GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700912 Thread* self = Thread::Current();
913 Locks::mutator_lock_->AssertNotHeld(self);
914 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700915
Ian Rogers120f1c72012-09-28 17:17:10 -0700916 if (self->IsHandlingStackOverflow()) {
917 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
918 }
919
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700920 // Ensure there is only one GC at a time.
921 bool start_collect = false;
922 while (!start_collect) {
923 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700924 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700925 if (!is_gc_running_) {
926 is_gc_running_ = true;
927 start_collect = true;
928 }
929 }
930 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700931 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700932 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
933 // Not doing at the moment to ensure soft references are cleared.
934 }
935 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700936 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700937
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700938 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
939 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
940 ++Thread::Current()->GetStats()->gc_for_alloc_count;
941 }
942
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700943 // We need to do partial GCs every now and then to avoid the heap growing too much and
944 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700945 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700946 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700947 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700948 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700949 sticky_gc_count_ = 0;
950 }
951
Mathieu Chartier637e3482012-08-17 10:41:32 -0700952 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700953 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700954 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700955 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700956 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700957 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700958
Ian Rogers15bf2d32012-08-28 17:33:04 -0700959 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700960 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700961 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700962 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700963 // Wake anyone who may have been waiting for the GC to complete.
964 gc_complete_cond_->Broadcast();
965 }
966 // Inform DDMS that a GC completed.
967 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700968 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700969}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700970
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700971void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
972 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700973 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700974
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700975 std::stringstream gc_type_str;
976 gc_type_str << gc_type << " ";
977
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700978 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700979 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700980 ThreadList* thread_list = Runtime::Current()->GetThreadList();
981 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700982 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700983 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700984
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700985 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700986 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700987 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700988 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700989 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700990 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700991
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700992 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700993 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700994 if (!VerifyHeapReferences()) {
995 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
996 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700997 timings.AddSplit("VerifyHeapReferencesPreGC");
998 }
999
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001001 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001002
1003 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1004 // TODO: Investigate using a mark stack instead of a vector.
1005 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001006 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001007 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1008 card_table_->GetDirtyCards(*it, dirty_cards);
1009 }
1010 }
1011
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001012 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001013 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001014
Ian Rogers120f1c72012-09-28 17:17:10 -07001015 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001016 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001017 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1018 // accidentally un-mark roots.
1019 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001020 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001021 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1022 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001023 }
1024 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001025 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001026
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001027 // We can assume that everything from the start of the first space to the alloc space is marked.
1028 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1029 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001030 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001031 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001032 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1033 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001034 }
1035 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001036 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001037 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001038 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001039 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1040 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001041 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001042 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001043
Carl Shapiro58551df2011-07-24 03:09:51 -07001044 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001045 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001046
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001047 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001048 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -07001049
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001050 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1051
1052 if (gc_type != kGcTypeSticky) {
1053 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1054 live_stack_.get());
1055 timings.AddSplit("MarkStackAsLive");
1056 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001057
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001058 if (verify_mod_union_table_) {
1059 zygote_mod_union_table_->Update();
1060 zygote_mod_union_table_->Verify();
1061 mod_union_table_->Update();
1062 mod_union_table_->Verify();
1063 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001064
1065 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001066 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001067 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001068 } else {
1069 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1070 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001071 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001072
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001073 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001074 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001075 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001076
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001077#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001078 // Verify that we only reach marked objects from the image space
1079 mark_sweep.VerifyImageRoots();
1080 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001081#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001082
Mathieu Chartier0325e622012-09-05 14:22:51 -07001083 if (gc_type != kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001084 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1085 timings.AddSplit("Sweep");
1086 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001087 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001088 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001089 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001090 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001091 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001092 live_stack_->Reset();
1093
1094 // Unbind the live and mark bitmaps.
1095 mark_sweep.UnBindBitmaps();
1096
1097 const bool swap = true;
1098 if (swap) {
1099 if (gc_type == kGcTypeSticky) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001100 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001101 } else {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001102 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001103 }
1104 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001105
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001106 if (verify_system_weaks_) {
1107 mark_sweep.VerifySystemWeaks();
1108 timings.AddSplit("VerifySystemWeaks");
1109 }
1110
Elliott Hughesadb460d2011-10-05 17:02:34 -07001111 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001112 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001113 total_bytes_freed_ += bytes_freed;
1114 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001115 }
1116
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001117 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001118 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001119 if (!VerifyHeapReferences()) {
1120 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1121 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001122 timings.AddSplit("VerifyHeapReferencesPostGC");
1123 }
1124
Carl Shapiro58551df2011-07-24 03:09:51 -07001125 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001126 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001127
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001128 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001129 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001130
1131 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001132 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001133 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001134
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001135 // If the GC was slow, then print timings in the log.
1136 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001137 total_paused_time_ += duration / kTimeAdjust;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001138 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001139 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001140 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001141 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001142 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001143 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001144 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001145 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001146 if (VLOG_IS_ON(heap)) {
1147 timings.Dump();
1148 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001149 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001150
Mathieu Chartier0325e622012-09-05 14:22:51 -07001151 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1152 logger->Start();
1153 logger->AddLogger(timings);
1154 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001155}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001156
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001157void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001158 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001159 // 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 -07001160 // cards.
1161 return;
1162 }
1163
1164 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001165 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001166 zygote_mod_union_table_->Update();
1167 timings.AddSplit("UpdateZygoteModUnionTable");
1168
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001169 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001170 timings.AddSplit("ZygoteMarkReferences");
1171 }
1172
1173 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1174 mod_union_table_->Update();
1175 timings.AddSplit("UpdateModUnionTable");
1176
1177 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001178 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001179 timings.AddSplit("MarkImageToAllocSpaceReferences");
1180}
1181
1182void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1183 Object* obj = reinterpret_cast<Object*>(arg);
1184 if (root == obj) {
1185 LOG(INFO) << "Object " << obj << " is a root";
1186 }
1187}
1188
1189class ScanVisitor {
1190 public:
1191 void operator ()(const Object* obj) const {
1192 LOG(INFO) << "Would have rescanned object " << obj;
1193 }
1194};
1195
1196class VerifyReferenceVisitor {
1197 public:
1198 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001199 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1200 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001201 : heap_(heap),
1202 failed_(failed) {
1203 }
1204
1205 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1206 // analysis.
1207 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1208 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1209 // Verify that the reference is live.
1210 if (ref != NULL && !IsLive(ref)) {
1211 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001212 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1213 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001214
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001215 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001216 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1217 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1218 << "Obj type " << PrettyTypeOf(obj) << "\n"
1219 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001220 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001221 void* cover_begin = card_table->AddrFromCard(card_addr);
1222 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001223 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001224 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001225 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001226 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1227
1228 // Print out how the object is live.
1229 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001230 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1231 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001232 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1233 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1234 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001235 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1236 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001237 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001238 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001239 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240 }
1241
1242 // Attempt to see if the card table missed the reference.
1243 ScanVisitor scan_visitor;
1244 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001245 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1246 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001247
1248 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001249 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001250 MarkSweep ms(mark_stack);
1251 ms.Init();
1252 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001253 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001254
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001255 // All the references should end up in the mark stack.
1256 ms.ScanRoot(obj);
1257 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001258 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001259 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001260 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001261 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001262 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001263 }
1264 }
1265 mark_stack->Reset();
1266
1267 // Search to see if any of the roots reference our object.
1268 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1269 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1270 *failed_ = true;
1271 }
1272 }
1273
1274 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1275 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1276 if (bitmap != NULL) {
1277 if (bitmap->Test(obj)) {
1278 return true;
1279 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001280 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001281 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001282 } else {
1283 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001284 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001285 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001286 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001287 // At this point we need to search the allocation since things in the live stack may get swept.
1288 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1289 return true;
1290 }
1291 // Not either in the live bitmap or allocation stack, so the object must be dead.
1292 return false;
1293 }
1294
1295 private:
1296 Heap* heap_;
1297 bool* failed_;
1298};
1299
1300class VerifyObjectVisitor {
1301 public:
1302 VerifyObjectVisitor(Heap* heap)
1303 : heap_(heap),
1304 failed_(false) {
1305
1306 }
1307
1308 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001309 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001310 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1311 MarkSweep::VisitObjectReferences(obj, visitor);
1312 }
1313
1314 bool Failed() const {
1315 return failed_;
1316 }
1317
1318 private:
1319 Heap* heap_;
1320 bool failed_;
1321};
1322
1323// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001324bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001325 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001326 // Lets sort our allocation stacks so that we can efficiently binary search them.
1327 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1328 std::sort(live_stack_->Begin(), live_stack_->End());
1329 // Perform the verification.
1330 VerifyObjectVisitor visitor(this);
1331 GetLiveBitmap()->Visit(visitor);
1332 // We don't want to verify the objects in the allocation stack since they themselves may be
1333 // pointing to dead objects if they are not reachable.
1334 if (visitor.Failed()) {
1335 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001336 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001337 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001338 return true;
1339}
1340
1341class VerifyReferenceCardVisitor {
1342 public:
1343 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1344 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1345 Locks::heap_bitmap_lock_)
1346 : heap_(heap),
1347 failed_(failed) {
1348 }
1349
1350 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1351 // analysis.
1352 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1353 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001354 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001355 CardTable* card_table = heap_->GetCardTable();
1356 // If the object is not dirty and it is referencing something in the live stack other than
1357 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001358 if (!card_table->AddrIsInCardTable(obj)) {
1359 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1360 *failed_ = true;
1361 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001362 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001363 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1364 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1365 LOG(ERROR) << "Object " << obj << " found in live stack";
1366 }
1367 if (heap_->GetLiveBitmap()->Test(obj)) {
1368 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1369 }
1370 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1371 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1372
1373 // Print which field of the object is dead.
1374 if (!obj->IsObjectArray()) {
1375 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1376 CHECK(klass != NULL);
1377 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1378 CHECK(fields != NULL);
1379 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1380 const Field* cur = fields->Get(i);
1381 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1382 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1383 << PrettyField(cur);
1384 break;
1385 }
1386 }
1387 } else {
1388 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1389 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1390 if (object_array->Get(i) == ref) {
1391 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1392 }
1393 }
1394 }
1395
1396 *failed_ = true;
1397 }
1398 }
1399 }
1400 }
1401
1402 private:
1403 Heap* heap_;
1404 bool* failed_;
1405};
1406
1407class VerifyLiveStackReferences {
1408 public:
1409 VerifyLiveStackReferences(Heap* heap)
1410 : heap_(heap),
1411 failed_(false) {
1412
1413 }
1414
1415 void operator ()(const Object* obj) const
1416 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1417 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1418 MarkSweep::VisitObjectReferences(obj, visitor);
1419 }
1420
1421 bool Failed() const {
1422 return failed_;
1423 }
1424
1425 private:
1426 Heap* heap_;
1427 bool failed_;
1428};
1429
1430bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001431 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001432
1433 VerifyLiveStackReferences visitor(this);
1434 GetLiveBitmap()->Visit(visitor);
1435
1436 // We can verify objects in the live stack since none of these should reference dead objects.
1437 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1438 visitor(*it);
1439 }
1440
1441 if (visitor.Failed()) {
1442 DumpSpaces();
1443 return false;
1444 }
1445 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001446}
1447
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001448void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001449 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001450 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1451 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001452 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1453 ContinuousSpace* space = *it;
1454 // We never allocate into zygote spaces.
1455 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1456 (gc_type == kGcTypeFull &&
1457 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
1458 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1459 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1460 space->AsAllocSpace()->SwapBitmaps();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001461 }
1462 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001463 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001464}
1465
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001466void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001467 large_object_space_->SwapBitmaps();
1468 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1469 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001470}
1471
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001472void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001473 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001474 allocation_stack_.reset(live_stack_.release());
1475 live_stack_.reset(temp);
1476
1477 // Sort the live stack so that we can quickly binary search it later.
1478 if (VERIFY_OBJECT_ENABLED) {
1479 std::sort(live_stack_->Begin(), live_stack_->End());
1480 }
1481}
1482
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001483void Heap::ClearCards(TimingLogger& timings) {
1484 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1485 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1486 ContinuousSpace* space = *it;
1487 if (space->IsImageSpace()) {
1488 mod_union_table_->ClearCards(*it);
1489 timings.AddSplit("ModUnionClearCards");
1490 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1491 zygote_mod_union_table_->ClearCards(space);
1492 timings.AddSplit("ZygoteModUnionClearCards");
1493 } else {
1494 card_table_->ClearSpaceCards(space);
1495 timings.AddSplit("ClearCards");
1496 }
1497 }
1498}
1499
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001500void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1501 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001502 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1503 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001504 std::stringstream gc_type_str;
1505 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001506
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001507 // Suspend all threads are get exclusive access to the heap.
1508 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1509 thread_list->SuspendAll();
1510 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001511 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001512
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001513 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001514 Object* cleared_references = NULL;
1515 {
1516 MarkSweep mark_sweep(mark_stack_.get());
1517 timings.AddSplit("ctor");
1518
1519 mark_sweep.Init();
1520 timings.AddSplit("Init");
1521
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001522 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001523 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001524 if (!VerifyHeapReferences()) {
1525 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1526 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001527 timings.AddSplit("VerifyHeapReferencesPreGC");
1528 }
1529
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001530 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1531 SwapStacks();
1532
1533 // Check that all objects which reference things in the live stack are on dirty cards.
1534 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001535 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001536 // Sort the live stack so that we can quickly binary search it later.
1537 std::sort(live_stack_->Begin(), live_stack_->End());
1538 if (!VerifyMissingCardMarks()) {
1539 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1540 }
1541 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001542
1543 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1544 // TODO: Investigate using a mark stack instead of a vector.
1545 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001546 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001547 dirty_cards.reserve(4 * KB);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001548 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1549 card_table_->GetDirtyCards(*it, dirty_cards);
1550 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001551 timings.AddSplit("GetDirtyCards");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001552 }
1553
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001554 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001555 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001558 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001559
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001560 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001561 DCHECK(!GetLiveBitmap()->Test(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001562 }
1563
Mathieu Chartier0325e622012-09-05 14:22:51 -07001564 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001565 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1566 // accidentally un-mark roots.
1567 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001568 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001569 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1570 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001571 }
1572 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001573 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001574 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1575 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001576 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001577 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001578 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1579 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001580 }
1581 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001582 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001583 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001584 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001585 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1586 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001587 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001588 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001589
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001590 // Marking roots is not necessary for sticky mark bits since we only actually require the
1591 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001592 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001593 mark_sweep.MarkRoots();
1594 timings.AddSplit("MarkRoots");
1595 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001596
1597 if (verify_mod_union_table_) {
1598 zygote_mod_union_table_->Update();
1599 zygote_mod_union_table_->Verify();
1600 mod_union_table_->Update();
1601 mod_union_table_->Verify();
1602 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001603 }
1604
1605 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001606 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001607
1608 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1609 thread_list->ResumeAll();
1610 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001611 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001612 root_end = NanoTime();
1613 timings.AddSplit("RootEnd");
1614
Ian Rogers81d425b2012-09-27 16:03:43 -07001615 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001616 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001617
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001618 if (gc_type != kGcTypeSticky) {
1619 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1620 // knowing that new allocations won't be marked as live.
1621 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1622 live_stack_.get());
1623 timings.AddSplit("MarkStackAsLive");
1624 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001625
Mathieu Chartier0325e622012-09-05 14:22:51 -07001626 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001627 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001628 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001629 } else {
1630 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001631 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001632 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001633 }
1634 // Release share on mutator_lock_ and then get exclusive access.
1635 dirty_begin = NanoTime();
1636 thread_list->SuspendAll();
1637 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001638 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001639
1640 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001641 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001642
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001643 // Re-mark root set.
1644 mark_sweep.ReMarkRoots();
1645 timings.AddSplit("ReMarkRoots");
1646
1647 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001648 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001649 timings.AddSplit("RecursiveMarkDirtyObjects");
1650 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001651
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001652 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001653 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001654
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655 mark_sweep.ProcessReferences(clear_soft_references);
1656 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001657 }
1658
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001659 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1660 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001661 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001662 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001663 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001664 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001665 // We only sweep over the live stack, and the live stack should not intersect with the
1666 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001667 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1668 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001669 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001670#ifndef NDEBUG
1671 if (gc_type == kGcTypeSticky) {
1672 // Make sure everything in the live stack isn't something we unmarked.
1673 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1674 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001675 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1676 << "Unmarked object " << *it << " in the live stack";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001677 }
1678 } else {
1679 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001680 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001681 }
1682 }
1683#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001684 }
1685
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001686 if (kIsDebugBuild) {
1687 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001688 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001689 mark_sweep.VerifyImageRoots();
1690 timings.AddSplit("VerifyImageRoots");
1691 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001692
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001693 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001694 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1695 SwapBitmaps(gc_type);
1696 if (!VerifyHeapReferences()) {
1697 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001698 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001699 SwapBitmaps(gc_type);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001700 timings.AddSplit("VerifyHeapReferencesPostGC");
1701 }
1702
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001703 thread_list->ResumeAll();
1704 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001705 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001706
1707 {
1708 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001709 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001710 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001711 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1712 timings.AddSplit("Sweep");
1713 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001714 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001715 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001716 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001717 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001718 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001719 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001720 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001721 }
1722
1723 {
1724 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1725 // Unbind the live and mark bitmaps.
1726 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001727
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001728 // Swap the live and mark bitmaps for each space which we modified space. This is an
1729 // optimization that enables us to not clear live bits inside of the sweep.
1730 const bool swap = true;
1731 if (swap) {
1732 if (gc_type == kGcTypeSticky) {
1733 SwapLargeObjects();
1734 } else {
1735 SwapBitmaps(gc_type);
1736 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001737 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001738 }
1739
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001740 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001741 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001742 mark_sweep.VerifySystemWeaks();
1743 timings.AddSplit("VerifySystemWeaks");
1744 }
1745
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001746 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001747 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001748 total_bytes_freed_ += bytes_freed;
1749 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001750 }
1751
1752 GrowForUtilization();
1753 timings.AddSplit("GrowForUtilization");
1754
1755 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001756 timings.AddSplit("EnqueueClearedReferences");
1757
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001758 RequestHeapTrim();
1759 timings.AddSplit("Finish");
1760
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001761 // If the GC was slow, then print timings in the log.
1762 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1763 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001764 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001765 total_paused_time_ += (pause_roots + pause_dirty) / kTimeAdjust;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001766 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001767 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001768 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001769 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001770 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001771 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001772 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001773 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1774 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001775 if (VLOG_IS_ON(heap)) {
1776 timings.Dump();
1777 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001778 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001779
Mathieu Chartier0325e622012-09-05 14:22:51 -07001780 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1781 logger->Start();
1782 logger->AddLogger(timings);
1783 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001784}
1785
Ian Rogers81d425b2012-09-27 16:03:43 -07001786GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001787 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001788 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001789 bool do_wait;
1790 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001791 {
1792 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001793 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001794 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001795 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001796 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001797 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001798 // We must wait, change thread state then sleep on gc_complete_cond_;
1799 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1800 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001801 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001802 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001803 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001804 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001805 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001806 wait_time = NanoTime() - wait_start;;
1807 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001809 if (wait_time > MsToNs(5)) {
1810 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1811 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001812 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001813 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001814 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001815}
1816
Elliott Hughesc967f782012-04-16 10:23:15 -07001817void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001818 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1819 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001820 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001821}
1822
1823size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001824 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001825}
1826
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001827void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001828 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001829 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001830 << PrettySize(GetMaxMemory());
1831 max_allowed_footprint = GetMaxMemory();
1832 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001833 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001834}
1835
Ian Rogers3bb17a62012-01-27 23:56:44 -08001836// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001837static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001838// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1839// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001840static const size_t kHeapMinFree = kHeapIdealFree / 4;
1841
Carl Shapiro69759ea2011-07-21 18:13:35 -07001842void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001843 // We know what our utilization is at this moment.
1844 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1845 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
1846 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1847 target_size = num_bytes_allocated_ + kHeapIdealFree;
1848 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1849 target_size = num_bytes_allocated_ + kHeapMinFree;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001850 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001851
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001852 // Calculate when to perform the next ConcurrentGC.
1853 if (GetFreeMemory() < concurrent_min_free_) {
1854 // Not enough free memory to perform concurrent GC.
1855 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1856 } else {
1857 // Start a concurrent Gc when we get close to the target size.
1858 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001859 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001860
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001861 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001862}
1863
jeffhaoc1160702011-10-27 15:48:45 -07001864void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001865 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001866 alloc_space_->ClearGrowthLimit();
1867}
1868
Elliott Hughesadb460d2011-10-05 17:02:34 -07001869void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001870 MemberOffset reference_queue_offset,
1871 MemberOffset reference_queueNext_offset,
1872 MemberOffset reference_pendingNext_offset,
1873 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001874 reference_referent_offset_ = reference_referent_offset;
1875 reference_queue_offset_ = reference_queue_offset;
1876 reference_queueNext_offset_ = reference_queueNext_offset;
1877 reference_pendingNext_offset_ = reference_pendingNext_offset;
1878 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1879 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1880 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1881 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1882 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1883 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1884}
1885
1886Object* Heap::GetReferenceReferent(Object* reference) {
1887 DCHECK(reference != NULL);
1888 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1889 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1890}
1891
1892void Heap::ClearReferenceReferent(Object* reference) {
1893 DCHECK(reference != NULL);
1894 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1895 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1896}
1897
1898// Returns true if the reference object has not yet been enqueued.
1899bool Heap::IsEnqueuable(const Object* ref) {
1900 DCHECK(ref != NULL);
1901 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1902 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1903 return (queue != NULL) && (queue_next == NULL);
1904}
1905
1906void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1907 DCHECK(ref != NULL);
1908 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1909 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1910 EnqueuePendingReference(ref, cleared_reference_list);
1911}
1912
1913void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1914 DCHECK(ref != NULL);
1915 DCHECK(list != NULL);
1916
1917 if (*list == NULL) {
1918 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1919 *list = ref;
1920 } else {
1921 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1922 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1923 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1924 }
1925}
1926
1927Object* Heap::DequeuePendingReference(Object** list) {
1928 DCHECK(list != NULL);
1929 DCHECK(*list != NULL);
1930 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1931 Object* ref;
1932 if (*list == head) {
1933 ref = *list;
1934 *list = NULL;
1935 } else {
1936 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1937 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1938 ref = head;
1939 }
1940 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1941 return ref;
1942}
1943
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001944void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001945 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001946 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001947 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001948 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1949 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001950}
1951
1952size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001953 return num_bytes_allocated_;
1954}
1955
1956size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001957 size_t total = 0;
1958 // TODO: C++0x
1959 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1960 Space* space = *it;
1961 if (space->IsAllocSpace()) {
1962 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1963 }
1964 }
1965 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001966}
1967
1968size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001969 return concurrent_start_size_;
1970}
1971
1972size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001973 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001974}
1975
1976void Heap::EnqueueClearedReferences(Object** cleared) {
1977 DCHECK(cleared != NULL);
1978 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001979 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001980 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001981 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001982 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1983 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001984 *cleared = NULL;
1985 }
1986}
1987
Ian Rogers1f539342012-10-03 21:09:42 -07001988void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001989 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001990 Runtime* runtime = Runtime::Current();
1991 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1992 !runtime->IsConcurrentGcEnabled()) {
1993 return;
1994 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001995 {
1996 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1997 if (runtime->IsShuttingDown()) {
1998 return;
1999 }
2000 }
2001 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002002 return;
2003 }
2004
2005 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07002006 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002007 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2008 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002009 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2010 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002011 CHECK(!env->ExceptionCheck());
2012 requesting_gc_ = false;
2013}
2014
Ian Rogers81d425b2012-09-27 16:03:43 -07002015void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002016 {
2017 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2018 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2019 return;
2020 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002021 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002022
Ian Rogers81d425b2012-09-27 16:03:43 -07002023 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002024 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002025 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002026 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002027 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002028 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002029 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002030 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002031 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002032}
2033
Ian Rogers81d425b2012-09-27 16:03:43 -07002034void Heap::Trim(Thread* self) {
2035 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002036 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002037}
2038
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002039void Heap::RequestHeapTrim() {
2040 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2041 // because that only marks object heads, so a large array looks like lots of empty space. We
2042 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2043 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2044 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2045 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002046 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002047 float utilization =
2048 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2049 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2050 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2051 // heap trim occurred in the last two seconds.
2052 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002053 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002054
2055 Thread* self = Thread::Current();
2056 {
2057 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2058 Runtime* runtime = Runtime::Current();
2059 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2060 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2061 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2062 // as we don't hold the lock while requesting the trim).
2063 return;
2064 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002065 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002066 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002067 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002068 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2069 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002070 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2071 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002072 CHECK(!env->ExceptionCheck());
2073}
2074
Carl Shapiro69759ea2011-07-21 18:13:35 -07002075} // namespace art