blob: 40037e34af14e922973b27e68347932c6b7a914d [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 Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
Ian Rogers48931882013-01-22 14:35:16 -080026#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070027#include "debugger.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070028#include "gc/atomic_stack.h"
29#include "gc/card_table.h"
30#include "gc/heap_bitmap.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070031#include "gc/large_object_space.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070032#include "gc/mark_sweep.h"
Mathieu Chartier2b82db42012-11-14 17:29:05 -080033#include "gc/partial_mark_sweep.h"
34#include "gc/sticky_mark_sweep.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070035#include "gc/mod_union_table.h"
36#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070037#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080039#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080040#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070041#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070042#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070043#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070044#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070045#include "timing_logger.h"
46#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070047#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070048
49namespace art {
50
Mathieu Chartier2b82db42012-11-14 17:29:05 -080051static const uint64_t kSlowGcThreshold = MsToNs(100);
52static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080053static const bool kDumpGcPerformanceOnShutdown = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070054const double Heap::kDefaultTargetUtilization = 0.5;
55
Elliott Hughesae80b492012-04-24 10:43:17 -070056static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080057 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080058 std::vector<std::string> boot_class_path;
59 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070060 if (boot_class_path.empty()) {
61 LOG(FATAL) << "Failed to generate image because no boot class path specified";
62 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080063
64 std::vector<char*> arg_vector;
65
66 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070067 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080068 const char* dex2oat = dex2oat_string.c_str();
69 arg_vector.push_back(strdup(dex2oat));
70
71 std::string image_option_string("--image=");
72 image_option_string += image_file_name;
73 const char* image_option = image_option_string.c_str();
74 arg_vector.push_back(strdup(image_option));
75
76 arg_vector.push_back(strdup("--runtime-arg"));
77 arg_vector.push_back(strdup("-Xms64m"));
78
79 arg_vector.push_back(strdup("--runtime-arg"));
80 arg_vector.push_back(strdup("-Xmx64m"));
81
82 for (size_t i = 0; i < boot_class_path.size(); i++) {
83 std::string dex_file_option_string("--dex-file=");
84 dex_file_option_string += boot_class_path[i];
85 const char* dex_file_option = dex_file_option_string.c_str();
86 arg_vector.push_back(strdup(dex_file_option));
87 }
88
89 std::string oat_file_option_string("--oat-file=");
90 oat_file_option_string += image_file_name;
91 oat_file_option_string.erase(oat_file_option_string.size() - 3);
92 oat_file_option_string += "oat";
93 const char* oat_file_option = oat_file_option_string.c_str();
94 arg_vector.push_back(strdup(oat_file_option));
95
jeffhao8161c032012-10-31 15:50:00 -070096 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
97 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -080098
Elliott Hughes48436bb2012-02-07 15:23:28 -080099 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800100 LOG(INFO) << command_line;
101
Elliott Hughes48436bb2012-02-07 15:23:28 -0800102 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800103 char** argv = &arg_vector[0];
104
105 // fork and exec dex2oat
106 pid_t pid = fork();
107 if (pid == 0) {
108 // no allocation allowed between fork and exec
109
110 // change process groups, so we don't get reaped by ProcessManager
111 setpgid(0, 0);
112
113 execv(dex2oat, argv);
114
115 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
116 return false;
117 } else {
118 STLDeleteElements(&arg_vector);
119
120 // wait for dex2oat to finish
121 int status;
122 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
123 if (got_pid != pid) {
124 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
125 return false;
126 }
127 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
128 LOG(ERROR) << dex2oat << " failed: " << command_line;
129 return false;
130 }
131 }
132 return true;
133}
134
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700135void Heap::UnReserveOatFileAddressRange() {
136 oat_file_map_.reset(NULL);
137}
138
Mathieu Chartier0051be62012-10-12 17:47:11 -0700139Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
140 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700141 const std::string& original_image_file_name, bool concurrent_gc)
142 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800143 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700144 concurrent_gc_(concurrent_gc),
145 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800146 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700147 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700148 enforce_heap_growth_rate_(false),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800149 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700150 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700151 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700152 concurrent_start_size_(128 * KB),
153 concurrent_min_free_(256 * KB),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800154 concurrent_start_bytes_(concurrent_gc ? initial_size - concurrent_start_size_ :
155 std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700156 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700157 total_bytes_freed_(0),
158 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700159 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800160 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700161 verify_missing_card_marks_(false),
162 verify_system_weaks_(false),
163 verify_pre_gc_heap_(false),
164 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700165 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700166 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700167 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700168 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700169 last_trim_time_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800170 allocation_rate_(0),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700171 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800172 reference_referent_offset_(0),
173 reference_queue_offset_(0),
174 reference_queueNext_offset_(0),
175 reference_pendingNext_offset_(0),
176 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700177 min_free_(min_free),
178 max_free_(max_free),
179 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700180 total_wait_time_(0),
181 measure_allocation_time_(false),
182 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700183 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800184 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800185 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700186 }
187
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700188 live_bitmap_.reset(new HeapBitmap(this));
189 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700190
Ian Rogers30fab402012-01-23 15:43:46 -0800191 // Requested begin for the alloc space, to follow the mapped image and oat files
192 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800193 std::string image_file_name(original_image_file_name);
194 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700195 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700196
Brian Carlstrom5643b782012-02-05 12:32:53 -0800197 if (OS::FileExists(image_file_name.c_str())) {
198 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700199 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800200 } else {
201 // If the /system file didn't exist, we need to use one from the art-cache.
202 // If the cache file exists, try to open, but if it fails, regenerate.
203 // If it does not exist, generate.
204 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
205 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700206 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800207 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700208 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700209 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700210 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800211 }
212 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700213
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700214 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700215 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800216 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
217 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700218 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
219 CHECK_GT(oat_end_addr, image_space->End());
220
221 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
222 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
223 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
224 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
225 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800226 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700227
Ian Rogers30fab402012-01-23 15:43:46 -0800228 if (oat_end_addr > requested_begin) {
229 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700230 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700231 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700232 }
233
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700234 // Allocate the large object space.
235 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700236 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
237 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
238
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700239 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
240 growth_limit, capacity,
241 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700242 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700243 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700244 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700245 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700246
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700247 // Spaces are sorted in order of Begin().
248 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700249 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
250 if (spaces_.back()->IsAllocSpace()) {
251 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
252 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700253
Ian Rogers30fab402012-01-23 15:43:46 -0800254 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700255 // TODO: C++0x
256 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
257 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800258 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700259 ImageSpace* image_space = space->AsImageSpace();
260 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800261 }
262 }
263
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800264 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700265 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
266 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700267
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700268 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
269 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700270
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700271 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
272 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700273
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700274 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700275 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700276
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800277 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700278 static const size_t default_mark_stack_size = 64 * KB;
279 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
280 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700281 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700282 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
283 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700284
Mathieu Chartier65db8802012-11-20 12:36:46 -0800285 // It's still too early to take a lock because there are no threads yet, but we can create locks
286 // now. We don't create it earlier to make it clear that you can't use locks during heap
287 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700288 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700289 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
290 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700291
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700292 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
293 reference_queue_lock_.reset(new Mutex("reference queue lock"));
294
Mathieu Chartier65db8802012-11-20 12:36:46 -0800295 last_gc_time_ = NanoTime();
296 last_gc_size_ = GetBytesAllocated();
297
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800298 // Create our garbage collectors.
299 for (size_t i = 0; i < 2; ++i) {
300 const bool concurrent = i != 0;
301 mark_sweep_collectors_.push_back(new MarkSweep(this, concurrent));
302 mark_sweep_collectors_.push_back(new PartialMarkSweep(this, concurrent));
303 mark_sweep_collectors_.push_back(new StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700304 }
305
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800306 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800307 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800308 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700309 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700310}
311
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700312void Heap::CreateThreadPool() {
313 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
314 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
315 // workers to complete.
316 thread_pool_.reset(new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
317}
318
319void Heap::DeleteThreadPool() {
320 thread_pool_.reset(NULL);
321}
322
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700323// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700324struct SpaceSorter {
325 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700326 return a->Begin() < b->Begin();
327 }
328};
329
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700330void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700331 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700332 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700333 DCHECK(space->GetLiveBitmap() != NULL);
334 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700335 DCHECK(space->GetMarkBitmap() != NULL);
336 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800337 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700338 if (space->IsAllocSpace()) {
339 alloc_space_ = space->AsAllocSpace();
340 }
341
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700342 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
343 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700344
345 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
346 // avoid redundant marking.
347 bool seen_zygote = false, seen_alloc = false;
348 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
349 Space* space = *it;
350 if (space->IsImageSpace()) {
351 DCHECK(!seen_zygote);
352 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700353 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700354 DCHECK(!seen_alloc);
355 seen_zygote = true;
356 } else if (space->IsAllocSpace()) {
357 seen_alloc = true;
358 }
359 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800360}
361
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700362void Heap::DumpGcPerformanceInfo() {
363 // Dump cumulative timings.
364 LOG(INFO) << "Dumping cumulative Gc timings";
365 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800366
367 // Dump cumulative loggers for each GC type.
368 // TODO: C++0x
369 uint64_t total_paused_time = 0;
370 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
371 it != mark_sweep_collectors_.end(); ++it) {
372 MarkSweep* collector = *it;
373 const CumulativeLogger& logger = collector->GetCumulativeTimings();
374 if (logger.GetTotalNs() != 0) {
375 logger.Dump();
376 const uint64_t total_ns = logger.GetTotalNs();
377 const uint64_t total_pause_ns = (*it)->GetTotalPausedTime();
378 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
379 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
380 const uint64_t freed_objects = collector->GetTotalFreedObjects();
381 LOG(INFO)
382 << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
383 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
384 << collector->GetName() << " freed: " << freed_objects
385 << " objects with total size " << PrettySize(freed_bytes) << "\n"
386 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
387 << PrettySize(freed_bytes / seconds) << "/s\n";
388 total_duration += total_ns;
389 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700390 }
391 }
392 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
393 size_t total_objects_allocated = GetTotalObjectsAllocated();
394 size_t total_bytes_allocated = GetTotalBytesAllocated();
395 if (total_duration != 0) {
396 const double total_seconds = double(total_duration / 1000) / 1000000.0;
397 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
398 LOG(INFO) << "Mean GC size throughput: "
399 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
Elliott Hughes80537bb2013-01-04 16:37:26 -0800400 LOG(INFO) << "Mean GC object throughput: "
401 << (GetTotalObjectsFreed() / total_seconds) << " objects/s";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700402 }
403 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
404 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
405 if (measure_allocation_time_) {
406 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
407 LOG(INFO) << "Mean allocation time: "
408 << PrettyDuration(allocation_time / total_objects_allocated);
409 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800410 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time);
Elliott Hughes80537bb2013-01-04 16:37:26 -0800411 LOG(INFO) << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700412}
413
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800414Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700415 if (kDumpGcPerformanceOnShutdown) {
416 DumpGcPerformanceInfo();
417 }
418
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800419 STLDeleteElements(&mark_sweep_collectors_);
420
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700421 // If we don't reset then the mark stack complains in it's destructor.
422 allocation_stack_->Reset();
423 live_stack_->Reset();
424
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800425 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800426 // We can't take the heap lock here because there might be a daemon thread suspended with the
427 // heap lock held. We know though that no non-daemon threads are executing, and we know that
428 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
429 // 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 -0700430 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700431 delete gc_complete_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700432}
433
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700434ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700435 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700436 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
437 if ((*it)->Contains(obj)) {
438 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700439 }
440 }
441 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
442 return NULL;
443}
444
445ImageSpace* Heap::GetImageSpace() {
446 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700447 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
448 if ((*it)->IsImageSpace()) {
449 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700450 }
451 }
452 return NULL;
453}
454
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700455DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700456 return alloc_space_;
457}
458
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700459static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700460 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700461 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700462 size_t chunk_free_bytes = chunk_size - used_bytes;
463 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
464 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700465 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700466}
467
Ian Rogers50b35e22012-10-04 10:09:15 -0700468Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
470 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
471 strlen(ClassHelper(c).GetDescriptor()) == 0);
472 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700473
474 Object* obj = NULL;
475 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700476 uint64_t allocation_start = 0;
477 if (measure_allocation_time_) {
478 allocation_start = NanoTime();
479 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700480
481 // We need to have a zygote space or else our newly allocated large object can end up in the
482 // Zygote resulting in it being prematurely freed.
483 // We can only do this for primive objects since large objects will not be within the card table
484 // range. This also means that we rely on SetClass not dirtying the object's card.
485 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700486 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700487 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700488 // Make sure that our large object didn't get placed anywhere within the space interval or else
489 // it breaks the immune range.
490 DCHECK(obj == NULL ||
491 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
492 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700493 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700494 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700495
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700496 // Ensure that we did not allocate into a zygote space.
497 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
498 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700499 }
500
Mathieu Chartier037813d2012-08-23 16:44:59 -0700501 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700502 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700503
504 // Record allocation after since we want to use the atomic add for the atomic fence to guard
505 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700506 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700507
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700508 if (Dbg::IsAllocTrackingEnabled()) {
509 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700510 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700511 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700512 // We already have a request pending, no reason to start more until we update
513 // concurrent_start_bytes_.
514 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700515 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700516 SirtRef<Object> ref(self, obj);
517 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700518 }
519 VerifyObject(obj);
520
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700521 if (measure_allocation_time_) {
522 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
523 }
524
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700525 return obj;
526 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800527 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700528 int64_t total_bytes_free = GetFreeMemory();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800529 uint64_t alloc_space_size = alloc_space_->GetNumBytesAllocated();
530 uint64_t large_object_size = large_object_space_->GetNumObjectsAllocated();
531 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
532 << " free bytes; allocation space size " << alloc_space_size
533 << "; large object space size " << large_object_size;
534 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
535 if (total_bytes_free >= byte_count) {
536 size_t max_contiguous_allocation = 0;
537 // TODO: C++0x auto
538 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
539 if ((*it)->IsAllocSpace()) {
540 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
541 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700542 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800543 oss << "; failed due to fragmentation (largest possible contiguous allocation "
544 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700545 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800546 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700547 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700548}
549
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700550bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700551 // Note: we deliberately don't take the lock here, and mustn't test anything that would
552 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700553 if (obj == NULL) {
554 return true;
555 }
556 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700557 return false;
558 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800559 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800560 if (spaces_[i]->Contains(obj)) {
561 return true;
562 }
563 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700564 // Note: Doing this only works for the free list version of the large object space since the
565 // multiple memory map version uses a lock to do the contains check.
566 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700567}
568
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700569bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700570 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700571 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700572}
573
Elliott Hughes3e465b12011-09-02 18:26:12 -0700574#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700575void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700576 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700577 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700578 return;
579 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700580 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700581}
582#endif
583
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700584void Heap::DumpSpaces() {
585 // TODO: C++0x auto
586 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700587 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700588 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
589 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
590 LOG(INFO) << space << " " << *space << "\n"
591 << live_bitmap << " " << *live_bitmap << "\n"
592 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700593 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700594 if (large_object_space_.get() != NULL) {
595 large_object_space_->Dump(LOG(INFO));
596 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700597}
598
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700599void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700600 if (!IsAligned<kObjectAlignment>(obj)) {
601 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700602 }
603
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700604 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
605 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700606 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700607 // Check the allocation stack / live stack.
608 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
609 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
610 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700611 if (large_object_space_->GetLiveObjects()->Test(obj)) {
612 DumpSpaces();
613 LOG(FATAL) << "Object is dead: " << obj;
614 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700615 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700616 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700617
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700618 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700619 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700620 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
621 Object::ClassOffset().Int32Value();
622 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
623 if (c == NULL) {
624 LOG(FATAL) << "Null class in object: " << obj;
625 } else if (!IsAligned<kObjectAlignment>(c)) {
626 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
627 } else if (!GetLiveBitmap()->Test(c)) {
628 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
629 }
630 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
631 // Note: we don't use the accessors here as they have internal sanity checks
632 // that we don't want to run
633 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
634 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
635 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
636 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
637 CHECK_EQ(c_c, c_c_c);
638 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700639}
640
Brian Carlstrom78128a62011-09-15 17:21:19 -0700641void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700642 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700643 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700644}
645
646void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700647 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700648 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649}
650
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700651void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700652 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700653 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700654 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700655
656 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700657 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700658 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700659 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700660
661 // TODO: Update these atomically.
662 RuntimeStats* global_stats = Runtime::Current()->GetStats();
663 ++global_stats->allocated_objects;
664 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700665 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700666
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700667 // This is safe to do since the GC will never free objects which are neither in the allocation
668 // stack or the live bitmap.
669 while (!allocation_stack_->AtomicPushBack(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700670 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700671 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700672}
673
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700674void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700675 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
676 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700677
678 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700679 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700680 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700681 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700682
683 // TODO: Do this concurrently.
684 RuntimeStats* global_stats = Runtime::Current()->GetStats();
685 global_stats->freed_objects += freed_objects;
686 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700687 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700688}
689
Ian Rogers50b35e22012-10-04 10:09:15 -0700690Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700691 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800692 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
693 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
694 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
695 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700696 return NULL;
697 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700698
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800699 if (enforce_heap_growth_rate_) {
700 if (grow) {
701 // Grow the heap by alloc_size extra bytes.
702 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
703 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
704 << " for a " << PrettySize(alloc_size) << " allocation";
705 } else {
706 return NULL;
707 }
708 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700709 }
710
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700711 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700712}
713
Ian Rogers50b35e22012-10-04 10:09:15 -0700714Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700715 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
716 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700717 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700718 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700719
Ian Rogers50b35e22012-10-04 10:09:15 -0700720 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700721 if (ptr != NULL) {
722 return ptr;
723 }
724
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700725 // The allocation failed. If the GC is running, block until it completes, and then retry the
726 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700727 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700728 if (last_gc != kGcTypeNone) {
729 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700730 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700731 if (ptr != NULL) {
732 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700733 }
734 }
735
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700736 // Loop through our different Gc types and try to Gc until we get enough free memory.
737 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
738 bool run_gc = false;
739 GcType gc_type = static_cast<GcType>(i);
740 switch (gc_type) {
741 case kGcTypeSticky: {
742 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700743 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
744 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700745 break;
746 }
747 case kGcTypePartial:
748 run_gc = have_zygote_space_;
749 break;
750 case kGcTypeFull:
751 run_gc = true;
752 break;
753 default:
754 break;
755 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700756
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700757 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700758 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700759 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800760 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700761 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700762
763 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700764 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700765 if (ptr != NULL) {
766 return ptr;
767 }
768 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700769 }
770
771 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700772 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700773 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700774 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700775 return ptr;
776 }
777
Elliott Hughes81ff3182012-03-23 20:35:56 -0700778 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
779 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
780 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700781
Elliott Hughes418dfe72011-10-06 18:56:27 -0700782 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700783 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
784 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700785
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700786 // We don't need a WaitForConcurrentGcToComplete here either.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700787 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700788 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700789}
790
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700791void Heap::SetTargetHeapUtilization(float target) {
792 DCHECK_GT(target, 0.0f); // asserted in Java code
793 DCHECK_LT(target, 1.0f);
794 target_utilization_ = target;
795}
796
797int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700798 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700799}
800
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700801int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700802 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700803}
804
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700805int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700806 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700807}
808
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700809size_t Heap::GetTotalBytesFreed() const {
810 return total_bytes_freed_;
811}
812
813size_t Heap::GetTotalObjectsFreed() const {
814 return total_objects_freed_;
815}
816
817size_t Heap::GetTotalObjectsAllocated() const {
818 size_t total = large_object_space_->GetTotalObjectsAllocated();
819 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
820 Space* space = *it;
821 if (space->IsAllocSpace()) {
822 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
823 }
824 }
825 return total;
826}
827
828size_t Heap::GetTotalBytesAllocated() const {
829 size_t total = large_object_space_->GetTotalBytesAllocated();
830 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
831 Space* space = *it;
832 if (space->IsAllocSpace()) {
833 total += space->AsAllocSpace()->GetTotalBytesAllocated();
834 }
835 }
836 return total;
837}
838
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700839class InstanceCounter {
840 public:
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800841 InstanceCounter(const std::vector<Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700842 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800843 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700844 }
845
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700846 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800847 for (size_t i = 0; i < classes_.size(); ++i) {
848 const Class* instance_class = o->GetClass();
849 if (use_is_assignable_from_) {
850 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
851 ++counts_[i];
852 }
853 } else {
854 if (instance_class == classes_[i]) {
855 ++counts_[i];
856 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700857 }
858 }
859 }
860
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700861 private:
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800862 const std::vector<Class*>& classes_;
863 bool use_is_assignable_from_;
864 uint64_t* const counts_;
865
866 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700867};
868
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800869void Heap::CountInstances(const std::vector<Class*>& classes, bool use_is_assignable_from,
870 uint64_t* counts) {
871 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
872 // is empty, so the live bitmap is the only place we need to look.
873 Thread* self = Thread::Current();
874 self->TransitionFromRunnableToSuspended(kNative);
875 CollectGarbage(false);
876 self->TransitionFromSuspendedToRunnable();
877
878 InstanceCounter counter(classes, use_is_assignable_from, counts);
879 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700880 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700881}
882
Elliott Hughes3b78c942013-01-15 17:35:41 -0800883class InstanceCollector {
884 public:
885 InstanceCollector(Class* c, int32_t max_count, std::vector<Object*>& instances)
886 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
887 : class_(c), max_count_(max_count), instances_(instances) {
888 }
889
890 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
891 const Class* instance_class = o->GetClass();
892 if (instance_class == class_) {
893 if (max_count_ == 0 || instances_.size() < max_count_) {
894 instances_.push_back(const_cast<Object*>(o));
895 }
896 }
897 }
898
899 private:
900 Class* class_;
901 uint32_t max_count_;
902 std::vector<Object*>& instances_;
903
904 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
905};
906
907void Heap::GetInstances(Class* c, int32_t max_count, std::vector<Object*>& instances) {
908 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
909 // is empty, so the live bitmap is the only place we need to look.
910 Thread* self = Thread::Current();
911 self->TransitionFromRunnableToSuspended(kNative);
912 CollectGarbage(false);
913 self->TransitionFromSuspendedToRunnable();
914
915 InstanceCollector collector(c, max_count, instances);
916 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
917 GetLiveBitmap()->Visit(collector);
918}
919
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800920class ReferringObjectsFinder {
921 public:
922 ReferringObjectsFinder(Object* object, int32_t max_count, std::vector<Object*>& referring_objects)
923 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
924 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
925 }
926
927 // For bitmap Visit.
928 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
929 // annotalysis on visitors.
930 void operator()(const Object* o) const NO_THREAD_SAFETY_ANALYSIS {
931 MarkSweep::VisitObjectReferences(o, *this);
932 }
933
934 // For MarkSweep::VisitObjectReferences.
935 void operator ()(const Object* referrer, const Object* object, const MemberOffset&, bool) const {
936 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
937 referring_objects_.push_back(const_cast<Object*>(referrer));
938 }
939 }
940
941 private:
942 Object* object_;
943 uint32_t max_count_;
944 std::vector<Object*>& referring_objects_;
945
946 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
947};
948
949void Heap::GetReferringObjects(Object* o, int32_t max_count,
950 std::vector<Object*>& referring_objects) {
951 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
952 // is empty, so the live bitmap is the only place we need to look.
953 Thread* self = Thread::Current();
954 self->TransitionFromRunnableToSuspended(kNative);
955 CollectGarbage(false);
956 self->TransitionFromSuspendedToRunnable();
957
958 ReferringObjectsFinder finder(o, max_count, referring_objects);
959 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
960 GetLiveBitmap()->Visit(finder);
961}
962
Ian Rogers30fab402012-01-23 15:43:46 -0800963void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700964 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
965 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700966 Thread* self = Thread::Current();
967 WaitForConcurrentGcToComplete(self);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700968 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700969}
970
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700971void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700972 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800973 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
974 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700975 Thread* self = Thread::Current();
976 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700977
978 // Try to see if we have any Zygote spaces.
979 if (have_zygote_space_) {
980 return;
981 }
982
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700983 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
984
985 {
986 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700987 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700988 FlushAllocStack();
989 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700990
991 // Replace the first alloc space we find with a zygote space.
992 // TODO: C++0x auto
993 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
994 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700995 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700996
997 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
998 // of the remaining available heap memory.
999 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001000 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001001
1002 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001003 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001004 AddSpace(alloc_space_);
1005 have_zygote_space_ = true;
1006 break;
1007 }
1008 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001009
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001010 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001011 // TODO: C++0x
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001012 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
1013 it != mark_sweep_collectors_.end(); ++it) {
1014 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001015 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001016}
1017
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001018void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001019 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1020 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001021 allocation_stack_->Reset();
1022}
1023
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001024size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001025 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001026}
1027
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001028void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
1029 Object** limit = stack->End();
1030 for (Object** it = stack->Begin(); it != limit; ++it) {
1031 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001032 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001033 if (LIKELY(bitmap->HasAddress(obj))) {
1034 bitmap->Set(obj);
1035 } else {
1036 large_objects->Set(obj);
1037 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001038 }
1039}
1040
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001041void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
1042 Object** limit = stack->End();
1043 for (Object** it = stack->Begin(); it != limit; ++it) {
1044 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001045 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001046 if (LIKELY(bitmap->HasAddress(obj))) {
1047 bitmap->Clear(obj);
1048 } else {
1049 large_objects->Clear(obj);
1050 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001051 }
1052}
1053
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001054GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001055 Thread* self = Thread::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001056 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001057 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001058
Ian Rogers120f1c72012-09-28 17:17:10 -07001059 if (self->IsHandlingStackOverflow()) {
1060 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1061 }
1062
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001063 // Ensure there is only one GC at a time.
1064 bool start_collect = false;
1065 while (!start_collect) {
1066 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001067 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001068 if (!is_gc_running_) {
1069 is_gc_running_ = true;
1070 start_collect = true;
1071 }
1072 }
1073 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001074 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001075 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1076 // Not doing at the moment to ensure soft references are cleared.
1077 }
1078 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001079 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001080
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001081 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1082 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1083 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1084 }
1085
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001086 // We need to do partial GCs every now and then to avoid the heap growing too much and
1087 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001088 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001089 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001090 }
Mathieu Chartier0325e622012-09-05 14:22:51 -07001091 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092 sticky_gc_count_ = 0;
1093 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001094
Mathieu Chartier65db8802012-11-20 12:36:46 -08001095 uint64_t gc_start_time = NanoTime();
1096 uint64_t gc_start_size = GetBytesAllocated();
1097 // Approximate allocation rate in bytes / second.
1098 DCHECK_NE(gc_start_time, last_gc_time_);
1099 uint64_t ms_delta = NsToMs(gc_start_time - last_gc_time_);
1100 if (ms_delta != 0) {
1101 allocation_rate_ = (gc_start_size - last_gc_size_) * 1000 / ms_delta;
1102 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1103 }
1104
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001105 DCHECK_LT(gc_type, kGcTypeMax);
1106 DCHECK_NE(gc_type, kGcTypeNone);
1107 MarkSweep* collector = NULL;
1108 for (Collectors::iterator it = mark_sweep_collectors_.begin();
1109 it != mark_sweep_collectors_.end(); ++it) {
1110 MarkSweep* cur_collector = *it;
1111 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1112 collector = cur_collector;
1113 break;
1114 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001115 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001116 CHECK(collector != NULL)
1117 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1118 << " and type=" << gc_type;
1119 collector->clear_soft_references_ = clear_soft_references;
1120 collector->Run();
1121 total_objects_freed_ += collector->GetFreedObjects();
1122 total_bytes_freed_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001123
Mathieu Chartier65db8802012-11-20 12:36:46 -08001124 const size_t duration = collector->GetDuration();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001125 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1126 bool was_slow = duration > kSlowGcThreshold ||
1127 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1128 for (size_t i = 0; i < pauses.size(); ++i) {
1129 if (pauses[i] > kLongGcPauseThreshold) {
1130 was_slow = true;
1131 }
1132 }
1133
1134 if (was_slow) {
1135 const size_t percent_free = GetPercentFree();
1136 const size_t current_heap_size = GetUsedMemorySize();
1137 const size_t total_memory = GetTotalMemory();
1138 std::ostringstream pause_string;
1139 for (size_t i = 0; i < pauses.size(); ++i) {
1140 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1141 << ((i != pauses.size() - 1) ? ", " : "");
1142 }
1143 LOG(INFO) << gc_cause << " " << collector->GetName()
1144 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1145 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1146 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1147 << " total " << PrettyDuration((duration / 1000) * 1000);
1148 if (VLOG_IS_ON(heap)) {
1149 collector->GetTimings().Dump();
1150 }
1151 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001152
Ian Rogers15bf2d32012-08-28 17:33:04 -07001153 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001154 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001155 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001156 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001157 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001158 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001159 }
1160 // Inform DDMS that a GC completed.
1161 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001162 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001163}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001164
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001165void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001166 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001167 // 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 -07001168 // cards.
1169 return;
1170 }
1171
1172 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001173 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001174 zygote_mod_union_table_->Update();
1175 timings.AddSplit("UpdateZygoteModUnionTable");
1176
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001177 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001178 timings.AddSplit("ZygoteMarkReferences");
1179 }
1180
1181 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1182 mod_union_table_->Update();
1183 timings.AddSplit("UpdateModUnionTable");
1184
1185 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001186 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001187 timings.AddSplit("MarkImageToAllocSpaceReferences");
1188}
1189
1190void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1191 Object* obj = reinterpret_cast<Object*>(arg);
1192 if (root == obj) {
1193 LOG(INFO) << "Object " << obj << " is a root";
1194 }
1195}
1196
1197class ScanVisitor {
1198 public:
1199 void operator ()(const Object* obj) const {
1200 LOG(INFO) << "Would have rescanned object " << obj;
1201 }
1202};
1203
1204class VerifyReferenceVisitor {
1205 public:
1206 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001207 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1208 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001209 : heap_(heap),
1210 failed_(failed) {
1211 }
1212
1213 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1214 // analysis.
1215 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1216 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1217 // Verify that the reference is live.
1218 if (ref != NULL && !IsLive(ref)) {
1219 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001220 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1221 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001222
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001223 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001224 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1225 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1226 << "Obj type " << PrettyTypeOf(obj) << "\n"
1227 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001228 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001229 void* cover_begin = card_table->AddrFromCard(card_addr);
1230 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001231 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001232 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001233 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001234 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1235
1236 // Print out how the object is live.
1237 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001238 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1239 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001240 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1241 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1242 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001243 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1244 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001245 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001246 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001247 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001248 }
1249
1250 // Attempt to see if the card table missed the reference.
1251 ScanVisitor scan_visitor;
1252 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001253 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001254 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001255
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001256 // Search to see if any of the roots reference our object.
1257 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1258 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1259 *failed_ = true;
1260 }
1261 }
1262
1263 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001264 if (heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001265 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001266 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001267 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001268 // At this point we need to search the allocation since things in the live stack may get swept.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001269 // If the object is not either in the live bitmap or allocation stack, so the object must be
1270 // dead.
1271 return std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001272 }
1273
1274 private:
1275 Heap* heap_;
1276 bool* failed_;
1277};
1278
1279class VerifyObjectVisitor {
1280 public:
1281 VerifyObjectVisitor(Heap* heap)
1282 : heap_(heap),
1283 failed_(false) {
1284
1285 }
1286
1287 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001288 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001289 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1290 MarkSweep::VisitObjectReferences(obj, visitor);
1291 }
1292
1293 bool Failed() const {
1294 return failed_;
1295 }
1296
1297 private:
1298 Heap* heap_;
1299 bool failed_;
1300};
1301
1302// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001303bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001304 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001305 // Lets sort our allocation stacks so that we can efficiently binary search them.
1306 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1307 std::sort(live_stack_->Begin(), live_stack_->End());
1308 // Perform the verification.
1309 VerifyObjectVisitor visitor(this);
1310 GetLiveBitmap()->Visit(visitor);
1311 // We don't want to verify the objects in the allocation stack since they themselves may be
1312 // pointing to dead objects if they are not reachable.
1313 if (visitor.Failed()) {
1314 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001315 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001316 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001317 return true;
1318}
1319
1320class VerifyReferenceCardVisitor {
1321 public:
1322 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1323 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1324 Locks::heap_bitmap_lock_)
1325 : heap_(heap),
1326 failed_(failed) {
1327 }
1328
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001329 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1330 // annotalysis on visitors.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001331 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1332 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001333 // Filter out class references since changing an object's class does not mark the card as dirty.
1334 // Also handles large objects, since the only reference they hold is a class reference.
1335 if (ref != NULL && !ref->IsClass()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001336 CardTable* card_table = heap_->GetCardTable();
1337 // If the object is not dirty and it is referencing something in the live stack other than
1338 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001339 if (!card_table->AddrIsInCardTable(obj)) {
1340 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1341 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001342 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001343 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1344 // kCardDirty - 1 if it didnt get touched since we aged it.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001345 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001346 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001347 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1348 LOG(ERROR) << "Object " << obj << " found in live stack";
1349 }
1350 if (heap_->GetLiveBitmap()->Test(obj)) {
1351 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1352 }
1353 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1354 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1355
1356 // Print which field of the object is dead.
1357 if (!obj->IsObjectArray()) {
1358 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1359 CHECK(klass != NULL);
1360 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1361 CHECK(fields != NULL);
1362 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1363 const Field* cur = fields->Get(i);
1364 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1365 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1366 << PrettyField(cur);
1367 break;
1368 }
1369 }
1370 } else {
1371 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1372 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1373 if (object_array->Get(i) == ref) {
1374 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1375 }
1376 }
1377 }
1378
1379 *failed_ = true;
1380 }
1381 }
1382 }
1383 }
1384
1385 private:
1386 Heap* heap_;
1387 bool* failed_;
1388};
1389
1390class VerifyLiveStackReferences {
1391 public:
1392 VerifyLiveStackReferences(Heap* heap)
1393 : heap_(heap),
1394 failed_(false) {
1395
1396 }
1397
1398 void operator ()(const Object* obj) const
1399 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1400 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1401 MarkSweep::VisitObjectReferences(obj, visitor);
1402 }
1403
1404 bool Failed() const {
1405 return failed_;
1406 }
1407
1408 private:
1409 Heap* heap_;
1410 bool failed_;
1411};
1412
1413bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001414 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001415
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001416 // We need to sort the live stack since we binary search it.
1417 std::sort(live_stack_->Begin(), live_stack_->End());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001418 VerifyLiveStackReferences visitor(this);
1419 GetLiveBitmap()->Visit(visitor);
1420
1421 // We can verify objects in the live stack since none of these should reference dead objects.
1422 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1423 visitor(*it);
1424 }
1425
1426 if (visitor.Failed()) {
1427 DumpSpaces();
1428 return false;
1429 }
1430 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001431}
1432
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001433void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001434 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001435
1436 // Sort the live stack so that we can quickly binary search it later.
1437 if (VERIFY_OBJECT_ENABLED) {
1438 std::sort(live_stack_->Begin(), live_stack_->End());
1439 }
1440}
1441
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001442void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001443 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1444 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1445 ContinuousSpace* space = *it;
1446 if (space->IsImageSpace()) {
1447 mod_union_table_->ClearCards(*it);
1448 timings.AddSplit("ModUnionClearCards");
1449 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1450 zygote_mod_union_table_->ClearCards(space);
1451 timings.AddSplit("ZygoteModUnionClearCards");
1452 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001453 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1454 // were dirty before the GC started.
1455 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1456 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001457 }
1458 }
1459}
1460
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001461void Heap::PreGcVerification(GarbageCollector* gc) {
1462 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1463 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001464
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001465 if (verify_pre_gc_heap_) {
1466 thread_list->SuspendAll();
1467 {
1468 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1469 if (!VerifyHeapReferences()) {
1470 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1471 }
1472 }
1473 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001474 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001475
1476 // Check that all objects which reference things in the live stack are on dirty cards.
1477 if (verify_missing_card_marks_) {
1478 thread_list->SuspendAll();
1479 {
1480 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1481 SwapStacks();
1482 // Sort the live stack so that we can quickly binary search it later.
1483 if (!VerifyMissingCardMarks()) {
1484 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1485 }
1486 SwapStacks();
1487 }
1488 thread_list->ResumeAll();
1489 }
1490
1491 if (verify_mod_union_table_) {
1492 thread_list->SuspendAll();
1493 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1494 zygote_mod_union_table_->Update();
1495 zygote_mod_union_table_->Verify();
1496 mod_union_table_->Update();
1497 mod_union_table_->Verify();
1498 thread_list->ResumeAll();
1499 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001500}
1501
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001502void Heap::PreSweepingGcVerification(GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001503 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001504 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001505
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001506 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1507 // reachable objects.
1508 if (verify_post_gc_heap_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001509 thread_list->SuspendAll();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001510 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1511 // Swapping bound bitmaps does nothing.
1512 live_bitmap_.swap(mark_bitmap_);
1513 if (!VerifyHeapReferences()) {
1514 LOG(FATAL) << "Post " << gc->GetName() << "Gc verification failed";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001515 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001516 live_bitmap_.swap(mark_bitmap_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001517 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001518 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001519}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001520
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001521void Heap::PostGcVerification(GarbageCollector* gc) {
1522 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001523
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001524 if (verify_system_weaks_) {
1525 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1526 MarkSweep* mark_sweep = down_cast<MarkSweep*>(gc);
1527 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001528 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001529}
1530
Ian Rogers81d425b2012-09-27 16:03:43 -07001531GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001532 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001533 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001534 bool do_wait;
1535 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001536 {
1537 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001538 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001539 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001540 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001541 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001542 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001543 // We must wait, change thread state then sleep on gc_complete_cond_;
1544 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1545 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001546 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001548 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001549 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001550 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001551 wait_time = NanoTime() - wait_start;;
1552 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001553 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001554 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001555 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1556 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001558 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001559 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001560}
1561
Elliott Hughesc967f782012-04-16 10:23:15 -07001562void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001563 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1564 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001565 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001566}
1567
1568size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001569 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001570}
1571
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001572void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001573 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001574 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001575 << PrettySize(GetMaxMemory());
1576 max_allowed_footprint = GetMaxMemory();
1577 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001578 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001579}
1580
Mathieu Chartier65db8802012-11-20 12:36:46 -08001581void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001582 // We know what our utilization is at this moment.
1583 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001584 const size_t bytes_allocated = GetBytesAllocated();
1585 last_gc_size_ = bytes_allocated;
1586 last_gc_time_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001587
Mathieu Chartier65db8802012-11-20 12:36:46 -08001588 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1589 if (target_size > bytes_allocated + max_free_) {
1590 target_size = bytes_allocated + max_free_;
1591 } else if (target_size < bytes_allocated + min_free_) {
1592 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001593 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001594
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001595 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001596
1597 // Calculate when to perform the next ConcurrentGC if we have enough free memory.
1598 if (concurrent_gc_ && GetFreeMemory() >= concurrent_min_free_) {
1599 // Calculate the estimated GC duration.
1600 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1601 // Estimate how many remaining bytes we will have when we need to start the next GC.
1602 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1603 if (remaining_bytes < max_allowed_footprint_) {
1604 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1605 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1606 // right away.
1607 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1608 } else {
1609 // The estimated rate is so high that we should request another GC straight away.
1610 concurrent_start_bytes_ = bytes_allocated;
1611 }
1612 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1613 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1614 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001615}
1616
jeffhaoc1160702011-10-27 15:48:45 -07001617void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001618 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001619 alloc_space_->ClearGrowthLimit();
1620}
1621
Elliott Hughesadb460d2011-10-05 17:02:34 -07001622void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001623 MemberOffset reference_queue_offset,
1624 MemberOffset reference_queueNext_offset,
1625 MemberOffset reference_pendingNext_offset,
1626 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001627 reference_referent_offset_ = reference_referent_offset;
1628 reference_queue_offset_ = reference_queue_offset;
1629 reference_queueNext_offset_ = reference_queueNext_offset;
1630 reference_pendingNext_offset_ = reference_pendingNext_offset;
1631 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1632 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1633 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1634 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1635 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1636 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1637}
1638
1639Object* Heap::GetReferenceReferent(Object* reference) {
1640 DCHECK(reference != NULL);
1641 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1642 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1643}
1644
1645void Heap::ClearReferenceReferent(Object* reference) {
1646 DCHECK(reference != NULL);
1647 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1648 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1649}
1650
1651// Returns true if the reference object has not yet been enqueued.
1652bool Heap::IsEnqueuable(const Object* ref) {
1653 DCHECK(ref != NULL);
1654 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1655 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1656 return (queue != NULL) && (queue_next == NULL);
1657}
1658
1659void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1660 DCHECK(ref != NULL);
1661 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1662 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1663 EnqueuePendingReference(ref, cleared_reference_list);
1664}
1665
1666void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1667 DCHECK(ref != NULL);
1668 DCHECK(list != NULL);
1669
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001670 // TODO: Remove this lock, use atomic stacks for storing references.
1671 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001672 if (*list == NULL) {
1673 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1674 *list = ref;
1675 } else {
1676 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1677 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1678 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1679 }
1680}
1681
1682Object* Heap::DequeuePendingReference(Object** list) {
1683 DCHECK(list != NULL);
1684 DCHECK(*list != NULL);
1685 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1686 Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001687
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001688 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1689 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001690 if (*list == head) {
1691 ref = *list;
1692 *list = NULL;
1693 } else {
1694 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1695 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1696 ref = head;
1697 }
1698 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1699 return ref;
1700}
1701
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001702void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001703 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001704 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001705 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001706 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1707 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001708}
1709
1710size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001711 return num_bytes_allocated_;
1712}
1713
1714size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001715 size_t total = 0;
1716 // TODO: C++0x
1717 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1718 Space* space = *it;
1719 if (space->IsAllocSpace()) {
1720 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1721 }
1722 }
1723 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001724}
1725
1726size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001727 return concurrent_start_size_;
1728}
1729
1730size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001731 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001732}
1733
1734void Heap::EnqueueClearedReferences(Object** cleared) {
1735 DCHECK(cleared != NULL);
1736 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001737 // When a runtime isn't started there are no reference queues to care about so ignore.
1738 if (LIKELY(Runtime::Current()->IsStarted())) {
1739 ScopedObjectAccess soa(Thread::Current());
1740 JValue args[1];
1741 args[0].SetL(*cleared);
1742 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1743 args, NULL);
1744 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001745 *cleared = NULL;
1746 }
1747}
1748
Ian Rogers1f539342012-10-03 21:09:42 -07001749void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001750 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001751 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001752 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001753 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001754 !runtime->IsConcurrentGcEnabled()) {
1755 return;
1756 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001757 {
1758 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1759 if (runtime->IsShuttingDown()) {
1760 return;
1761 }
1762 }
1763 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001764 return;
1765 }
1766
Ian Rogers120f1c72012-09-28 17:17:10 -07001767 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001768 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1769 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001770 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1771 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001772 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001773}
1774
Ian Rogers81d425b2012-09-27 16:03:43 -07001775void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001776 {
1777 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001778 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001779 return;
1780 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001781 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001782
Mathieu Chartier65db8802012-11-20 12:36:46 -08001783 // Wait for any GCs currently running to finish.
Ian Rogers81d425b2012-09-27 16:03:43 -07001784 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001785 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001786 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001787 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001788 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001789 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001790 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001791}
1792
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001793void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001794 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1795 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1796 // a space it will hold its lock and can become a cause of jank.
1797 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1798 // forking.
1799
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001800 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1801 // because that only marks object heads, so a large array looks like lots of empty space. We
1802 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1803 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1804 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1805 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001806 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001807 float utilization =
1808 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1809 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1810 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1811 // heap trim occurred in the last two seconds.
1812 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001813 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001814
1815 Thread* self = Thread::Current();
1816 {
1817 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1818 Runtime* runtime = Runtime::Current();
1819 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1820 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1821 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1822 // as we don't hold the lock while requesting the trim).
1823 return;
1824 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001825 }
Ian Rogers48931882013-01-22 14:35:16 -08001826
1827 SchedPolicy policy;
1828 get_sched_policy(self->GetTid(), &policy);
1829 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1830 // Don't trim the heap if we are a foreground or audio app.
1831 return;
1832 }
1833
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001834 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001835 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001836 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1837 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001838 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1839 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001840 CHECK(!env->ExceptionCheck());
1841}
1842
Ian Rogers48931882013-01-22 14:35:16 -08001843size_t Heap::Trim() {
1844 // Handle a requested heap trim on a thread outside of the main GC thread.
1845 return alloc_space_->Trim();
1846}
1847
Carl Shapiro69759ea2011-07-21 18:13:35 -07001848} // namespace art