blob: 7edbcf04606e13e05fb090b6fc040d443082b149 [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"
Elliott Hughes767a1472011-10-26 18:49:02 -070026#include "debugger.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070027#include "gc/atomic_stack.h"
28#include "gc/card_table.h"
29#include "gc/heap_bitmap.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070030#include "gc/large_object_space.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070031#include "gc/mark_sweep.h"
Mathieu Chartier2b82db42012-11-14 17:29:05 -080032#include "gc/partial_mark_sweep.h"
33#include "gc/sticky_mark_sweep.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070034#include "gc/mod_union_table.h"
35#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070036#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070037#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080038#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080039#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070040#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070041#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070042#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070043#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070044#include "timing_logger.h"
45#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070046#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070047
48namespace art {
49
Mathieu Chartier2b82db42012-11-14 17:29:05 -080050static const uint64_t kSlowGcThreshold = MsToNs(100);
51static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080052static const bool kDumpGcPerformanceOnShutdown = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070053const double Heap::kDefaultTargetUtilization = 0.5;
54
Elliott Hughesae80b492012-04-24 10:43:17 -070055static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080056 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080057 std::vector<std::string> boot_class_path;
58 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070059 if (boot_class_path.empty()) {
60 LOG(FATAL) << "Failed to generate image because no boot class path specified";
61 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080062
63 std::vector<char*> arg_vector;
64
65 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070066 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080067 const char* dex2oat = dex2oat_string.c_str();
68 arg_vector.push_back(strdup(dex2oat));
69
70 std::string image_option_string("--image=");
71 image_option_string += image_file_name;
72 const char* image_option = image_option_string.c_str();
73 arg_vector.push_back(strdup(image_option));
74
75 arg_vector.push_back(strdup("--runtime-arg"));
76 arg_vector.push_back(strdup("-Xms64m"));
77
78 arg_vector.push_back(strdup("--runtime-arg"));
79 arg_vector.push_back(strdup("-Xmx64m"));
80
81 for (size_t i = 0; i < boot_class_path.size(); i++) {
82 std::string dex_file_option_string("--dex-file=");
83 dex_file_option_string += boot_class_path[i];
84 const char* dex_file_option = dex_file_option_string.c_str();
85 arg_vector.push_back(strdup(dex_file_option));
86 }
87
88 std::string oat_file_option_string("--oat-file=");
89 oat_file_option_string += image_file_name;
90 oat_file_option_string.erase(oat_file_option_string.size() - 3);
91 oat_file_option_string += "oat";
92 const char* oat_file_option = oat_file_option_string.c_str();
93 arg_vector.push_back(strdup(oat_file_option));
94
jeffhao8161c032012-10-31 15:50:00 -070095 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
96 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -080097
Elliott Hughes48436bb2012-02-07 15:23:28 -080098 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080099 LOG(INFO) << command_line;
100
Elliott Hughes48436bb2012-02-07 15:23:28 -0800101 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800102 char** argv = &arg_vector[0];
103
104 // fork and exec dex2oat
105 pid_t pid = fork();
106 if (pid == 0) {
107 // no allocation allowed between fork and exec
108
109 // change process groups, so we don't get reaped by ProcessManager
110 setpgid(0, 0);
111
112 execv(dex2oat, argv);
113
114 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
115 return false;
116 } else {
117 STLDeleteElements(&arg_vector);
118
119 // wait for dex2oat to finish
120 int status;
121 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
122 if (got_pid != pid) {
123 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
124 return false;
125 }
126 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
127 LOG(ERROR) << dex2oat << " failed: " << command_line;
128 return false;
129 }
130 }
131 return true;
132}
133
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700134void Heap::UnReserveOatFileAddressRange() {
135 oat_file_map_.reset(NULL);
136}
137
Mathieu Chartier0051be62012-10-12 17:47:11 -0700138Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
139 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700140 const std::string& original_image_file_name, bool concurrent_gc)
141 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800142 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700143 concurrent_gc_(concurrent_gc),
144 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800145 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700146 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700147 enforce_heap_growth_rate_(false),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800148 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700149 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700150 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700151 concurrent_start_size_(128 * KB),
152 concurrent_min_free_(256 * KB),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800153 concurrent_start_bytes_(concurrent_gc ? initial_size - concurrent_start_size_ :
154 std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700155 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700156 total_bytes_freed_(0),
157 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700158 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800159 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700160 verify_missing_card_marks_(false),
161 verify_system_weaks_(false),
162 verify_pre_gc_heap_(false),
163 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700164 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700165 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700166 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700167 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700168 last_trim_time_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800169 allocation_rate_(0),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700170 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800171 reference_referent_offset_(0),
172 reference_queue_offset_(0),
173 reference_queueNext_offset_(0),
174 reference_pendingNext_offset_(0),
175 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700176 min_free_(min_free),
177 max_free_(max_free),
178 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700179 total_wait_time_(0),
180 measure_allocation_time_(false),
181 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700182 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800183 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800184 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700185 }
186
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700187 live_bitmap_.reset(new HeapBitmap(this));
188 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700189
Ian Rogers30fab402012-01-23 15:43:46 -0800190 // Requested begin for the alloc space, to follow the mapped image and oat files
191 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800192 std::string image_file_name(original_image_file_name);
193 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700194 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700195
Brian Carlstrom5643b782012-02-05 12:32:53 -0800196 if (OS::FileExists(image_file_name.c_str())) {
197 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700198 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800199 } else {
200 // If the /system file didn't exist, we need to use one from the art-cache.
201 // If the cache file exists, try to open, but if it fails, regenerate.
202 // If it does not exist, generate.
203 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
204 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700205 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800206 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700207 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700208 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700209 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800210 }
211 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700212
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700213 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700214 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800215 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
216 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700217 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
218 CHECK_GT(oat_end_addr, image_space->End());
219
220 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
221 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
222 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
223 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
224 reinterpret_cast<byte*>(reserve_begin),
225 reserve_end - reserve_begin, PROT_READ));
226
Ian Rogers30fab402012-01-23 15:43:46 -0800227 if (oat_end_addr > requested_begin) {
228 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700229 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700230 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700231 }
232
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700233 // Allocate the large object space.
234 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700235 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
236 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
237
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700238 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
239 growth_limit, capacity,
240 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700241 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700242 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700243 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700244 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700245
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700246 // Spaces are sorted in order of Begin().
247 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700248 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
249 if (spaces_.back()->IsAllocSpace()) {
250 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
251 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700252
Ian Rogers30fab402012-01-23 15:43:46 -0800253 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700254 // TODO: C++0x
255 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
256 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800257 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700258 ImageSpace* image_space = space->AsImageSpace();
259 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800260 }
261 }
262
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800263 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700264 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
265 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700266
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700267 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
268 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700269
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700270 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
271 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700272
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700273 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700274 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800276 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700277 static const size_t default_mark_stack_size = 64 * KB;
278 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
279 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700280 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700281 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
282 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700283
Mathieu Chartier65db8802012-11-20 12:36:46 -0800284 // It's still too early to take a lock because there are no threads yet, but we can create locks
285 // now. We don't create it earlier to make it clear that you can't use locks during heap
286 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700287 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700288 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
289 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700290
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700291 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
292 reference_queue_lock_.reset(new Mutex("reference queue lock"));
293
Mathieu Chartier65db8802012-11-20 12:36:46 -0800294 last_gc_time_ = NanoTime();
295 last_gc_size_ = GetBytesAllocated();
296
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800297 // Create our garbage collectors.
298 for (size_t i = 0; i < 2; ++i) {
299 const bool concurrent = i != 0;
300 mark_sweep_collectors_.push_back(new MarkSweep(this, concurrent));
301 mark_sweep_collectors_.push_back(new PartialMarkSweep(this, concurrent));
302 mark_sweep_collectors_.push_back(new StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700303 }
304
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800305 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800306 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800307 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700308 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700309}
310
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700311void Heap::CreateThreadPool() {
312 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
313 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
314 // workers to complete.
315 thread_pool_.reset(new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
316}
317
318void Heap::DeleteThreadPool() {
319 thread_pool_.reset(NULL);
320}
321
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700322// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700323struct SpaceSorter {
324 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700325 return a->Begin() < b->Begin();
326 }
327};
328
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700329void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700330 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700331 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700332 DCHECK(space->GetLiveBitmap() != NULL);
333 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700334 DCHECK(space->GetMarkBitmap() != NULL);
335 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800336 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700337 if (space->IsAllocSpace()) {
338 alloc_space_ = space->AsAllocSpace();
339 }
340
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700341 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
342 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700343
344 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
345 // avoid redundant marking.
346 bool seen_zygote = false, seen_alloc = false;
347 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
348 Space* space = *it;
349 if (space->IsImageSpace()) {
350 DCHECK(!seen_zygote);
351 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700352 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700353 DCHECK(!seen_alloc);
354 seen_zygote = true;
355 } else if (space->IsAllocSpace()) {
356 seen_alloc = true;
357 }
358 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800359}
360
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700361void Heap::DumpGcPerformanceInfo() {
362 // Dump cumulative timings.
363 LOG(INFO) << "Dumping cumulative Gc timings";
364 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800365
366 // Dump cumulative loggers for each GC type.
367 // TODO: C++0x
368 uint64_t total_paused_time = 0;
369 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
370 it != mark_sweep_collectors_.end(); ++it) {
371 MarkSweep* collector = *it;
372 const CumulativeLogger& logger = collector->GetCumulativeTimings();
373 if (logger.GetTotalNs() != 0) {
374 logger.Dump();
375 const uint64_t total_ns = logger.GetTotalNs();
376 const uint64_t total_pause_ns = (*it)->GetTotalPausedTime();
377 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
378 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
379 const uint64_t freed_objects = collector->GetTotalFreedObjects();
380 LOG(INFO)
381 << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
382 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
383 << collector->GetName() << " freed: " << freed_objects
384 << " objects with total size " << PrettySize(freed_bytes) << "\n"
385 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
386 << PrettySize(freed_bytes / seconds) << "/s\n";
387 total_duration += total_ns;
388 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700389 }
390 }
391 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
392 size_t total_objects_allocated = GetTotalObjectsAllocated();
393 size_t total_bytes_allocated = GetTotalBytesAllocated();
394 if (total_duration != 0) {
395 const double total_seconds = double(total_duration / 1000) / 1000000.0;
396 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
397 LOG(INFO) << "Mean GC size throughput: "
398 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
399 LOG(INFO) << "Mean GC object throughput: " << GetTotalObjectsFreed() / total_seconds << "/s";
400 }
401 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
402 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
403 if (measure_allocation_time_) {
404 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
405 LOG(INFO) << "Mean allocation time: "
406 << PrettyDuration(allocation_time / total_objects_allocated);
407 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800408 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time);
409 LOG(INFO) << "Total time waiting for GC to complete time: " << PrettyDuration(total_wait_time_);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700410}
411
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800412Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700413 if (kDumpGcPerformanceOnShutdown) {
414 DumpGcPerformanceInfo();
415 }
416
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800417 STLDeleteElements(&mark_sweep_collectors_);
418
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700419 // If we don't reset then the mark stack complains in it's destructor.
420 allocation_stack_->Reset();
421 live_stack_->Reset();
422
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800423 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800424 // We can't take the heap lock here because there might be a daemon thread suspended with the
425 // heap lock held. We know though that no non-daemon threads are executing, and we know that
426 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
427 // 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 -0700428 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 delete gc_complete_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700430}
431
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700432ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700433 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700434 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
435 if ((*it)->Contains(obj)) {
436 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700437 }
438 }
439 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
440 return NULL;
441}
442
443ImageSpace* Heap::GetImageSpace() {
444 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700445 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
446 if ((*it)->IsImageSpace()) {
447 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700448 }
449 }
450 return NULL;
451}
452
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700453DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700454 return alloc_space_;
455}
456
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700457static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700458 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700459 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700460 size_t chunk_free_bytes = chunk_size - used_bytes;
461 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
462 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700463 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700464}
465
Ian Rogers50b35e22012-10-04 10:09:15 -0700466Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
468 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
469 strlen(ClassHelper(c).GetDescriptor()) == 0);
470 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700471
472 Object* obj = NULL;
473 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700474 uint64_t allocation_start = 0;
475 if (measure_allocation_time_) {
476 allocation_start = NanoTime();
477 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700478
479 // We need to have a zygote space or else our newly allocated large object can end up in the
480 // Zygote resulting in it being prematurely freed.
481 // We can only do this for primive objects since large objects will not be within the card table
482 // range. This also means that we rely on SetClass not dirtying the object's card.
483 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700484 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700485 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700486 // Make sure that our large object didn't get placed anywhere within the space interval or else
487 // it breaks the immune range.
488 DCHECK(obj == NULL ||
489 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
490 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700491 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700492 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700493
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700494 // Ensure that we did not allocate into a zygote space.
495 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
496 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700497 }
498
Mathieu Chartier037813d2012-08-23 16:44:59 -0700499 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700501
502 // Record allocation after since we want to use the atomic add for the atomic fence to guard
503 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700504 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700505
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700506 if (Dbg::IsAllocTrackingEnabled()) {
507 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700508 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700509 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700510 // We already have a request pending, no reason to start more until we update
511 // concurrent_start_bytes_.
512 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700514 SirtRef<Object> ref(self, obj);
515 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516 }
517 VerifyObject(obj);
518
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700519 if (measure_allocation_time_) {
520 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
521 }
522
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700523 return obj;
524 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800525 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700526 int64_t total_bytes_free = GetFreeMemory();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800527 uint64_t alloc_space_size = alloc_space_->GetNumBytesAllocated();
528 uint64_t large_object_size = large_object_space_->GetNumObjectsAllocated();
529 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
530 << " free bytes; allocation space size " << alloc_space_size
531 << "; large object space size " << large_object_size;
532 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
533 if (total_bytes_free >= byte_count) {
534 size_t max_contiguous_allocation = 0;
535 // TODO: C++0x auto
536 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
537 if ((*it)->IsAllocSpace()) {
538 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
539 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700540 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800541 oss << "; failed due to fragmentation (largest possible contiguous allocation "
542 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700543 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800544 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700545 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700546}
547
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700548bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700549 // Note: we deliberately don't take the lock here, and mustn't test anything that would
550 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700551 if (obj == NULL) {
552 return true;
553 }
554 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700555 return false;
556 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800557 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800558 if (spaces_[i]->Contains(obj)) {
559 return true;
560 }
561 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700562 // Note: Doing this only works for the free list version of the large object space since the
563 // multiple memory map version uses a lock to do the contains check.
564 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700565}
566
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700567bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700568 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700569 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700570}
571
Elliott Hughes3e465b12011-09-02 18:26:12 -0700572#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700573void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700574 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700575 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700576 return;
577 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700578 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700579}
580#endif
581
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700582void Heap::DumpSpaces() {
583 // TODO: C++0x auto
584 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700585 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700586 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
587 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
588 LOG(INFO) << space << " " << *space << "\n"
589 << live_bitmap << " " << *live_bitmap << "\n"
590 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700591 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700592 if (large_object_space_.get() != NULL) {
593 large_object_space_->Dump(LOG(INFO));
594 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700595}
596
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700597void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700598 if (!IsAligned<kObjectAlignment>(obj)) {
599 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700600 }
601
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700602 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
603 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700604 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700605 // Check the allocation stack / live stack.
606 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
607 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
608 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700609 if (large_object_space_->GetLiveObjects()->Test(obj)) {
610 DumpSpaces();
611 LOG(FATAL) << "Object is dead: " << obj;
612 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700613 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700614 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700615
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700616 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700617 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700618 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
619 Object::ClassOffset().Int32Value();
620 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
621 if (c == NULL) {
622 LOG(FATAL) << "Null class in object: " << obj;
623 } else if (!IsAligned<kObjectAlignment>(c)) {
624 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
625 } else if (!GetLiveBitmap()->Test(c)) {
626 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
627 }
628 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
629 // Note: we don't use the accessors here as they have internal sanity checks
630 // that we don't want to run
631 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
632 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
633 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
634 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
635 CHECK_EQ(c_c, c_c_c);
636 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700637}
638
Brian Carlstrom78128a62011-09-15 17:21:19 -0700639void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700640 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700641 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700642}
643
644void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700645 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700646 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700647}
648
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700649void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700650 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700651 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700652 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700653
654 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700655 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700656 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700657 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700658
659 // TODO: Update these atomically.
660 RuntimeStats* global_stats = Runtime::Current()->GetStats();
661 ++global_stats->allocated_objects;
662 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700663 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700664
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700665 // This is safe to do since the GC will never free objects which are neither in the allocation
666 // stack or the live bitmap.
667 while (!allocation_stack_->AtomicPushBack(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700668 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700669 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700670}
671
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700672void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700673 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
674 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700675
676 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700677 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700678 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700679 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700680
681 // TODO: Do this concurrently.
682 RuntimeStats* global_stats = Runtime::Current()->GetStats();
683 global_stats->freed_objects += freed_objects;
684 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700685 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700686}
687
Ian Rogers50b35e22012-10-04 10:09:15 -0700688Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700689 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800690 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
691 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
692 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
693 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700694 return NULL;
695 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700696
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800697 if (enforce_heap_growth_rate_) {
698 if (grow) {
699 // Grow the heap by alloc_size extra bytes.
700 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
701 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
702 << " for a " << PrettySize(alloc_size) << " allocation";
703 } else {
704 return NULL;
705 }
706 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700707 }
708
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700709 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700710}
711
Ian Rogers50b35e22012-10-04 10:09:15 -0700712Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700713 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
714 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700715 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700716 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700717
Ian Rogers50b35e22012-10-04 10:09:15 -0700718 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700719 if (ptr != NULL) {
720 return ptr;
721 }
722
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700723 // The allocation failed. If the GC is running, block until it completes, and then retry the
724 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700725 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700726 if (last_gc != kGcTypeNone) {
727 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700728 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700729 if (ptr != NULL) {
730 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700731 }
732 }
733
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700734 // Loop through our different Gc types and try to Gc until we get enough free memory.
735 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
736 bool run_gc = false;
737 GcType gc_type = static_cast<GcType>(i);
738 switch (gc_type) {
739 case kGcTypeSticky: {
740 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700741 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
742 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700743 break;
744 }
745 case kGcTypePartial:
746 run_gc = have_zygote_space_;
747 break;
748 case kGcTypeFull:
749 run_gc = true;
750 break;
751 default:
752 break;
753 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700754
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700755 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700756 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700757 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800758 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700759 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700760
761 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700762 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700763 if (ptr != NULL) {
764 return ptr;
765 }
766 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700767 }
768
769 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700770 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700771 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700772 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700773 return ptr;
774 }
775
Elliott Hughes81ff3182012-03-23 20:35:56 -0700776 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
777 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
778 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700779
Elliott Hughes418dfe72011-10-06 18:56:27 -0700780 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700781 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
782 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700783
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700784 // We don't need a WaitForConcurrentGcToComplete here either.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700785 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700786 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700787}
788
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700789void Heap::SetTargetHeapUtilization(float target) {
790 DCHECK_GT(target, 0.0f); // asserted in Java code
791 DCHECK_LT(target, 1.0f);
792 target_utilization_ = target;
793}
794
795int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700796 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700797}
798
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700799int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700800 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700801}
802
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700803int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700804 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700805}
806
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700807size_t Heap::GetTotalBytesFreed() const {
808 return total_bytes_freed_;
809}
810
811size_t Heap::GetTotalObjectsFreed() const {
812 return total_objects_freed_;
813}
814
815size_t Heap::GetTotalObjectsAllocated() const {
816 size_t total = large_object_space_->GetTotalObjectsAllocated();
817 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
818 Space* space = *it;
819 if (space->IsAllocSpace()) {
820 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
821 }
822 }
823 return total;
824}
825
826size_t Heap::GetTotalBytesAllocated() const {
827 size_t total = large_object_space_->GetTotalBytesAllocated();
828 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
829 Space* space = *it;
830 if (space->IsAllocSpace()) {
831 total += space->AsAllocSpace()->GetTotalBytesAllocated();
832 }
833 }
834 return total;
835}
836
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700837class InstanceCounter {
838 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700839 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700840 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700841 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700842
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700843 }
844
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700845 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
846 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700847 if (count_assignable_) {
848 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700849 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700850 }
851 } else {
852 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700853 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700854 }
855 }
856 }
857
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700858 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700859 Class* class_;
860 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700861 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700862};
863
864int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700865 size_t count = 0;
866 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700867 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700868 GetLiveBitmap()->Visit(counter);
869 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700870}
871
Ian Rogers30fab402012-01-23 15:43:46 -0800872void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700873 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
874 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700875 Thread* self = Thread::Current();
876 WaitForConcurrentGcToComplete(self);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700877 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700878}
879
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700880void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700881 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800882 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
883 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700884 Thread* self = Thread::Current();
885 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700886
887 // Try to see if we have any Zygote spaces.
888 if (have_zygote_space_) {
889 return;
890 }
891
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700892 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
893
894 {
895 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700896 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700897 FlushAllocStack();
898 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700899
900 // Replace the first alloc space we find with a zygote space.
901 // TODO: C++0x auto
902 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
903 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700904 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700905
906 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
907 // of the remaining available heap memory.
908 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700909 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700910
911 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700912 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700913 AddSpace(alloc_space_);
914 have_zygote_space_ = true;
915 break;
916 }
917 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700918
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700919 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700920 // TODO: C++0x
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800921 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
922 it != mark_sweep_collectors_.end(); ++it) {
923 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -0700924 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700925}
926
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700927void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700928 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
929 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700930 allocation_stack_->Reset();
931}
932
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700933size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700934 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700935}
936
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700937void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
938 Object** limit = stack->End();
939 for (Object** it = stack->Begin(); it != limit; ++it) {
940 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700941 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700942 if (LIKELY(bitmap->HasAddress(obj))) {
943 bitmap->Set(obj);
944 } else {
945 large_objects->Set(obj);
946 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700947 }
948}
949
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700950void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
951 Object** limit = stack->End();
952 for (Object** it = stack->Begin(); it != limit; ++it) {
953 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700954 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700955 if (LIKELY(bitmap->HasAddress(obj))) {
956 bitmap->Clear(obj);
957 } else {
958 large_objects->Clear(obj);
959 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700960 }
961}
962
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700963GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700964 Thread* self = Thread::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800965 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -0700966 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -0700967
Ian Rogers120f1c72012-09-28 17:17:10 -0700968 if (self->IsHandlingStackOverflow()) {
969 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
970 }
971
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700972 // Ensure there is only one GC at a time.
973 bool start_collect = false;
974 while (!start_collect) {
975 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700976 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700977 if (!is_gc_running_) {
978 is_gc_running_ = true;
979 start_collect = true;
980 }
981 }
982 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700983 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700984 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
985 // Not doing at the moment to ensure soft references are cleared.
986 }
987 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700988 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700989
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700990 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
991 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
992 ++Thread::Current()->GetStats()->gc_for_alloc_count;
993 }
994
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700995 // We need to do partial GCs every now and then to avoid the heap growing too much and
996 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700997 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700998 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700999 }
Mathieu Chartier0325e622012-09-05 14:22:51 -07001000 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001001 sticky_gc_count_ = 0;
1002 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001003
Mathieu Chartier65db8802012-11-20 12:36:46 -08001004 uint64_t gc_start_time = NanoTime();
1005 uint64_t gc_start_size = GetBytesAllocated();
1006 // Approximate allocation rate in bytes / second.
1007 DCHECK_NE(gc_start_time, last_gc_time_);
1008 uint64_t ms_delta = NsToMs(gc_start_time - last_gc_time_);
1009 if (ms_delta != 0) {
1010 allocation_rate_ = (gc_start_size - last_gc_size_) * 1000 / ms_delta;
1011 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1012 }
1013
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001014 DCHECK_LT(gc_type, kGcTypeMax);
1015 DCHECK_NE(gc_type, kGcTypeNone);
1016 MarkSweep* collector = NULL;
1017 for (Collectors::iterator it = mark_sweep_collectors_.begin();
1018 it != mark_sweep_collectors_.end(); ++it) {
1019 MarkSweep* cur_collector = *it;
1020 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1021 collector = cur_collector;
1022 break;
1023 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001024 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001025 CHECK(collector != NULL)
1026 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1027 << " and type=" << gc_type;
1028 collector->clear_soft_references_ = clear_soft_references;
1029 collector->Run();
1030 total_objects_freed_ += collector->GetFreedObjects();
1031 total_bytes_freed_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001032
Mathieu Chartier65db8802012-11-20 12:36:46 -08001033 const size_t duration = collector->GetDuration();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001034 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1035 bool was_slow = duration > kSlowGcThreshold ||
1036 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1037 for (size_t i = 0; i < pauses.size(); ++i) {
1038 if (pauses[i] > kLongGcPauseThreshold) {
1039 was_slow = true;
1040 }
1041 }
1042
1043 if (was_slow) {
1044 const size_t percent_free = GetPercentFree();
1045 const size_t current_heap_size = GetUsedMemorySize();
1046 const size_t total_memory = GetTotalMemory();
1047 std::ostringstream pause_string;
1048 for (size_t i = 0; i < pauses.size(); ++i) {
1049 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1050 << ((i != pauses.size() - 1) ? ", " : "");
1051 }
1052 LOG(INFO) << gc_cause << " " << collector->GetName()
1053 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1054 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1055 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1056 << " total " << PrettyDuration((duration / 1000) * 1000);
1057 if (VLOG_IS_ON(heap)) {
1058 collector->GetTimings().Dump();
1059 }
1060 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001061
Ian Rogers15bf2d32012-08-28 17:33:04 -07001062 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001063 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001064 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001065 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001066 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001067 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001068 }
1069 // Inform DDMS that a GC completed.
1070 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001071 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001072}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001073
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001074void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001075 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001076 // 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 -07001077 // cards.
1078 return;
1079 }
1080
1081 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001082 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001083 zygote_mod_union_table_->Update();
1084 timings.AddSplit("UpdateZygoteModUnionTable");
1085
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001086 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001087 timings.AddSplit("ZygoteMarkReferences");
1088 }
1089
1090 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1091 mod_union_table_->Update();
1092 timings.AddSplit("UpdateModUnionTable");
1093
1094 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001095 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001096 timings.AddSplit("MarkImageToAllocSpaceReferences");
1097}
1098
1099void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1100 Object* obj = reinterpret_cast<Object*>(arg);
1101 if (root == obj) {
1102 LOG(INFO) << "Object " << obj << " is a root";
1103 }
1104}
1105
1106class ScanVisitor {
1107 public:
1108 void operator ()(const Object* obj) const {
1109 LOG(INFO) << "Would have rescanned object " << obj;
1110 }
1111};
1112
1113class VerifyReferenceVisitor {
1114 public:
1115 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001116 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1117 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001118 : heap_(heap),
1119 failed_(failed) {
1120 }
1121
1122 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1123 // analysis.
1124 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1125 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1126 // Verify that the reference is live.
1127 if (ref != NULL && !IsLive(ref)) {
1128 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001129 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1130 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001131
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001132 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001133 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1134 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1135 << "Obj type " << PrettyTypeOf(obj) << "\n"
1136 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001137 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001138 void* cover_begin = card_table->AddrFromCard(card_addr);
1139 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001140 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001141 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001142 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001143 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1144
1145 // Print out how the object is live.
1146 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001147 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1148 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001149 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1150 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1151 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001152 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1153 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001154 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001155 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001156 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001157 }
1158
1159 // Attempt to see if the card table missed the reference.
1160 ScanVisitor scan_visitor;
1161 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001162 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001163 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001164
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001165 // Search to see if any of the roots reference our object.
1166 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1167 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1168 *failed_ = true;
1169 }
1170 }
1171
1172 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001173 if (heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001174 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001175 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001176 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001177 // 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 -08001178 // If the object is not either in the live bitmap or allocation stack, so the object must be
1179 // dead.
1180 return std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001181 }
1182
1183 private:
1184 Heap* heap_;
1185 bool* failed_;
1186};
1187
1188class VerifyObjectVisitor {
1189 public:
1190 VerifyObjectVisitor(Heap* heap)
1191 : heap_(heap),
1192 failed_(false) {
1193
1194 }
1195
1196 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001197 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001198 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1199 MarkSweep::VisitObjectReferences(obj, visitor);
1200 }
1201
1202 bool Failed() const {
1203 return failed_;
1204 }
1205
1206 private:
1207 Heap* heap_;
1208 bool failed_;
1209};
1210
1211// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001212bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001213 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001214 // Lets sort our allocation stacks so that we can efficiently binary search them.
1215 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1216 std::sort(live_stack_->Begin(), live_stack_->End());
1217 // Perform the verification.
1218 VerifyObjectVisitor visitor(this);
1219 GetLiveBitmap()->Visit(visitor);
1220 // We don't want to verify the objects in the allocation stack since they themselves may be
1221 // pointing to dead objects if they are not reachable.
1222 if (visitor.Failed()) {
1223 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001224 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001225 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001226 return true;
1227}
1228
1229class VerifyReferenceCardVisitor {
1230 public:
1231 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1232 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1233 Locks::heap_bitmap_lock_)
1234 : heap_(heap),
1235 failed_(failed) {
1236 }
1237
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001238 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1239 // annotalysis on visitors.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001240 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1241 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001242 // Filter out class references since changing an object's class does not mark the card as dirty.
1243 // Also handles large objects, since the only reference they hold is a class reference.
1244 if (ref != NULL && !ref->IsClass()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001245 CardTable* card_table = heap_->GetCardTable();
1246 // If the object is not dirty and it is referencing something in the live stack other than
1247 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001248 if (!card_table->AddrIsInCardTable(obj)) {
1249 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1250 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001251 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001252 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1253 // kCardDirty - 1 if it didnt get touched since we aged it.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001254 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001255 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001256 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1257 LOG(ERROR) << "Object " << obj << " found in live stack";
1258 }
1259 if (heap_->GetLiveBitmap()->Test(obj)) {
1260 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1261 }
1262 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1263 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1264
1265 // Print which field of the object is dead.
1266 if (!obj->IsObjectArray()) {
1267 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1268 CHECK(klass != NULL);
1269 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1270 CHECK(fields != NULL);
1271 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1272 const Field* cur = fields->Get(i);
1273 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1274 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1275 << PrettyField(cur);
1276 break;
1277 }
1278 }
1279 } else {
1280 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1281 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1282 if (object_array->Get(i) == ref) {
1283 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1284 }
1285 }
1286 }
1287
1288 *failed_ = true;
1289 }
1290 }
1291 }
1292 }
1293
1294 private:
1295 Heap* heap_;
1296 bool* failed_;
1297};
1298
1299class VerifyLiveStackReferences {
1300 public:
1301 VerifyLiveStackReferences(Heap* heap)
1302 : heap_(heap),
1303 failed_(false) {
1304
1305 }
1306
1307 void operator ()(const Object* obj) const
1308 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1309 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1310 MarkSweep::VisitObjectReferences(obj, visitor);
1311 }
1312
1313 bool Failed() const {
1314 return failed_;
1315 }
1316
1317 private:
1318 Heap* heap_;
1319 bool failed_;
1320};
1321
1322bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001323 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001324
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001325 // We need to sort the live stack since we binary search it.
1326 std::sort(live_stack_->Begin(), live_stack_->End());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001327 VerifyLiveStackReferences visitor(this);
1328 GetLiveBitmap()->Visit(visitor);
1329
1330 // We can verify objects in the live stack since none of these should reference dead objects.
1331 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1332 visitor(*it);
1333 }
1334
1335 if (visitor.Failed()) {
1336 DumpSpaces();
1337 return false;
1338 }
1339 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001340}
1341
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001342void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001343 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001344
1345 // Sort the live stack so that we can quickly binary search it later.
1346 if (VERIFY_OBJECT_ENABLED) {
1347 std::sort(live_stack_->Begin(), live_stack_->End());
1348 }
1349}
1350
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001351void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001352 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1353 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1354 ContinuousSpace* space = *it;
1355 if (space->IsImageSpace()) {
1356 mod_union_table_->ClearCards(*it);
1357 timings.AddSplit("ModUnionClearCards");
1358 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1359 zygote_mod_union_table_->ClearCards(space);
1360 timings.AddSplit("ZygoteModUnionClearCards");
1361 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001362 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1363 // were dirty before the GC started.
1364 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1365 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001366 }
1367 }
1368}
1369
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001370void Heap::PreGcVerification(GarbageCollector* gc) {
1371 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1372 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001373
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001374 if (verify_pre_gc_heap_) {
1375 thread_list->SuspendAll();
1376 {
1377 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1378 if (!VerifyHeapReferences()) {
1379 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1380 }
1381 }
1382 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001383 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001384
1385 // Check that all objects which reference things in the live stack are on dirty cards.
1386 if (verify_missing_card_marks_) {
1387 thread_list->SuspendAll();
1388 {
1389 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1390 SwapStacks();
1391 // Sort the live stack so that we can quickly binary search it later.
1392 if (!VerifyMissingCardMarks()) {
1393 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1394 }
1395 SwapStacks();
1396 }
1397 thread_list->ResumeAll();
1398 }
1399
1400 if (verify_mod_union_table_) {
1401 thread_list->SuspendAll();
1402 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1403 zygote_mod_union_table_->Update();
1404 zygote_mod_union_table_->Verify();
1405 mod_union_table_->Update();
1406 mod_union_table_->Verify();
1407 thread_list->ResumeAll();
1408 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001409}
1410
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001411void Heap::PreSweepingGcVerification(GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001412 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001413 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001414
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001415 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1416 // reachable objects.
1417 if (verify_post_gc_heap_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001418 thread_list->SuspendAll();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001419 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1420 // Swapping bound bitmaps does nothing.
1421 live_bitmap_.swap(mark_bitmap_);
1422 if (!VerifyHeapReferences()) {
1423 LOG(FATAL) << "Post " << gc->GetName() << "Gc verification failed";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001424 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001425 live_bitmap_.swap(mark_bitmap_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001426 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001427 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001428}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001429
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001430void Heap::PostGcVerification(GarbageCollector* gc) {
1431 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001432
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001433 if (verify_system_weaks_) {
1434 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1435 MarkSweep* mark_sweep = down_cast<MarkSweep*>(gc);
1436 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001437 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001438}
1439
Ian Rogers81d425b2012-09-27 16:03:43 -07001440GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001441 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001442 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001443 bool do_wait;
1444 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001445 {
1446 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001447 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001448 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001449 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001450 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001451 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001452 // We must wait, change thread state then sleep on gc_complete_cond_;
1453 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1454 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001455 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001456 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001457 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001458 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001459 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001460 wait_time = NanoTime() - wait_start;;
1461 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001462 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001463 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001464 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1465 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001466 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001467 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001468 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001469}
1470
Elliott Hughesc967f782012-04-16 10:23:15 -07001471void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001472 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1473 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001474 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001475}
1476
1477size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001478 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001479}
1480
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001481void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001482 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001483 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001484 << PrettySize(GetMaxMemory());
1485 max_allowed_footprint = GetMaxMemory();
1486 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001487 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001488}
1489
Mathieu Chartier65db8802012-11-20 12:36:46 -08001490void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001491 // We know what our utilization is at this moment.
1492 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001493 const size_t bytes_allocated = GetBytesAllocated();
1494 last_gc_size_ = bytes_allocated;
1495 last_gc_time_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001496
Mathieu Chartier65db8802012-11-20 12:36:46 -08001497 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1498 if (target_size > bytes_allocated + max_free_) {
1499 target_size = bytes_allocated + max_free_;
1500 } else if (target_size < bytes_allocated + min_free_) {
1501 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001502 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001503
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001504 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001505
1506 // Calculate when to perform the next ConcurrentGC if we have enough free memory.
1507 if (concurrent_gc_ && GetFreeMemory() >= concurrent_min_free_) {
1508 // Calculate the estimated GC duration.
1509 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1510 // Estimate how many remaining bytes we will have when we need to start the next GC.
1511 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1512 if (remaining_bytes < max_allowed_footprint_) {
1513 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1514 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1515 // right away.
1516 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1517 } else {
1518 // The estimated rate is so high that we should request another GC straight away.
1519 concurrent_start_bytes_ = bytes_allocated;
1520 }
1521 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1522 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1523 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001524}
1525
jeffhaoc1160702011-10-27 15:48:45 -07001526void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001527 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001528 alloc_space_->ClearGrowthLimit();
1529}
1530
Elliott Hughesadb460d2011-10-05 17:02:34 -07001531void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001532 MemberOffset reference_queue_offset,
1533 MemberOffset reference_queueNext_offset,
1534 MemberOffset reference_pendingNext_offset,
1535 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001536 reference_referent_offset_ = reference_referent_offset;
1537 reference_queue_offset_ = reference_queue_offset;
1538 reference_queueNext_offset_ = reference_queueNext_offset;
1539 reference_pendingNext_offset_ = reference_pendingNext_offset;
1540 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1541 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1542 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1543 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1544 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1545 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1546}
1547
1548Object* Heap::GetReferenceReferent(Object* reference) {
1549 DCHECK(reference != NULL);
1550 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1551 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1552}
1553
1554void Heap::ClearReferenceReferent(Object* reference) {
1555 DCHECK(reference != NULL);
1556 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1557 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1558}
1559
1560// Returns true if the reference object has not yet been enqueued.
1561bool Heap::IsEnqueuable(const Object* ref) {
1562 DCHECK(ref != NULL);
1563 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1564 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1565 return (queue != NULL) && (queue_next == NULL);
1566}
1567
1568void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1569 DCHECK(ref != NULL);
1570 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1571 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1572 EnqueuePendingReference(ref, cleared_reference_list);
1573}
1574
1575void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1576 DCHECK(ref != NULL);
1577 DCHECK(list != NULL);
1578
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001579 // TODO: Remove this lock, use atomic stacks for storing references.
1580 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001581 if (*list == NULL) {
1582 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1583 *list = ref;
1584 } else {
1585 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1586 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1587 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1588 }
1589}
1590
1591Object* Heap::DequeuePendingReference(Object** list) {
1592 DCHECK(list != NULL);
1593 DCHECK(*list != NULL);
1594 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1595 Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001596
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001597 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1598 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001599 if (*list == head) {
1600 ref = *list;
1601 *list = NULL;
1602 } else {
1603 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1604 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1605 ref = head;
1606 }
1607 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1608 return ref;
1609}
1610
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001611void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001612 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001613 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001614 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001615 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1616 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001617}
1618
1619size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001620 return num_bytes_allocated_;
1621}
1622
1623size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001624 size_t total = 0;
1625 // TODO: C++0x
1626 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1627 Space* space = *it;
1628 if (space->IsAllocSpace()) {
1629 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1630 }
1631 }
1632 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001633}
1634
1635size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001636 return concurrent_start_size_;
1637}
1638
1639size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001640 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001641}
1642
1643void Heap::EnqueueClearedReferences(Object** cleared) {
1644 DCHECK(cleared != NULL);
1645 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001646 // When a runtime isn't started there are no reference queues to care about so ignore.
1647 if (LIKELY(Runtime::Current()->IsStarted())) {
1648 ScopedObjectAccess soa(Thread::Current());
1649 JValue args[1];
1650 args[0].SetL(*cleared);
1651 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1652 args, NULL);
1653 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001654 *cleared = NULL;
1655 }
1656}
1657
Ian Rogers1f539342012-10-03 21:09:42 -07001658void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001659 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001660 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001661 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001662 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001663 !runtime->IsConcurrentGcEnabled()) {
1664 return;
1665 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001666 {
1667 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1668 if (runtime->IsShuttingDown()) {
1669 return;
1670 }
1671 }
1672 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001673 return;
1674 }
1675
Ian Rogers120f1c72012-09-28 17:17:10 -07001676 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001677 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1678 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001679 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1680 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001681 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001682}
1683
Ian Rogers81d425b2012-09-27 16:03:43 -07001684void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001685 {
1686 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001687 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001688 return;
1689 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001690 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001691
Mathieu Chartier65db8802012-11-20 12:36:46 -08001692 // Wait for any GCs currently running to finish.
Ian Rogers81d425b2012-09-27 16:03:43 -07001693 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001694 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001695 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001696 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001697 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001698 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001699 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001700}
1701
Mathieu Chartier3056d0c2012-10-19 10:49:56 -07001702void Heap::Trim() {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001703 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001704}
1705
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001706void Heap::RequestHeapTrim() {
1707 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1708 // because that only marks object heads, so a large array looks like lots of empty space. We
1709 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1710 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1711 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1712 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001713 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001714 float utilization =
1715 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1716 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1717 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1718 // heap trim occurred in the last two seconds.
1719 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001720 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001721
1722 Thread* self = Thread::Current();
1723 {
1724 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1725 Runtime* runtime = Runtime::Current();
1726 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1727 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1728 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1729 // as we don't hold the lock while requesting the trim).
1730 return;
1731 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001732 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001733 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001734 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001735 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1736 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001737 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1738 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001739 CHECK(!env->ExceptionCheck());
1740}
1741
Carl Shapiro69759ea2011-07-21 18:13:35 -07001742} // namespace art