blob: a68cc024358f84d7a4dc98f93f386297a0e254e7 [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
Mathieu Chartier752a0e62013-06-27 11:03:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
Brian Carlstrom5643b782012-02-05 12:32:53 -080021#include <sys/types.h>
22#include <sys/wait.h>
23
Brian Carlstrom58ae9412011-10-04 00:56:06 -070024#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070025#include <vector>
26
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Ian Rogers48931882013-01-22 14:35:16 -080028#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070029#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070030#include "gc/accounting/atomic_stack.h"
31#include "gc/accounting/card_table-inl.h"
32#include "gc/accounting/heap_bitmap-inl.h"
33#include "gc/accounting/mod_union_table-inl.h"
34#include "gc/accounting/space_bitmap-inl.h"
35#include "gc/collector/mark_sweep-inl.h"
36#include "gc/collector/partial_mark_sweep.h"
37#include "gc/collector/sticky_mark_sweep.h"
38#include "gc/space/image_space.h"
39#include "gc/space/large_object_space.h"
40#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070041#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080042#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/class-inl.h"
44#include "mirror/field-inl.h"
45#include "mirror/object.h"
46#include "mirror/object-inl.h"
47#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080048#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080049#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070050#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070051#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070052#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070053#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070054#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070055#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070056
57namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070058namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070059
Ian Rogers1d54e732013-05-02 21:10:01 -070060// When to create a log message about a slow GC, 100ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080061static const uint64_t kSlowGcThreshold = MsToNs(100);
Ian Rogers1d54e732013-05-02 21:10:01 -070062// When to create a log message about a slow pause, 5ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080063static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080064static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070065// Minimum amount of remaining bytes before a concurrent GC is triggered.
66static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070067const double Heap::kDefaultTargetUtilization = 0.5;
68
Elliott Hughesae80b492012-04-24 10:43:17 -070069static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080070 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080071 std::vector<std::string> boot_class_path;
72 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070073 if (boot_class_path.empty()) {
74 LOG(FATAL) << "Failed to generate image because no boot class path specified";
75 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080076
77 std::vector<char*> arg_vector;
78
79 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070080 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080081 const char* dex2oat = dex2oat_string.c_str();
82 arg_vector.push_back(strdup(dex2oat));
83
84 std::string image_option_string("--image=");
85 image_option_string += image_file_name;
86 const char* image_option = image_option_string.c_str();
87 arg_vector.push_back(strdup(image_option));
88
89 arg_vector.push_back(strdup("--runtime-arg"));
90 arg_vector.push_back(strdup("-Xms64m"));
91
92 arg_vector.push_back(strdup("--runtime-arg"));
93 arg_vector.push_back(strdup("-Xmx64m"));
94
95 for (size_t i = 0; i < boot_class_path.size(); i++) {
96 std::string dex_file_option_string("--dex-file=");
97 dex_file_option_string += boot_class_path[i];
98 const char* dex_file_option = dex_file_option_string.c_str();
99 arg_vector.push_back(strdup(dex_file_option));
100 }
101
102 std::string oat_file_option_string("--oat-file=");
103 oat_file_option_string += image_file_name;
104 oat_file_option_string.erase(oat_file_option_string.size() - 3);
105 oat_file_option_string += "oat";
106 const char* oat_file_option = oat_file_option_string.c_str();
107 arg_vector.push_back(strdup(oat_file_option));
108
jeffhao8161c032012-10-31 15:50:00 -0700109 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
110 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800111
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700112 if (kIsTargetBuild) {
113 arg_vector.push_back(strdup("--image-classes-zip=/system/framework/framework.jar"));
114 arg_vector.push_back(strdup("--image-classes=preloaded-classes"));
115 } else {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800116 arg_vector.push_back(strdup("--host"));
117 }
118
Elliott Hughes48436bb2012-02-07 15:23:28 -0800119 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800120 LOG(INFO) << command_line;
121
Elliott Hughes48436bb2012-02-07 15:23:28 -0800122 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800123 char** argv = &arg_vector[0];
124
125 // fork and exec dex2oat
126 pid_t pid = fork();
127 if (pid == 0) {
128 // no allocation allowed between fork and exec
129
130 // change process groups, so we don't get reaped by ProcessManager
131 setpgid(0, 0);
132
133 execv(dex2oat, argv);
134
135 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
136 return false;
137 } else {
138 STLDeleteElements(&arg_vector);
139
140 // wait for dex2oat to finish
141 int status;
142 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
143 if (got_pid != pid) {
144 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
145 return false;
146 }
147 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
148 LOG(ERROR) << dex2oat << " failed: " << command_line;
149 return false;
150 }
151 }
152 return true;
153}
154
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700155void Heap::UnReserveOatFileAddressRange() {
156 oat_file_map_.reset(NULL);
157}
158
Mathieu Chartier0051be62012-10-12 17:47:11 -0700159Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
160 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700161 const std::string& original_image_file_name, bool concurrent_gc)
162 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800163 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700164 concurrent_gc_(concurrent_gc),
165 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -0700166 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800167 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -0700168 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700169 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800170 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700171 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700172 max_allowed_footprint_(initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -0700173 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
174 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700175 total_bytes_freed_ever_(0),
176 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700177 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800178 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700179 verify_missing_card_marks_(false),
180 verify_system_weaks_(false),
181 verify_pre_gc_heap_(false),
182 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700183 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700184 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700185 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700186 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800187 allocation_rate_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700188 max_allocation_stack_size_(kDesiredHeapVerification > kNoHeapVerification? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800189 reference_referent_offset_(0),
190 reference_queue_offset_(0),
191 reference_queueNext_offset_(0),
192 reference_pendingNext_offset_(0),
193 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700194 min_free_(min_free),
195 max_free_(max_free),
196 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700197 total_wait_time_(0),
198 measure_allocation_time_(false),
199 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700200 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800201 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800202 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700203 }
204
Ian Rogers1d54e732013-05-02 21:10:01 -0700205 live_bitmap_.reset(new accounting::HeapBitmap(this));
206 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700207
Ian Rogers30fab402012-01-23 15:43:46 -0800208 // Requested begin for the alloc space, to follow the mapped image and oat files
209 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800210 std::string image_file_name(original_image_file_name);
211 if (!image_file_name.empty()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700212 space::ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700213
Brian Carlstrom5643b782012-02-05 12:32:53 -0800214 if (OS::FileExists(image_file_name.c_str())) {
215 // If the /system file exists, it should be up-to-date, don't try to generate
Ian Rogers1d54e732013-05-02 21:10:01 -0700216 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800217 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -0700218 // If the /system file didn't exist, we need to use one from the dalvik-cache.
Brian Carlstrom5643b782012-02-05 12:32:53 -0800219 // If the cache file exists, try to open, but if it fails, regenerate.
220 // If it does not exist, generate.
Brian Carlstrom7675e162013-06-10 16:18:04 -0700221 image_file_name = GetDalvikCacheFilenameOrDie(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800222 if (OS::FileExists(image_file_name.c_str())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700223 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800224 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700225 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700226 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700227 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800228 }
229 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700230
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700231 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700232 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800233 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
234 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800235 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
236 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700237
238 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
239 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800240 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700241 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
242 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800243 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700244
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800245 if (oat_file_end_addr > requested_begin) {
246 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700247 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700248 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700249 }
250
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700251 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700252 const bool kUseFreeListSpaceForLOS = false;
253 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700254 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700255 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700256 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700257 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700258 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
259 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700260
Ian Rogers1d54e732013-05-02 21:10:01 -0700261 alloc_space_ = space::DlMallocSpace::Create("alloc space",
262 initial_size,
263 growth_limit, capacity,
264 requested_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700265 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700266 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700267 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700268
Ian Rogers1d54e732013-05-02 21:10:01 -0700269 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
270 byte* heap_begin = continuous_spaces_.front()->Begin();
271 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
272 if (continuous_spaces_.back()->IsDlMallocSpace()) {
273 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700274 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700275
Ian Rogers30fab402012-01-23 15:43:46 -0800276 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700277 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700278 typedef std::vector<space::ContinuousSpace*>::iterator It;
279 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
280 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800281 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700282 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700283 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800284 }
285 }
286
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800287 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700288 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700289 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700290
Ian Rogers1d54e732013-05-02 21:10:01 -0700291 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
292 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700293
Ian Rogers1d54e732013-05-02 21:10:01 -0700294 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700295 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700296
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700297 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700298 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800300 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700301 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700302 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
303 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
304 max_allocation_stack_size_));
305 live_stack_.reset(accounting::ObjectStack::Create("live stack",
306 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700307
Mathieu Chartier65db8802012-11-20 12:36:46 -0800308 // It's still too early to take a lock because there are no threads yet, but we can create locks
309 // now. We don't create it earlier to make it clear that you can't use locks during heap
310 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700311 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700312 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
313 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700314
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700315 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700316 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700317
Ian Rogers1d54e732013-05-02 21:10:01 -0700318 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800319 last_gc_size_ = GetBytesAllocated();
320
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800321 // Create our garbage collectors.
322 for (size_t i = 0; i < 2; ++i) {
323 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700324 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
325 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
326 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700327 }
328
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800329 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800330 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800331 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700332 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700333}
334
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700335void Heap::CreateThreadPool() {
336 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
337 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
338 // workers to complete.
Ian Rogers1d54e732013-05-02 21:10:01 -0700339 thread_pool_.reset(new ThreadPool(1)); // new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700340}
341
342void Heap::DeleteThreadPool() {
343 thread_pool_.reset(NULL);
344}
345
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700346// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700347struct ContinuousSpaceSorter {
348 bool operator ()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700349 return a->Begin() < b->Begin();
350 }
351};
352
Ian Rogers1d54e732013-05-02 21:10:01 -0700353void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700354 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700355 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700356 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700357 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700358 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700359 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
360 continuous_spaces_.push_back(space);
361 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
362 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700363 }
364
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700365 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700366 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700367
368 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
369 // avoid redundant marking.
370 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700371 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
372 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
373 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700374 if (space->IsImageSpace()) {
375 DCHECK(!seen_zygote);
376 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700377 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700378 DCHECK(!seen_alloc);
379 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700380 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700381 seen_alloc = true;
382 }
383 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800384}
385
Ian Rogers1d54e732013-05-02 21:10:01 -0700386void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
387 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
388 DCHECK(space != NULL);
389 DCHECK(space->GetLiveObjects() != NULL);
390 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
391 DCHECK(space->GetMarkObjects() != NULL);
392 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
393 discontinuous_spaces_.push_back(space);
394}
395
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700396void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700397 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700398 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700399 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800400
401 // Dump cumulative loggers for each GC type.
402 // TODO: C++0x
403 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700404 typedef std::vector<collector::MarkSweep*>::const_iterator It;
405 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800406 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700407 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800408 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800409 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700410 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800411 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700412 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800413 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
414 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
415 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700416 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
417 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
418 << collector->GetName() << " freed: " << freed_objects
419 << " objects with total size " << PrettySize(freed_bytes) << "\n"
420 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
421 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800422 total_duration += total_ns;
423 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700424 }
425 }
426 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700427 size_t total_objects_allocated = GetObjectsAllocatedEver();
428 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700429 if (total_duration != 0) {
430 const double total_seconds = double(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700431 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
432 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700433 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700434 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700435 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700436 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700437 os << "Total number of allocations: " << total_objects_allocated << "\n";
438 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700439 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700440 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
441 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
442 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700443 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700444 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
445 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700446}
447
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800448Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700449 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700450 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700451 }
452
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800453 STLDeleteElements(&mark_sweep_collectors_);
454
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700455 // If we don't reset then the mark stack complains in it's destructor.
456 allocation_stack_->Reset();
457 live_stack_->Reset();
458
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800459 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800460 // We can't take the heap lock here because there might be a daemon thread suspended with the
461 // heap lock held. We know though that no non-daemon threads are executing, and we know that
462 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
463 // those threads can't resume. We're the only running thread, and we can do whatever we like...
Ian Rogers1d54e732013-05-02 21:10:01 -0700464 STLDeleteElements(&continuous_spaces_);
465 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700467 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700468}
469
Ian Rogers1d54e732013-05-02 21:10:01 -0700470space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
471 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700472 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700473 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
474 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700475 if ((*it)->Contains(obj)) {
476 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700477 }
478 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700479 if (!fail_ok) {
480 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
481 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700482 return NULL;
483}
484
Ian Rogers1d54e732013-05-02 21:10:01 -0700485space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
486 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700487 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700488 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
489 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
490 if ((*it)->Contains(obj)) {
491 return *it;
492 }
493 }
494 if (!fail_ok) {
495 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
496 }
497 return NULL;
498}
499
500space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
501 space::Space* result = FindContinuousSpaceFromObject(obj, true);
502 if (result != NULL) {
503 return result;
504 }
505 return FindDiscontinuousSpaceFromObject(obj, true);
506}
507
508space::ImageSpace* Heap::GetImageSpace() const {
509 // TODO: C++0x auto
510 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
511 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700512 if ((*it)->IsImageSpace()) {
513 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700514 }
515 }
516 return NULL;
517}
518
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700519static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700520 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700521 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700522 size_t chunk_free_bytes = chunk_size - used_bytes;
523 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
524 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700525 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700526}
527
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800528mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
529 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700530 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
531 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800532 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700533
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800534 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700535 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700536 uint64_t allocation_start = 0;
537 if (measure_allocation_time_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700538 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700539 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700540
541 // We need to have a zygote space or else our newly allocated large object can end up in the
542 // Zygote resulting in it being prematurely freed.
543 // We can only do this for primive objects since large objects will not be within the card table
544 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers22a20862013-03-16 16:34:57 -0700545 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700546 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700547 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700548 // Make sure that our large object didn't get placed anywhere within the space interval or else
549 // it breaks the immune range.
550 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700551 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
552 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700553 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700554 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700555
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700556 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700557 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700558 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700559 }
560
Mathieu Chartier037813d2012-08-23 16:44:59 -0700561 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700562 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700563
564 // Record allocation after since we want to use the atomic add for the atomic fence to guard
565 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700566 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700567
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700568 if (Dbg::IsAllocTrackingEnabled()) {
569 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700570 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700571 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700572 // We already have a request pending, no reason to start more until we update
573 // concurrent_start_bytes_.
574 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700575 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800576 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700577 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700578 }
579 VerifyObject(obj);
580
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700581 if (measure_allocation_time_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700582 total_allocation_time_ += NanoTime() / kTimeAdjust - allocation_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700583 }
584
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700585 return obj;
586 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800587 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700588 int64_t total_bytes_free = GetFreeMemory();
Ian Rogers1d54e732013-05-02 21:10:01 -0700589 uint64_t alloc_space_size = alloc_space_->GetBytesAllocated();
590 uint64_t large_object_size = large_object_space_->GetObjectsAllocated();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800591 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
592 << " free bytes; allocation space size " << alloc_space_size
593 << "; large object space size " << large_object_size;
594 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
595 if (total_bytes_free >= byte_count) {
596 size_t max_contiguous_allocation = 0;
597 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700598 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
599 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
600 space::ContinuousSpace* space = *it;
601 if (space->IsDlMallocSpace()) {
602 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800603 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700604 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800605 oss << "; failed due to fragmentation (largest possible contiguous allocation "
606 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700607 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800608 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700609 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700610}
611
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800612bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700613 // Note: we deliberately don't take the lock here, and mustn't test anything that would
614 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700615 if (obj == NULL) {
616 return true;
617 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700618 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700619 return false;
620 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700621 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700622}
623
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800624bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700625 //Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
626 if (obj == NULL) {
627 return false;
628 }
629 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
630 return false;
631 }
632 space::ContinuousSpace* cont_space = FindContinuousSpaceFromObject(obj, true);
633 if (cont_space != NULL) {
634 if (cont_space->GetLiveBitmap()->Test(obj)) {
635 return true;
636 }
637 } else {
638 space::DiscontinuousSpace* disc_space = FindDiscontinuousSpaceFromObject(obj, true);
639 if (disc_space != NULL) {
640 if (disc_space->GetLiveObjects()->Test(obj)) {
641 return true;
642 }
643 }
644 }
645 for (size_t i = 0; i < 5; ++i) {
646 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
647 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
648 return true;
649 }
650 NanoSleep(MsToNs(10));
651 }
652 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700653}
654
Ian Rogers04d7aa92013-03-16 14:29:17 -0700655void Heap::VerifyObjectImpl(const mirror::Object* obj) {
656 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700657 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700658 return;
659 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700660 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700661}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700662
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700663void Heap::DumpSpaces() {
664 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700665 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
666 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
667 space::ContinuousSpace* space = *it;
668 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
669 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700670 LOG(INFO) << space << " " << *space << "\n"
671 << live_bitmap << " " << *live_bitmap << "\n"
672 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700673 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700674 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
675 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
676 space::DiscontinuousSpace* space = *it;
677 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700678 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700679}
680
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800681void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800682 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700683 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700684 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800685 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
686 return;
687 }
688 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
689 mirror::Object::ClassOffset().Int32Value();
690 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
691 if (UNLIKELY(c == NULL)) {
692 LOG(FATAL) << "Null class in object: " << obj;
693 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
694 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
695 }
696 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
697 // Note: we don't use the accessors here as they have internal sanity checks
698 // that we don't want to run
699 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
700 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
701 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
702 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
703 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700704
Ian Rogers62d6c772013-02-27 08:32:07 -0800705 if (verify_object_mode_ != kVerifyAllFast) {
706 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
707 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700708 if (!IsLiveObjectLocked(obj)) {
709 DumpSpaces();
710 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700711 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700712 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700713 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
714 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700715 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700716}
717
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800718void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700719 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700720 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700721}
722
723void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700724 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700725 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700726}
727
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800728void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700729 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700730 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700731 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700732
733 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700734 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700735 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700736 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700737
738 // TODO: Update these atomically.
739 RuntimeStats* global_stats = Runtime::Current()->GetStats();
740 ++global_stats->allocated_objects;
741 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700742 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700743
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700744 // This is safe to do since the GC will never free objects which are neither in the allocation
745 // stack or the live bitmap.
746 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700747 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700748 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700749}
750
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700751void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700752 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
753 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700754
755 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700756 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700757 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700758 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700759
760 // TODO: Do this concurrently.
761 RuntimeStats* global_stats = Runtime::Current()->GetStats();
762 global_stats->freed_objects += freed_objects;
763 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700764 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700765}
766
Ian Rogers1d54e732013-05-02 21:10:01 -0700767mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
768 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700769 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800770 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
771 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
772 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
773 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700774 return NULL;
775 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700776 }
777
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700778 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700779}
780
Ian Rogers1d54e732013-05-02 21:10:01 -0700781mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700782 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
783 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700784 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700785 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700786
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800787 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700788 if (ptr != NULL) {
789 return ptr;
790 }
791
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700792 // The allocation failed. If the GC is running, block until it completes, and then retry the
793 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700794 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
795 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700796 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700797 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700798 if (ptr != NULL) {
799 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700800 }
801 }
802
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700803 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700804 for (size_t i = static_cast<size_t>(last_gc) + 1;
805 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700806 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700807 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700808 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700809 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700810 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700811 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
812 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700813 break;
814 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700815 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700816 run_gc = have_zygote_space_;
817 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700818 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700819 run_gc = true;
820 break;
821 default:
822 break;
823 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700824
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700825 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700826 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700827 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800828 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700829 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700830
831 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700832 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700833 if (ptr != NULL) {
834 return ptr;
835 }
836 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700837 }
838
839 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700840 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700841 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700842 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700843 return ptr;
844 }
845
Elliott Hughes81ff3182012-03-23 20:35:56 -0700846 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
847 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
848 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700849
Elliott Hughes418dfe72011-10-06 18:56:27 -0700850 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700851 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
852 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700853
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700854 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700855 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700856 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700857}
858
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700859void Heap::SetTargetHeapUtilization(float target) {
860 DCHECK_GT(target, 0.0f); // asserted in Java code
861 DCHECK_LT(target, 1.0f);
862 target_utilization_ = target;
863}
864
Ian Rogers1d54e732013-05-02 21:10:01 -0700865size_t Heap::GetObjectsAllocated() const {
866 size_t total = 0;
867 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
868 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
869 space::ContinuousSpace* space = *it;
870 if (space->IsDlMallocSpace()) {
871 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700872 }
873 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700874 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
875 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
876 space::DiscontinuousSpace* space = *it;
877 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
878 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700879 return total;
880}
881
Ian Rogers1d54e732013-05-02 21:10:01 -0700882size_t Heap::GetObjectsAllocatedEver() const {
883 size_t total = 0;
884 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
885 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
886 space::ContinuousSpace* space = *it;
887 if (space->IsDlMallocSpace()) {
888 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700889 }
890 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700891 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
892 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
893 space::DiscontinuousSpace* space = *it;
894 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
895 }
896 return total;
897}
898
899size_t Heap::GetBytesAllocatedEver() const {
900 size_t total = 0;
901 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
902 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
903 space::ContinuousSpace* space = *it;
904 if (space->IsDlMallocSpace()) {
905 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
906 }
907 }
908 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
909 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
910 space::DiscontinuousSpace* space = *it;
911 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
912 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700913 return total;
914}
915
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700916class InstanceCounter {
917 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800918 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700919 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800920 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700921 }
922
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800923 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800924 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800925 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800926 if (use_is_assignable_from_) {
927 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
928 ++counts_[i];
929 }
930 } else {
931 if (instance_class == classes_[i]) {
932 ++counts_[i];
933 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700934 }
935 }
936 }
937
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700938 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800939 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800940 bool use_is_assignable_from_;
941 uint64_t* const counts_;
942
943 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700944};
945
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800946void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800947 uint64_t* counts) {
948 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
949 // is empty, so the live bitmap is the only place we need to look.
950 Thread* self = Thread::Current();
951 self->TransitionFromRunnableToSuspended(kNative);
952 CollectGarbage(false);
953 self->TransitionFromSuspendedToRunnable();
954
955 InstanceCounter counter(classes, use_is_assignable_from, counts);
956 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700957 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700958}
959
Elliott Hughes3b78c942013-01-15 17:35:41 -0800960class InstanceCollector {
961 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800962 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800963 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
964 : class_(c), max_count_(max_count), instances_(instances) {
965 }
966
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800967 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
968 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800969 if (instance_class == class_) {
970 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800971 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800972 }
973 }
974 }
975
976 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800977 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800978 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800979 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800980
981 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
982};
983
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800984void Heap::GetInstances(mirror::Class* c, int32_t max_count,
985 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800986 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
987 // is empty, so the live bitmap is the only place we need to look.
988 Thread* self = Thread::Current();
989 self->TransitionFromRunnableToSuspended(kNative);
990 CollectGarbage(false);
991 self->TransitionFromSuspendedToRunnable();
992
993 InstanceCollector collector(c, max_count, instances);
994 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
995 GetLiveBitmap()->Visit(collector);
996}
997
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800998class ReferringObjectsFinder {
999 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001000 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1001 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001002 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1003 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1004 }
1005
1006 // For bitmap Visit.
1007 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1008 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001009 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001010 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001011 }
1012
1013 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001014 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
1015 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001016 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001018 }
1019 }
1020
1021 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001022 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001023 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001024 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001025
1026 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1027};
1028
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001029void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1030 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001031 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1032 // is empty, so the live bitmap is the only place we need to look.
1033 Thread* self = Thread::Current();
1034 self->TransitionFromRunnableToSuspended(kNative);
1035 CollectGarbage(false);
1036 self->TransitionFromSuspendedToRunnable();
1037
1038 ReferringObjectsFinder finder(o, max_count, referring_objects);
1039 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1040 GetLiveBitmap()->Visit(finder);
1041}
1042
Ian Rogers30fab402012-01-23 15:43:46 -08001043void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001044 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1045 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001046 Thread* self = Thread::Current();
1047 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001048 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001049}
1050
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001051void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001052 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001053 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1054 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001055 Thread* self = Thread::Current();
1056 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001057
1058 // Try to see if we have any Zygote spaces.
1059 if (have_zygote_space_) {
1060 return;
1061 }
1062
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001063 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1064
1065 {
1066 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001067 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001068 FlushAllocStack();
1069 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001070
Ian Rogers1d54e732013-05-02 21:10:01 -07001071 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1072 // of the remaining available heap memory.
1073 space::DlMallocSpace* zygote_space = alloc_space_;
1074 alloc_space_ = zygote_space->CreateZygoteSpace();
1075 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001076
Ian Rogers1d54e732013-05-02 21:10:01 -07001077 // Change the GC retention policy of the zygote space to only collect when full.
1078 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1079 AddContinuousSpace(alloc_space_);
1080 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001081
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001082 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001083 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001084 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1085 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1086 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001087 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001088 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001089}
1090
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001091void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001092 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1093 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001094 allocation_stack_->Reset();
1095}
1096
Ian Rogers1d54e732013-05-02 21:10:01 -07001097void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1098 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001099 mirror::Object** limit = stack->End();
1100 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1101 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001102 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001103 if (LIKELY(bitmap->HasAddress(obj))) {
1104 bitmap->Set(obj);
1105 } else {
1106 large_objects->Set(obj);
1107 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001108 }
1109}
1110
Ian Rogers1d54e732013-05-02 21:10:01 -07001111void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1112 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001113 mirror::Object** limit = stack->End();
1114 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1115 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001116 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001117 if (LIKELY(bitmap->HasAddress(obj))) {
1118 bitmap->Clear(obj);
1119 } else {
1120 large_objects->Clear(obj);
1121 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001122 }
1123}
1124
Ian Rogers1d54e732013-05-02 21:10:01 -07001125collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1126 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001127 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001128
1129 switch (gc_cause) {
1130 case kGcCauseForAlloc:
1131 ATRACE_BEGIN("GC (alloc)");
1132 break;
1133 case kGcCauseBackground:
1134 ATRACE_BEGIN("GC (background)");
1135 break;
1136 case kGcCauseExplicit:
1137 ATRACE_BEGIN("GC (explicit)");
1138 break;
1139 }
1140
Mathieu Chartier65db8802012-11-20 12:36:46 -08001141 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001142 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001143
Ian Rogers120f1c72012-09-28 17:17:10 -07001144 if (self->IsHandlingStackOverflow()) {
1145 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1146 }
1147
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001148 // Ensure there is only one GC at a time.
1149 bool start_collect = false;
1150 while (!start_collect) {
1151 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001152 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001153 if (!is_gc_running_) {
1154 is_gc_running_ = true;
1155 start_collect = true;
1156 }
1157 }
1158 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001159 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001160 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1161 // Not doing at the moment to ensure soft references are cleared.
1162 }
1163 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001164 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001165
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001166 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1167 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1168 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1169 }
1170
Ian Rogers1d54e732013-05-02 21:10:01 -07001171 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001172 uint64_t gc_start_size = GetBytesAllocated();
1173 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001174 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001175 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1176 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001177 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001178 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001179 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001180 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1181 }
1182
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001183 if (gc_type == collector::kGcTypeSticky &&
1184 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1185 gc_type = collector::kGcTypePartial;
1186 }
1187
Ian Rogers1d54e732013-05-02 21:10:01 -07001188 DCHECK_LT(gc_type, collector::kGcTypeMax);
1189 DCHECK_NE(gc_type, collector::kGcTypeNone);
1190 collector::MarkSweep* collector = NULL;
1191 typedef std::vector<collector::MarkSweep*>::iterator It;
1192 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1193 it != end; ++it) {
1194 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001195 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1196 collector = cur_collector;
1197 break;
1198 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001199 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001200 CHECK(collector != NULL)
1201 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1202 << " and type=" << gc_type;
1203 collector->clear_soft_references_ = clear_soft_references;
1204 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001205 total_objects_freed_ever_ += collector->GetFreedObjects();
1206 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001207
Ian Rogers1d54e732013-05-02 21:10:01 -07001208 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001209 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1210 bool was_slow = duration > kSlowGcThreshold ||
1211 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1212 for (size_t i = 0; i < pauses.size(); ++i) {
1213 if (pauses[i] > kLongGcPauseThreshold) {
1214 was_slow = true;
1215 }
1216 }
1217
1218 if (was_slow) {
1219 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001220 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001221 const size_t total_memory = GetTotalMemory();
1222 std::ostringstream pause_string;
1223 for (size_t i = 0; i < pauses.size(); ++i) {
1224 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1225 << ((i != pauses.size() - 1) ? ", " : "");
1226 }
1227 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001228 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1229 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1230 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1231 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001232 if (VLOG_IS_ON(heap)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001233 LOG(INFO) << Dumpable<base::NewTimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001234 }
1235 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001236
Ian Rogers15bf2d32012-08-28 17:33:04 -07001237 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001238 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001239 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001240 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001241 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001242 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001243 }
1244 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001245 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001246 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001247 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001248}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001249
Ian Rogers1d54e732013-05-02 21:10:01 -07001250void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::NewTimingLogger& timings,
1251 collector::GcType gc_type) {
1252 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001253 // 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 -07001254 // cards.
1255 return;
1256 }
1257
1258 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001259 if (gc_type == collector::kGcTypePartial) {
1260 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001261 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001262
Ian Rogers1d54e732013-05-02 21:10:01 -07001263 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001264 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001265 }
1266
1267 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001268 timings.NewSplit("UpdateModUnionTable");
1269 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001270
1271 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001272 timings.NewSplit("MarkImageToAllocSpaceReferences");
1273 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001274}
1275
Ian Rogers1d54e732013-05-02 21:10:01 -07001276static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001277 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001278 if (root == obj) {
1279 LOG(INFO) << "Object " << obj << " is a root";
1280 }
1281}
1282
1283class ScanVisitor {
1284 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001285 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001286 LOG(INFO) << "Would have rescanned object " << obj;
1287 }
1288};
1289
Ian Rogers1d54e732013-05-02 21:10:01 -07001290// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001291class VerifyReferenceVisitor {
1292 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001293 VerifyReferenceVisitor(Heap* heap)
1294 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
1295 : heap_(heap), failed_(false) {
1296 }
1297
1298 bool Failed() const {
1299 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001300 }
1301
1302 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001303 // analysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001304 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
Ian Rogers1d54e732013-05-02 21:10:01 -07001305 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001306 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001307 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001308 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1309 accounting::CardTable* card_table = heap_->GetCardTable();
1310 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1311 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001312
Ian Rogers1d54e732013-05-02 21:10:01 -07001313 if (obj != NULL) {
1314 byte* card_addr = card_table->CardFromAddr(obj);
1315 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1316 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1317 << "\nObj type " << PrettyTypeOf(obj)
1318 << "\nRef type " << PrettyTypeOf(ref);
1319 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1320 void* cover_begin = card_table->AddrFromCard(card_addr);
1321 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1322 accounting::CardTable::kCardSize);
1323 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1324 << "-" << cover_end;
1325 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001326
Ian Rogers1d54e732013-05-02 21:10:01 -07001327 // Print out how the object is live.
1328 if (bitmap != NULL && bitmap->Test(obj)) {
1329 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1330 }
1331 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
1332 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1333 }
1334 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
1335 LOG(ERROR) << "Object " << obj << " found in live stack";
1336 }
1337 // Attempt to see if the card table missed the reference.
1338 ScanVisitor scan_visitor;
1339 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1340 card_table->Scan(bitmap, byte_cover_begin,
1341 byte_cover_begin + accounting::CardTable::kCardSize,
1342 scan_visitor, VoidFunctor());
1343
1344 // Search to see if any of the roots reference our object.
1345 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1346 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1347
1348 // Search to see if any of the roots reference our reference.
1349 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1350 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1351 } else {
1352 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001353 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001354 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1355 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001356 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001357 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001358 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001359 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001360 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1361 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1362 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001363 }
1364 }
1365
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001366 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001367 return heap_->IsLiveObjectLocked(obj);
1368 }
1369
1370 static void VerifyRoots(const mirror::Object* root, void* arg) {
1371 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1372 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001373 }
1374
1375 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001376 Heap* const heap_;
1377 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001378};
1379
Ian Rogers1d54e732013-05-02 21:10:01 -07001380// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001381class VerifyObjectVisitor {
1382 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001383 VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001384 }
1385
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001386 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001387 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001388 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1389 // be live or else how did we find it in the live bitmap?
1390 VerifyReferenceVisitor visitor(heap_);
1391 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1392 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001393 }
1394
1395 bool Failed() const {
1396 return failed_;
1397 }
1398
1399 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001400 Heap* const heap_;
1401 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001402};
1403
1404// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001405bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001406 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001407 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001408 allocation_stack_->Sort();
1409 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001410 // Perform the verification.
1411 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001412 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001413 GetLiveBitmap()->Visit(visitor);
1414 // We don't want to verify the objects in the allocation stack since they themselves may be
1415 // pointing to dead objects if they are not reachable.
1416 if (visitor.Failed()) {
1417 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001418 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001419 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001420 return true;
1421}
1422
1423class VerifyReferenceCardVisitor {
1424 public:
1425 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1426 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1427 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001428 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001429 }
1430
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001431 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1432 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001433 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1434 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001435 // Filter out class references since changing an object's class does not mark the card as dirty.
1436 // Also handles large objects, since the only reference they hold is a class reference.
1437 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001438 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001439 // If the object is not dirty and it is referencing something in the live stack other than
1440 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001441 if (!card_table->AddrIsInCardTable(obj)) {
1442 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1443 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001444 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001445 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1446 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001447 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
1448 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1449 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001450 LOG(ERROR) << "Object " << obj << " found in live stack";
1451 }
1452 if (heap_->GetLiveBitmap()->Test(obj)) {
1453 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1454 }
1455 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1456 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1457
1458 // Print which field of the object is dead.
1459 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001460 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001461 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001462 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1463 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001464 CHECK(fields != NULL);
1465 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001466 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001467 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1468 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1469 << PrettyField(cur);
1470 break;
1471 }
1472 }
1473 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001474 const mirror::ObjectArray<mirror::Object>* object_array =
1475 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001476 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1477 if (object_array->Get(i) == ref) {
1478 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1479 }
1480 }
1481 }
1482
1483 *failed_ = true;
1484 }
1485 }
1486 }
1487 }
1488
1489 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001490 Heap* const heap_;
1491 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001492};
1493
1494class VerifyLiveStackReferences {
1495 public:
1496 VerifyLiveStackReferences(Heap* heap)
1497 : heap_(heap),
1498 failed_(false) {
1499
1500 }
1501
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001502 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001503 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1504 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001505 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001506 }
1507
1508 bool Failed() const {
1509 return failed_;
1510 }
1511
1512 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001513 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001514 bool failed_;
1515};
1516
1517bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001518 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001519
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001520 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001521 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001522 VerifyLiveStackReferences visitor(this);
1523 GetLiveBitmap()->Visit(visitor);
1524
1525 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001526 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001527 visitor(*it);
1528 }
1529
1530 if (visitor.Failed()) {
1531 DumpSpaces();
1532 return false;
1533 }
1534 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001535}
1536
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001537void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001538 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001539
1540 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001541 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001542 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001543 }
1544}
1545
Ian Rogers1d54e732013-05-02 21:10:01 -07001546void Heap::ProcessCards(base::NewTimingLogger& timings) {
1547 // Clear cards and keep track of cards cleared in the mod-union table.
1548 typedef std::vector<space::ContinuousSpace*>::iterator It;
1549 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1550 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001551 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001552 timings.NewSplit("ModUnionClearCards");
1553 image_mod_union_table_->ClearCards(space);
1554 } else if (space->IsZygoteSpace()) {
1555 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001556 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001557 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001558 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1559 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001560 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001561 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001562 }
1563 }
1564}
1565
Ian Rogers1d54e732013-05-02 21:10:01 -07001566void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001567 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1568 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001569
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001570 if (verify_pre_gc_heap_) {
1571 thread_list->SuspendAll();
1572 {
1573 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1574 if (!VerifyHeapReferences()) {
1575 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1576 }
1577 }
1578 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001579 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001580
1581 // Check that all objects which reference things in the live stack are on dirty cards.
1582 if (verify_missing_card_marks_) {
1583 thread_list->SuspendAll();
1584 {
1585 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1586 SwapStacks();
1587 // Sort the live stack so that we can quickly binary search it later.
1588 if (!VerifyMissingCardMarks()) {
1589 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1590 }
1591 SwapStacks();
1592 }
1593 thread_list->ResumeAll();
1594 }
1595
1596 if (verify_mod_union_table_) {
1597 thread_list->SuspendAll();
1598 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1599 zygote_mod_union_table_->Update();
1600 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001601 image_mod_union_table_->Update();
1602 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001603 thread_list->ResumeAll();
1604 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001605}
1606
Ian Rogers1d54e732013-05-02 21:10:01 -07001607void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001608 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001609
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001610 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1611 // reachable objects.
1612 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001613 Thread* self = Thread::Current();
1614 CHECK_NE(self->GetState(), kRunnable);
1615 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001616 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001617 {
1618 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1619 // Swapping bound bitmaps does nothing.
1620 gc->SwapBitmaps();
1621 if (!VerifyHeapReferences()) {
1622 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1623 }
1624 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001625 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001626 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001627 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001628 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001629}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001630
Ian Rogers1d54e732013-05-02 21:10:01 -07001631void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001632 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001633
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001634 if (verify_system_weaks_) {
1635 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001636 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001637 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001638 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001639}
1640
Ian Rogers1d54e732013-05-02 21:10:01 -07001641collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1642 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001643 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001644 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001645 bool do_wait;
1646 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001647 {
1648 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001649 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001650 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001651 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001652 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001653 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001654 // We must wait, change thread state then sleep on gc_complete_cond_;
1655 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1656 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001657 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001658 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001659 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001660 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001661 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001662 wait_time = NanoTime() - wait_start;;
1663 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001665 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001666 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1667 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001668 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001669 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001670 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001671 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001672}
1673
Elliott Hughesc967f782012-04-16 10:23:15 -07001674void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001675 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001676 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001677 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001678}
1679
1680size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001681 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001682}
1683
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001684void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001685 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001686 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001687 << PrettySize(GetMaxMemory());
1688 max_allowed_footprint = GetMaxMemory();
1689 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001690 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001691}
1692
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001693void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001694 // We know what our utilization is at this moment.
1695 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001696 const size_t bytes_allocated = GetBytesAllocated();
1697 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001698 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001699
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001700 size_t target_size;
1701 if (gc_type != collector::kGcTypeSticky) {
1702 // Grow the heap for non sticky GC.
1703 target_size = bytes_allocated / GetTargetHeapUtilization();
1704 if (target_size > bytes_allocated + max_free_) {
1705 target_size = bytes_allocated + max_free_;
1706 } else if (target_size < bytes_allocated + min_free_) {
1707 target_size = bytes_allocated + min_free_;
1708 }
1709 next_gc_type_ = collector::kGcTypeSticky;
1710 } else {
1711 // Based on how close the current heap size is to the target size, decide
1712 // whether or not to do a partial or sticky GC next.
1713 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1714 next_gc_type_ = collector::kGcTypeSticky;
1715 } else {
1716 next_gc_type_ = collector::kGcTypePartial;
1717 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001718
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001719 // If we have freed enough memory, shrink the heap back down.
1720 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1721 target_size = bytes_allocated + max_free_;
1722 } else {
1723 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1724 }
1725 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001726 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001727
Ian Rogers1d54e732013-05-02 21:10:01 -07001728 // Calculate when to perform the next ConcurrentGC.
1729 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001730 // Calculate the estimated GC duration.
1731 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1732 // Estimate how many remaining bytes we will have when we need to start the next GC.
1733 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001734 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1735 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1736 // A never going to happen situation that from the estimated allocation rate we will exceed
1737 // the applications entire footprint with the given estimated allocation rate. Schedule
1738 // another GC straight away.
1739 concurrent_start_bytes_ = bytes_allocated;
1740 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001741 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1742 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1743 // right away.
1744 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001745 }
1746 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1747 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1748 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001749}
1750
jeffhaoc1160702011-10-27 15:48:45 -07001751void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001752 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001753 alloc_space_->ClearGrowthLimit();
1754}
1755
Elliott Hughesadb460d2011-10-05 17:02:34 -07001756void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001757 MemberOffset reference_queue_offset,
1758 MemberOffset reference_queueNext_offset,
1759 MemberOffset reference_pendingNext_offset,
1760 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001761 reference_referent_offset_ = reference_referent_offset;
1762 reference_queue_offset_ = reference_queue_offset;
1763 reference_queueNext_offset_ = reference_queueNext_offset;
1764 reference_pendingNext_offset_ = reference_pendingNext_offset;
1765 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1766 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1767 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1768 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1769 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1770 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1771}
1772
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001773mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001774 DCHECK(reference != NULL);
1775 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001776 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001777}
1778
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001779void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001780 DCHECK(reference != NULL);
1781 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1782 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1783}
1784
1785// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001786bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001787 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001788 const mirror::Object* queue =
1789 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1790 const mirror::Object* queue_next =
1791 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001792 return (queue != NULL) && (queue_next == NULL);
1793}
1794
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001795void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001796 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001797 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1798 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001799 EnqueuePendingReference(ref, cleared_reference_list);
1800}
1801
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001802void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001803 DCHECK(ref != NULL);
1804 DCHECK(list != NULL);
1805
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001806 // TODO: Remove this lock, use atomic stacks for storing references.
1807 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001808 if (*list == NULL) {
1809 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1810 *list = ref;
1811 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001812 mirror::Object* head =
1813 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001814 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1815 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1816 }
1817}
1818
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001819mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001820 DCHECK(list != NULL);
1821 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001822 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1823 false);
1824 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001825
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001826 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1827 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001828 if (*list == head) {
1829 ref = *list;
1830 *list = NULL;
1831 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001832 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1833 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001834 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1835 ref = head;
1836 }
1837 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1838 return ref;
1839}
1840
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001841void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001842 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001843 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001844 ArgArray arg_array(NULL, 0);
1845 arg_array.Append(reinterpret_cast<uint32_t>(object));
1846 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001847 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001848}
1849
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001850void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001851 DCHECK(cleared != NULL);
1852 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001853 // When a runtime isn't started there are no reference queues to care about so ignore.
1854 if (LIKELY(Runtime::Current()->IsStarted())) {
1855 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001856 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001857 ArgArray arg_array(NULL, 0);
1858 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1859 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001860 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001861 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001862 *cleared = NULL;
1863 }
1864}
1865
Ian Rogers1f539342012-10-03 21:09:42 -07001866void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001867 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001868 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001869 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001870 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001871 !runtime->IsConcurrentGcEnabled()) {
1872 return;
1873 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001874 {
1875 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1876 if (runtime->IsShuttingDown()) {
1877 return;
1878 }
1879 }
1880 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001881 return;
1882 }
1883
Ian Rogers120f1c72012-09-28 17:17:10 -07001884 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001885 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1886 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001887 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1888 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001889 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001890}
1891
Ian Rogers81d425b2012-09-27 16:03:43 -07001892void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001893 {
1894 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001895 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001896 return;
1897 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001898 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001899
Mathieu Chartier65db8802012-11-20 12:36:46 -08001900 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001901 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001902 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001903 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001904}
1905
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001906void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001907 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1908 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1909 // a space it will hold its lock and can become a cause of jank.
1910 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1911 // forking.
1912
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001913 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1914 // because that only marks object heads, so a large array looks like lots of empty space. We
1915 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1916 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1917 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1918 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001919 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001920 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001921 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1922 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001923 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1924 // heap trim occurred in the last two seconds.
1925 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001926 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001927
1928 Thread* self = Thread::Current();
1929 {
1930 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1931 Runtime* runtime = Runtime::Current();
1932 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1933 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1934 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1935 // as we don't hold the lock while requesting the trim).
1936 return;
1937 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001938 }
Ian Rogers48931882013-01-22 14:35:16 -08001939
1940 SchedPolicy policy;
1941 get_sched_policy(self->GetTid(), &policy);
1942 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1943 // Don't trim the heap if we are a foreground or audio app.
1944 return;
1945 }
1946
Ian Rogers1d54e732013-05-02 21:10:01 -07001947 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001948 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001949 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1950 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001951 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1952 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001953 CHECK(!env->ExceptionCheck());
1954}
1955
Ian Rogers48931882013-01-22 14:35:16 -08001956size_t Heap::Trim() {
1957 // Handle a requested heap trim on a thread outside of the main GC thread.
1958 return alloc_space_->Trim();
1959}
1960
Ian Rogers1d54e732013-05-02 21:10:01 -07001961} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001962} // namespace art