blob: 7bd86872eef4ccc14781ff9df941b8dc59404ab3 [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 Chartier80de7a62012-11-27 17:21:50 -0800169 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700170 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700171 max_allowed_footprint_(initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -0700172 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
173 : std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700174 sticky_gc_count_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700175 sticky_to_partial_gc_ratio_(10),
176 total_bytes_freed_ever_(0),
177 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700178 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800179 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700180 verify_missing_card_marks_(false),
181 verify_system_weaks_(false),
182 verify_pre_gc_heap_(false),
183 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700184 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700185 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700186 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700187 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800188 allocation_rate_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700189 max_allocation_stack_size_(kDesiredHeapVerification > kNoHeapVerification? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800190 reference_referent_offset_(0),
191 reference_queue_offset_(0),
192 reference_queueNext_offset_(0),
193 reference_pendingNext_offset_(0),
194 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700195 min_free_(min_free),
196 max_free_(max_free),
197 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700198 total_wait_time_(0),
199 measure_allocation_time_(false),
200 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700201 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800202 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800203 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700204 }
205
Ian Rogers1d54e732013-05-02 21:10:01 -0700206 live_bitmap_.reset(new accounting::HeapBitmap(this));
207 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700208
Ian Rogers30fab402012-01-23 15:43:46 -0800209 // Requested begin for the alloc space, to follow the mapped image and oat files
210 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800211 std::string image_file_name(original_image_file_name);
212 if (!image_file_name.empty()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700213 space::ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700214
Brian Carlstrom5643b782012-02-05 12:32:53 -0800215 if (OS::FileExists(image_file_name.c_str())) {
216 // If the /system file exists, it should be up-to-date, don't try to generate
Ian Rogers1d54e732013-05-02 21:10:01 -0700217 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800218 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -0700219 // If the /system file didn't exist, we need to use one from the dalvik-cache.
Brian Carlstrom5643b782012-02-05 12:32:53 -0800220 // If the cache file exists, try to open, but if it fails, regenerate.
221 // If it does not exist, generate.
Brian Carlstrom7675e162013-06-10 16:18:04 -0700222 image_file_name = GetDalvikCacheFilenameOrDie(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800223 if (OS::FileExists(image_file_name.c_str())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700224 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800225 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700226 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700227 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700228 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800229 }
230 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700231
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700232 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700233 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800234 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
235 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800236 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
237 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700238
239 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
240 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800241 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700242 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
243 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800244 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700245
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800246 if (oat_file_end_addr > requested_begin) {
247 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700248 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700249 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700250 }
251
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700252 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700253 const bool kUseFreeListSpaceForLOS = false;
254 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700255 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700256 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700257 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700258 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700259 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
260 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700261
Ian Rogers1d54e732013-05-02 21:10:01 -0700262 alloc_space_ = space::DlMallocSpace::Create("alloc space",
263 initial_size,
264 growth_limit, capacity,
265 requested_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700266 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700267 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700268 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700269
Ian Rogers1d54e732013-05-02 21:10:01 -0700270 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
271 byte* heap_begin = continuous_spaces_.front()->Begin();
272 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
273 if (continuous_spaces_.back()->IsDlMallocSpace()) {
274 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700275 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700276
Ian Rogers30fab402012-01-23 15:43:46 -0800277 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700278 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700279 typedef std::vector<space::ContinuousSpace*>::iterator It;
280 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
281 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800282 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700283 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700284 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800285 }
286 }
287
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800288 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700289 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700290 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700291
Ian Rogers1d54e732013-05-02 21:10:01 -0700292 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
293 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700294
Ian Rogers1d54e732013-05-02 21:10:01 -0700295 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700296 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700297
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700298 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700299 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800301 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700302 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700303 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
304 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
305 max_allocation_stack_size_));
306 live_stack_.reset(accounting::ObjectStack::Create("live stack",
307 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700308
Mathieu Chartier65db8802012-11-20 12:36:46 -0800309 // It's still too early to take a lock because there are no threads yet, but we can create locks
310 // now. We don't create it earlier to make it clear that you can't use locks during heap
311 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700312 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700313 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
314 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700315
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700316 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700317 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700318
Ian Rogers1d54e732013-05-02 21:10:01 -0700319 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800320 last_gc_size_ = GetBytesAllocated();
321
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800322 // Create our garbage collectors.
323 for (size_t i = 0; i < 2; ++i) {
324 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700325 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
326 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
327 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700328 }
329
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800330 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800331 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800332 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700333 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700334}
335
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700336void Heap::CreateThreadPool() {
337 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
338 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
339 // workers to complete.
Ian Rogers1d54e732013-05-02 21:10:01 -0700340 thread_pool_.reset(new ThreadPool(1)); // new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700341}
342
343void Heap::DeleteThreadPool() {
344 thread_pool_.reset(NULL);
345}
346
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700347// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700348struct ContinuousSpaceSorter {
349 bool operator ()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700350 return a->Begin() < b->Begin();
351 }
352};
353
Ian Rogers1d54e732013-05-02 21:10:01 -0700354void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700355 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700356 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700357 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700358 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700359 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700360 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
361 continuous_spaces_.push_back(space);
362 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
363 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700364 }
365
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700366 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700367 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700368
369 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
370 // avoid redundant marking.
371 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700372 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
373 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
374 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700375 if (space->IsImageSpace()) {
376 DCHECK(!seen_zygote);
377 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700378 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700379 DCHECK(!seen_alloc);
380 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700381 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700382 seen_alloc = true;
383 }
384 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800385}
386
Ian Rogers1d54e732013-05-02 21:10:01 -0700387void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
388 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
389 DCHECK(space != NULL);
390 DCHECK(space->GetLiveObjects() != NULL);
391 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
392 DCHECK(space->GetMarkObjects() != NULL);
393 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
394 discontinuous_spaces_.push_back(space);
395}
396
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700397void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700398 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700399 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700400 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800401
402 // Dump cumulative loggers for each GC type.
403 // TODO: C++0x
404 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700405 typedef std::vector<collector::MarkSweep*>::const_iterator It;
406 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800407 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700408 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800409 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800410 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700411 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800412 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700413 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800414 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
415 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
416 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700417 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
418 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
419 << collector->GetName() << " freed: " << freed_objects
420 << " objects with total size " << PrettySize(freed_bytes) << "\n"
421 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
422 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800423 total_duration += total_ns;
424 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700425 }
426 }
427 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700428 size_t total_objects_allocated = GetObjectsAllocatedEver();
429 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700430 if (total_duration != 0) {
431 const double total_seconds = double(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700432 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
433 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700434 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700435 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700436 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700437 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700438 os << "Total number of allocations: " << total_objects_allocated << "\n";
439 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700440 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700441 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
442 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
443 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700444 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700445 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
446 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700447}
448
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800449Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700450 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700451 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700452 }
453
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800454 STLDeleteElements(&mark_sweep_collectors_);
455
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700456 // If we don't reset then the mark stack complains in it's destructor.
457 allocation_stack_->Reset();
458 live_stack_->Reset();
459
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800460 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800461 // We can't take the heap lock here because there might be a daemon thread suspended with the
462 // heap lock held. We know though that no non-daemon threads are executing, and we know that
463 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
464 // 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 -0700465 STLDeleteElements(&continuous_spaces_);
466 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700468 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700469}
470
Ian Rogers1d54e732013-05-02 21:10:01 -0700471space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
472 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700473 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700474 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
475 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700476 if ((*it)->Contains(obj)) {
477 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700478 }
479 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700480 if (!fail_ok) {
481 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
482 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700483 return NULL;
484}
485
Ian Rogers1d54e732013-05-02 21:10:01 -0700486space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
487 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700488 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700489 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
490 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
491 if ((*it)->Contains(obj)) {
492 return *it;
493 }
494 }
495 if (!fail_ok) {
496 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
497 }
498 return NULL;
499}
500
501space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
502 space::Space* result = FindContinuousSpaceFromObject(obj, true);
503 if (result != NULL) {
504 return result;
505 }
506 return FindDiscontinuousSpaceFromObject(obj, true);
507}
508
509space::ImageSpace* Heap::GetImageSpace() const {
510 // TODO: C++0x auto
511 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
512 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700513 if ((*it)->IsImageSpace()) {
514 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700515 }
516 }
517 return NULL;
518}
519
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700520static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700521 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700522 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700523 size_t chunk_free_bytes = chunk_size - used_bytes;
524 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
525 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700526 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700527}
528
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800529mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
530 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700531 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
532 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800533 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700534
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800535 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700536 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700537 uint64_t allocation_start = 0;
538 if (measure_allocation_time_) {
539 allocation_start = NanoTime();
540 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700541
542 // We need to have a zygote space or else our newly allocated large object can end up in the
543 // Zygote resulting in it being prematurely freed.
544 // We can only do this for primive objects since large objects will not be within the card table
545 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers22a20862013-03-16 16:34:57 -0700546 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700547 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700548 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700549 // Make sure that our large object didn't get placed anywhere within the space interval or else
550 // it breaks the immune range.
551 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700552 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
553 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700554 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700555 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700556
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700557 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700558 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700559 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700560 }
561
Mathieu Chartier037813d2012-08-23 16:44:59 -0700562 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700563 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700564
565 // Record allocation after since we want to use the atomic add for the atomic fence to guard
566 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700567 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700568
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700569 if (Dbg::IsAllocTrackingEnabled()) {
570 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700571 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700572 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700573 // We already have a request pending, no reason to start more until we update
574 // concurrent_start_bytes_.
575 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700576 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800577 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700578 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700579 }
580 VerifyObject(obj);
581
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700582 if (measure_allocation_time_) {
583 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
584 }
585
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700586 return obj;
587 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800588 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700589 int64_t total_bytes_free = GetFreeMemory();
Ian Rogers1d54e732013-05-02 21:10:01 -0700590 uint64_t alloc_space_size = alloc_space_->GetBytesAllocated();
591 uint64_t large_object_size = large_object_space_->GetObjectsAllocated();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800592 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
593 << " free bytes; allocation space size " << alloc_space_size
594 << "; large object space size " << large_object_size;
595 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
596 if (total_bytes_free >= byte_count) {
597 size_t max_contiguous_allocation = 0;
598 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700599 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
600 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
601 space::ContinuousSpace* space = *it;
602 if (space->IsDlMallocSpace()) {
603 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800604 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700605 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800606 oss << "; failed due to fragmentation (largest possible contiguous allocation "
607 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700608 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800609 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700610 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700611}
612
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800613bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700614 // Note: we deliberately don't take the lock here, and mustn't test anything that would
615 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700616 if (obj == NULL) {
617 return true;
618 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700619 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700620 return false;
621 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700622 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700623}
624
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800625bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700626 //Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
627 if (obj == NULL) {
628 return false;
629 }
630 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
631 return false;
632 }
633 space::ContinuousSpace* cont_space = FindContinuousSpaceFromObject(obj, true);
634 if (cont_space != NULL) {
635 if (cont_space->GetLiveBitmap()->Test(obj)) {
636 return true;
637 }
638 } else {
639 space::DiscontinuousSpace* disc_space = FindDiscontinuousSpaceFromObject(obj, true);
640 if (disc_space != NULL) {
641 if (disc_space->GetLiveObjects()->Test(obj)) {
642 return true;
643 }
644 }
645 }
646 for (size_t i = 0; i < 5; ++i) {
647 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
648 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
649 return true;
650 }
651 NanoSleep(MsToNs(10));
652 }
653 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700654}
655
Ian Rogers04d7aa92013-03-16 14:29:17 -0700656void Heap::VerifyObjectImpl(const mirror::Object* obj) {
657 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700658 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700659 return;
660 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700661 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700662}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700663
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700664void Heap::DumpSpaces() {
665 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700666 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
667 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
668 space::ContinuousSpace* space = *it;
669 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
670 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700671 LOG(INFO) << space << " " << *space << "\n"
672 << live_bitmap << " " << *live_bitmap << "\n"
673 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700674 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700675 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
676 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
677 space::DiscontinuousSpace* space = *it;
678 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700679 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700680}
681
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800682void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800683 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700684 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700685 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800686 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
687 return;
688 }
689 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
690 mirror::Object::ClassOffset().Int32Value();
691 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
692 if (UNLIKELY(c == NULL)) {
693 LOG(FATAL) << "Null class in object: " << obj;
694 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
695 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
696 }
697 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
698 // Note: we don't use the accessors here as they have internal sanity checks
699 // that we don't want to run
700 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
701 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
702 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
703 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
704 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700705
Ian Rogers62d6c772013-02-27 08:32:07 -0800706 if (verify_object_mode_ != kVerifyAllFast) {
707 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
708 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700709 if (!IsLiveObjectLocked(obj)) {
710 DumpSpaces();
711 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700712 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700713 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700714 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
715 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700716 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700717}
718
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800719void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700720 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700721 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700722}
723
724void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700725 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700726 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700727}
728
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800729void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700730 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700731 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700732 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700733
734 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700735 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700736 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700737 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700738
739 // TODO: Update these atomically.
740 RuntimeStats* global_stats = Runtime::Current()->GetStats();
741 ++global_stats->allocated_objects;
742 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700743 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700744
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700745 // This is safe to do since the GC will never free objects which are neither in the allocation
746 // stack or the live bitmap.
747 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700748 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700749 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700750}
751
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700752void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700753 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
754 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700755
756 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700757 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700758 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700759 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700760
761 // TODO: Do this concurrently.
762 RuntimeStats* global_stats = Runtime::Current()->GetStats();
763 global_stats->freed_objects += freed_objects;
764 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700765 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700766}
767
Ian Rogers1d54e732013-05-02 21:10:01 -0700768mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
769 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700770 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800771 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
772 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
773 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
774 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700775 return NULL;
776 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700777 }
778
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700779 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700780}
781
Ian Rogers1d54e732013-05-02 21:10:01 -0700782mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700783 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
784 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700785 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700786 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700787
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800788 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700789 if (ptr != NULL) {
790 return ptr;
791 }
792
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700793 // The allocation failed. If the GC is running, block until it completes, and then retry the
794 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700795 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
796 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700797 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700798 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700799 if (ptr != NULL) {
800 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700801 }
802 }
803
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700804 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700805 for (size_t i = static_cast<size_t>(last_gc) + 1;
806 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700807 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700808 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700809 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700810 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700811 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700812 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
813 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700814 break;
815 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700816 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700817 run_gc = have_zygote_space_;
818 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700819 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700820 run_gc = true;
821 break;
822 default:
823 break;
824 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700825
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700826 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700827 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700828 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800829 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700830 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700831
832 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700833 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700834 if (ptr != NULL) {
835 return ptr;
836 }
837 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700838 }
839
840 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700841 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700842 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700843 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700844 return ptr;
845 }
846
Elliott Hughes81ff3182012-03-23 20:35:56 -0700847 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
848 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
849 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700850
Elliott Hughes418dfe72011-10-06 18:56:27 -0700851 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700852 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
853 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700854
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700855 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700856 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700857 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700858}
859
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700860void Heap::SetTargetHeapUtilization(float target) {
861 DCHECK_GT(target, 0.0f); // asserted in Java code
862 DCHECK_LT(target, 1.0f);
863 target_utilization_ = target;
864}
865
Ian Rogers1d54e732013-05-02 21:10:01 -0700866size_t Heap::GetObjectsAllocated() const {
867 size_t total = 0;
868 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
869 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
870 space::ContinuousSpace* space = *it;
871 if (space->IsDlMallocSpace()) {
872 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700873 }
874 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700875 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
876 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
877 space::DiscontinuousSpace* space = *it;
878 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
879 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700880 return total;
881}
882
Ian Rogers1d54e732013-05-02 21:10:01 -0700883size_t Heap::GetObjectsAllocatedEver() const {
884 size_t total = 0;
885 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
886 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
887 space::ContinuousSpace* space = *it;
888 if (space->IsDlMallocSpace()) {
889 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700890 }
891 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700892 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
893 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
894 space::DiscontinuousSpace* space = *it;
895 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
896 }
897 return total;
898}
899
900size_t Heap::GetBytesAllocatedEver() const {
901 size_t total = 0;
902 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
903 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
904 space::ContinuousSpace* space = *it;
905 if (space->IsDlMallocSpace()) {
906 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
907 }
908 }
909 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
910 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
911 space::DiscontinuousSpace* space = *it;
912 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
913 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700914 return total;
915}
916
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700917class InstanceCounter {
918 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800919 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700920 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800921 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700922 }
923
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800924 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800925 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800926 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800927 if (use_is_assignable_from_) {
928 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
929 ++counts_[i];
930 }
931 } else {
932 if (instance_class == classes_[i]) {
933 ++counts_[i];
934 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700935 }
936 }
937 }
938
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700939 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800940 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800941 bool use_is_assignable_from_;
942 uint64_t* const counts_;
943
944 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700945};
946
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800947void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800948 uint64_t* counts) {
949 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
950 // is empty, so the live bitmap is the only place we need to look.
951 Thread* self = Thread::Current();
952 self->TransitionFromRunnableToSuspended(kNative);
953 CollectGarbage(false);
954 self->TransitionFromSuspendedToRunnable();
955
956 InstanceCounter counter(classes, use_is_assignable_from, counts);
957 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700958 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700959}
960
Elliott Hughes3b78c942013-01-15 17:35:41 -0800961class InstanceCollector {
962 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800963 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800964 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
965 : class_(c), max_count_(max_count), instances_(instances) {
966 }
967
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800968 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
969 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800970 if (instance_class == class_) {
971 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800972 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800973 }
974 }
975 }
976
977 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800978 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800979 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800980 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800981
982 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
983};
984
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800985void Heap::GetInstances(mirror::Class* c, int32_t max_count,
986 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800987 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
988 // is empty, so the live bitmap is the only place we need to look.
989 Thread* self = Thread::Current();
990 self->TransitionFromRunnableToSuspended(kNative);
991 CollectGarbage(false);
992 self->TransitionFromSuspendedToRunnable();
993
994 InstanceCollector collector(c, max_count, instances);
995 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
996 GetLiveBitmap()->Visit(collector);
997}
998
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800999class ReferringObjectsFinder {
1000 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001001 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1002 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001003 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1004 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1005 }
1006
1007 // For bitmap Visit.
1008 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1009 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001010 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001011 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001012 }
1013
1014 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001015 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
1016 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001017 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001018 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001019 }
1020 }
1021
1022 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001023 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001024 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001025 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001026
1027 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1028};
1029
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001030void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1031 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001032 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1033 // is empty, so the live bitmap is the only place we need to look.
1034 Thread* self = Thread::Current();
1035 self->TransitionFromRunnableToSuspended(kNative);
1036 CollectGarbage(false);
1037 self->TransitionFromSuspendedToRunnable();
1038
1039 ReferringObjectsFinder finder(o, max_count, referring_objects);
1040 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1041 GetLiveBitmap()->Visit(finder);
1042}
1043
Ian Rogers30fab402012-01-23 15:43:46 -08001044void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001045 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1046 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001047 Thread* self = Thread::Current();
1048 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001049 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001050}
1051
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001052void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001053 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001054 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1055 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001056 Thread* self = Thread::Current();
1057 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001058
1059 // Try to see if we have any Zygote spaces.
1060 if (have_zygote_space_) {
1061 return;
1062 }
1063
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001064 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1065
1066 {
1067 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001068 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001069 FlushAllocStack();
1070 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001071
Ian Rogers1d54e732013-05-02 21:10:01 -07001072 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1073 // of the remaining available heap memory.
1074 space::DlMallocSpace* zygote_space = alloc_space_;
1075 alloc_space_ = zygote_space->CreateZygoteSpace();
1076 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001077
Ian Rogers1d54e732013-05-02 21:10:01 -07001078 // Change the GC retention policy of the zygote space to only collect when full.
1079 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1080 AddContinuousSpace(alloc_space_);
1081 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001082
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001083 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001084 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001085 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1086 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1087 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001088 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001089 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001090}
1091
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001093 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1094 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001095 allocation_stack_->Reset();
1096}
1097
Ian Rogers1d54e732013-05-02 21:10:01 -07001098void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1099 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001100 mirror::Object** limit = stack->End();
1101 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1102 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001103 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001104 if (LIKELY(bitmap->HasAddress(obj))) {
1105 bitmap->Set(obj);
1106 } else {
1107 large_objects->Set(obj);
1108 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001109 }
1110}
1111
Ian Rogers1d54e732013-05-02 21:10:01 -07001112void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1113 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001114 mirror::Object** limit = stack->End();
1115 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1116 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001117 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001118 if (LIKELY(bitmap->HasAddress(obj))) {
1119 bitmap->Clear(obj);
1120 } else {
1121 large_objects->Clear(obj);
1122 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001123 }
1124}
1125
Ian Rogers1d54e732013-05-02 21:10:01 -07001126collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1127 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001128 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001129
1130 switch (gc_cause) {
1131 case kGcCauseForAlloc:
1132 ATRACE_BEGIN("GC (alloc)");
1133 break;
1134 case kGcCauseBackground:
1135 ATRACE_BEGIN("GC (background)");
1136 break;
1137 case kGcCauseExplicit:
1138 ATRACE_BEGIN("GC (explicit)");
1139 break;
1140 }
1141
Mathieu Chartier65db8802012-11-20 12:36:46 -08001142 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001143 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001144
Ian Rogers120f1c72012-09-28 17:17:10 -07001145 if (self->IsHandlingStackOverflow()) {
1146 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1147 }
1148
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001149 // Ensure there is only one GC at a time.
1150 bool start_collect = false;
1151 while (!start_collect) {
1152 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001153 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001154 if (!is_gc_running_) {
1155 is_gc_running_ = true;
1156 start_collect = true;
1157 }
1158 }
1159 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001160 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001161 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1162 // Not doing at the moment to ensure soft references are cleared.
1163 }
1164 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001165 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001166
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001167 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1168 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1169 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1170 }
1171
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001172 // We need to do partial GCs every now and then to avoid the heap growing too much and
1173 // fragmenting.
Ian Rogers1d54e732013-05-02 21:10:01 -07001174 // TODO: if sticky GCs are failing to free memory then we should lower the
1175 // sticky_to_partial_gc_ratio_, if they are successful we can increase it.
1176 if (gc_type == collector::kGcTypeSticky) {
1177 ++sticky_gc_count_;
1178 if (sticky_gc_count_ >= sticky_to_partial_gc_ratio_) {
1179 gc_type = have_zygote_space_ ? collector::kGcTypePartial : collector::kGcTypeFull;
1180 sticky_gc_count_ = 0;
1181 }
1182 } else {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001183 sticky_gc_count_ = 0;
1184 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001185
Ian Rogers1d54e732013-05-02 21:10:01 -07001186 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001187 uint64_t gc_start_size = GetBytesAllocated();
1188 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001189 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001190 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1191 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001192 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001193 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001194 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001195 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1196 }
1197
Ian Rogers1d54e732013-05-02 21:10:01 -07001198 DCHECK_LT(gc_type, collector::kGcTypeMax);
1199 DCHECK_NE(gc_type, collector::kGcTypeNone);
1200 collector::MarkSweep* collector = NULL;
1201 typedef std::vector<collector::MarkSweep*>::iterator It;
1202 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1203 it != end; ++it) {
1204 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001205 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1206 collector = cur_collector;
1207 break;
1208 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001209 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001210 CHECK(collector != NULL)
1211 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1212 << " and type=" << gc_type;
1213 collector->clear_soft_references_ = clear_soft_references;
1214 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001215 total_objects_freed_ever_ += collector->GetFreedObjects();
1216 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001217
Ian Rogers1d54e732013-05-02 21:10:01 -07001218 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001219 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1220 bool was_slow = duration > kSlowGcThreshold ||
1221 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1222 for (size_t i = 0; i < pauses.size(); ++i) {
1223 if (pauses[i] > kLongGcPauseThreshold) {
1224 was_slow = true;
1225 }
1226 }
1227
1228 if (was_slow) {
1229 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001230 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001231 const size_t total_memory = GetTotalMemory();
1232 std::ostringstream pause_string;
1233 for (size_t i = 0; i < pauses.size(); ++i) {
1234 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1235 << ((i != pauses.size() - 1) ? ", " : "");
1236 }
1237 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001238 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1239 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1240 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1241 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001242 if (VLOG_IS_ON(heap)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001243 LOG(INFO) << Dumpable<base::NewTimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001244 }
1245 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001246
Ian Rogers15bf2d32012-08-28 17:33:04 -07001247 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001248 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001249 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001250 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001251 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001252 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001253 }
1254 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001255 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001256 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001257 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001258}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001259
Ian Rogers1d54e732013-05-02 21:10:01 -07001260void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::NewTimingLogger& timings,
1261 collector::GcType gc_type) {
1262 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001263 // 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 -07001264 // cards.
1265 return;
1266 }
1267
1268 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001269 if (gc_type == collector::kGcTypePartial) {
1270 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001271 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001272
Ian Rogers1d54e732013-05-02 21:10:01 -07001273 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001274 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001275 }
1276
1277 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001278 timings.NewSplit("UpdateModUnionTable");
1279 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001280
1281 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001282 timings.NewSplit("MarkImageToAllocSpaceReferences");
1283 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001284}
1285
Ian Rogers1d54e732013-05-02 21:10:01 -07001286static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001287 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001288 if (root == obj) {
1289 LOG(INFO) << "Object " << obj << " is a root";
1290 }
1291}
1292
1293class ScanVisitor {
1294 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001295 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001296 LOG(INFO) << "Would have rescanned object " << obj;
1297 }
1298};
1299
Ian Rogers1d54e732013-05-02 21:10:01 -07001300// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001301class VerifyReferenceVisitor {
1302 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001303 VerifyReferenceVisitor(Heap* heap)
1304 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
1305 : heap_(heap), failed_(false) {
1306 }
1307
1308 bool Failed() const {
1309 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001310 }
1311
1312 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001313 // analysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001314 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
Ian Rogers1d54e732013-05-02 21:10:01 -07001315 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001316 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001317 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001318 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1319 accounting::CardTable* card_table = heap_->GetCardTable();
1320 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1321 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001322
Ian Rogers1d54e732013-05-02 21:10:01 -07001323 if (obj != NULL) {
1324 byte* card_addr = card_table->CardFromAddr(obj);
1325 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1326 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1327 << "\nObj type " << PrettyTypeOf(obj)
1328 << "\nRef type " << PrettyTypeOf(ref);
1329 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1330 void* cover_begin = card_table->AddrFromCard(card_addr);
1331 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1332 accounting::CardTable::kCardSize);
1333 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1334 << "-" << cover_end;
1335 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001336
Ian Rogers1d54e732013-05-02 21:10:01 -07001337 // Print out how the object is live.
1338 if (bitmap != NULL && bitmap->Test(obj)) {
1339 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1340 }
1341 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
1342 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1343 }
1344 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
1345 LOG(ERROR) << "Object " << obj << " found in live stack";
1346 }
1347 // Attempt to see if the card table missed the reference.
1348 ScanVisitor scan_visitor;
1349 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1350 card_table->Scan(bitmap, byte_cover_begin,
1351 byte_cover_begin + accounting::CardTable::kCardSize,
1352 scan_visitor, VoidFunctor());
1353
1354 // Search to see if any of the roots reference our object.
1355 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1356 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1357
1358 // Search to see if any of the roots reference our reference.
1359 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1360 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1361 } else {
1362 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001363 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001364 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1365 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001366 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001367 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001368 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001369 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001370 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1371 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1372 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001373 }
1374 }
1375
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001376 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001377 return heap_->IsLiveObjectLocked(obj);
1378 }
1379
1380 static void VerifyRoots(const mirror::Object* root, void* arg) {
1381 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1382 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001383 }
1384
1385 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001386 Heap* const heap_;
1387 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001388};
1389
Ian Rogers1d54e732013-05-02 21:10:01 -07001390// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001391class VerifyObjectVisitor {
1392 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001393 VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001394 }
1395
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001396 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001397 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001398 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1399 // be live or else how did we find it in the live bitmap?
1400 VerifyReferenceVisitor visitor(heap_);
1401 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1402 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001403 }
1404
1405 bool Failed() const {
1406 return failed_;
1407 }
1408
1409 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001410 Heap* const heap_;
1411 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001412};
1413
1414// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001415bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001416 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001417 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001418 allocation_stack_->Sort();
1419 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001420 // Perform the verification.
1421 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001422 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001423 GetLiveBitmap()->Visit(visitor);
1424 // We don't want to verify the objects in the allocation stack since they themselves may be
1425 // pointing to dead objects if they are not reachable.
1426 if (visitor.Failed()) {
1427 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001428 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001429 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001430 return true;
1431}
1432
1433class VerifyReferenceCardVisitor {
1434 public:
1435 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1436 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1437 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001438 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001439 }
1440
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001441 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1442 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001443 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1444 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001445 // Filter out class references since changing an object's class does not mark the card as dirty.
1446 // Also handles large objects, since the only reference they hold is a class reference.
1447 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001448 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001449 // If the object is not dirty and it is referencing something in the live stack other than
1450 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001451 if (!card_table->AddrIsInCardTable(obj)) {
1452 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1453 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001454 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001455 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1456 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001457 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
1458 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1459 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001460 LOG(ERROR) << "Object " << obj << " found in live stack";
1461 }
1462 if (heap_->GetLiveBitmap()->Test(obj)) {
1463 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1464 }
1465 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1466 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1467
1468 // Print which field of the object is dead.
1469 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001470 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001471 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001472 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1473 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001474 CHECK(fields != NULL);
1475 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001476 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001477 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1478 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1479 << PrettyField(cur);
1480 break;
1481 }
1482 }
1483 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001484 const mirror::ObjectArray<mirror::Object>* object_array =
1485 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001486 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1487 if (object_array->Get(i) == ref) {
1488 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1489 }
1490 }
1491 }
1492
1493 *failed_ = true;
1494 }
1495 }
1496 }
1497 }
1498
1499 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001500 Heap* const heap_;
1501 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001502};
1503
1504class VerifyLiveStackReferences {
1505 public:
1506 VerifyLiveStackReferences(Heap* heap)
1507 : heap_(heap),
1508 failed_(false) {
1509
1510 }
1511
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001512 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001513 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1514 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001515 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001516 }
1517
1518 bool Failed() const {
1519 return failed_;
1520 }
1521
1522 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001523 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001524 bool failed_;
1525};
1526
1527bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001528 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001529
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001530 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001531 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001532 VerifyLiveStackReferences visitor(this);
1533 GetLiveBitmap()->Visit(visitor);
1534
1535 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001536 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001537 visitor(*it);
1538 }
1539
1540 if (visitor.Failed()) {
1541 DumpSpaces();
1542 return false;
1543 }
1544 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001545}
1546
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001547void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001548 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001549
1550 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001551 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001552 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001553 }
1554}
1555
Ian Rogers1d54e732013-05-02 21:10:01 -07001556void Heap::ProcessCards(base::NewTimingLogger& timings) {
1557 // Clear cards and keep track of cards cleared in the mod-union table.
1558 typedef std::vector<space::ContinuousSpace*>::iterator It;
1559 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1560 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001561 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001562 timings.NewSplit("ModUnionClearCards");
1563 image_mod_union_table_->ClearCards(space);
1564 } else if (space->IsZygoteSpace()) {
1565 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001566 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001567 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001568 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1569 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001570 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001571 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001572 }
1573 }
1574}
1575
Ian Rogers1d54e732013-05-02 21:10:01 -07001576void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001577 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1578 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001579
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001580 if (verify_pre_gc_heap_) {
1581 thread_list->SuspendAll();
1582 {
1583 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1584 if (!VerifyHeapReferences()) {
1585 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1586 }
1587 }
1588 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001589 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001590
1591 // Check that all objects which reference things in the live stack are on dirty cards.
1592 if (verify_missing_card_marks_) {
1593 thread_list->SuspendAll();
1594 {
1595 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1596 SwapStacks();
1597 // Sort the live stack so that we can quickly binary search it later.
1598 if (!VerifyMissingCardMarks()) {
1599 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1600 }
1601 SwapStacks();
1602 }
1603 thread_list->ResumeAll();
1604 }
1605
1606 if (verify_mod_union_table_) {
1607 thread_list->SuspendAll();
1608 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1609 zygote_mod_union_table_->Update();
1610 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001611 image_mod_union_table_->Update();
1612 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001613 thread_list->ResumeAll();
1614 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001615}
1616
Ian Rogers1d54e732013-05-02 21:10:01 -07001617void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001618 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001619
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001620 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1621 // reachable objects.
1622 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001623 Thread* self = Thread::Current();
1624 CHECK_NE(self->GetState(), kRunnable);
1625 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001626 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001627 {
1628 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1629 // Swapping bound bitmaps does nothing.
1630 gc->SwapBitmaps();
1631 if (!VerifyHeapReferences()) {
1632 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1633 }
1634 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001635 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001636 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001637 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001638 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001639}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001640
Ian Rogers1d54e732013-05-02 21:10:01 -07001641void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001642 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001643
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001644 if (verify_system_weaks_) {
1645 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001646 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001647 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001649}
1650
Ian Rogers1d54e732013-05-02 21:10:01 -07001651collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1652 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001653 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001654 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001655 bool do_wait;
1656 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001657 {
1658 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001659 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001660 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001661 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001662 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001663 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664 // We must wait, change thread state then sleep on gc_complete_cond_;
1665 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1666 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001667 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001668 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001669 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001670 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001671 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001672 wait_time = NanoTime() - wait_start;;
1673 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001674 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001675 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001676 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1677 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001678 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001679 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001680 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001681 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001682}
1683
Elliott Hughesc967f782012-04-16 10:23:15 -07001684void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001685 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001686 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001687 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001688}
1689
1690size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001691 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001692}
1693
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001694void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001695 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001696 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001697 << PrettySize(GetMaxMemory());
1698 max_allowed_footprint = GetMaxMemory();
1699 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001700 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001701}
1702
Mathieu Chartier65db8802012-11-20 12:36:46 -08001703void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001704 // We know what our utilization is at this moment.
1705 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001706 const size_t bytes_allocated = GetBytesAllocated();
1707 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001708 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001709
Mathieu Chartier65db8802012-11-20 12:36:46 -08001710 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1711 if (target_size > bytes_allocated + max_free_) {
1712 target_size = bytes_allocated + max_free_;
1713 } else if (target_size < bytes_allocated + min_free_) {
1714 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001715 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001716
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001717 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001718
Ian Rogers1d54e732013-05-02 21:10:01 -07001719 // Calculate when to perform the next ConcurrentGC.
1720 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001721 // Calculate the estimated GC duration.
1722 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1723 // Estimate how many remaining bytes we will have when we need to start the next GC.
1724 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001725 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1726 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1727 // A never going to happen situation that from the estimated allocation rate we will exceed
1728 // the applications entire footprint with the given estimated allocation rate. Schedule
1729 // another GC straight away.
1730 concurrent_start_bytes_ = bytes_allocated;
1731 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001732 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1733 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1734 // right away.
1735 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001736 }
1737 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1738 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1739 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001740}
1741
jeffhaoc1160702011-10-27 15:48:45 -07001742void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001743 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001744 alloc_space_->ClearGrowthLimit();
1745}
1746
Elliott Hughesadb460d2011-10-05 17:02:34 -07001747void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001748 MemberOffset reference_queue_offset,
1749 MemberOffset reference_queueNext_offset,
1750 MemberOffset reference_pendingNext_offset,
1751 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001752 reference_referent_offset_ = reference_referent_offset;
1753 reference_queue_offset_ = reference_queue_offset;
1754 reference_queueNext_offset_ = reference_queueNext_offset;
1755 reference_pendingNext_offset_ = reference_pendingNext_offset;
1756 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1757 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1758 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1759 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1760 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1761 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1762}
1763
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001764mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001765 DCHECK(reference != NULL);
1766 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001767 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001768}
1769
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001770void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001771 DCHECK(reference != NULL);
1772 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1773 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1774}
1775
1776// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001777bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001778 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001779 const mirror::Object* queue =
1780 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1781 const mirror::Object* queue_next =
1782 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001783 return (queue != NULL) && (queue_next == NULL);
1784}
1785
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001786void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001787 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001788 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1789 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001790 EnqueuePendingReference(ref, cleared_reference_list);
1791}
1792
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001793void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001794 DCHECK(ref != NULL);
1795 DCHECK(list != NULL);
1796
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001797 // TODO: Remove this lock, use atomic stacks for storing references.
1798 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001799 if (*list == NULL) {
1800 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1801 *list = ref;
1802 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001803 mirror::Object* head =
1804 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001805 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1806 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1807 }
1808}
1809
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001810mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001811 DCHECK(list != NULL);
1812 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001813 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1814 false);
1815 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001816
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001817 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1818 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001819 if (*list == head) {
1820 ref = *list;
1821 *list = NULL;
1822 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001823 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1824 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001825 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1826 ref = head;
1827 }
1828 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1829 return ref;
1830}
1831
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001832void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001833 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001834 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001835 ArgArray arg_array(NULL, 0);
1836 arg_array.Append(reinterpret_cast<uint32_t>(object));
1837 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001838 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001839}
1840
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001841void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001842 DCHECK(cleared != NULL);
1843 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001844 // When a runtime isn't started there are no reference queues to care about so ignore.
1845 if (LIKELY(Runtime::Current()->IsStarted())) {
1846 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001847 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001848 ArgArray arg_array(NULL, 0);
1849 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1850 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001851 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001852 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001853 *cleared = NULL;
1854 }
1855}
1856
Ian Rogers1f539342012-10-03 21:09:42 -07001857void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001858 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001859 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001860 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001861 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001862 !runtime->IsConcurrentGcEnabled()) {
1863 return;
1864 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001865 {
1866 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1867 if (runtime->IsShuttingDown()) {
1868 return;
1869 }
1870 }
1871 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001872 return;
1873 }
1874
Ian Rogers120f1c72012-09-28 17:17:10 -07001875 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001876 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1877 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001878 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1879 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001880 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001881}
1882
Ian Rogers81d425b2012-09-27 16:03:43 -07001883void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001884 {
1885 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001886 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001887 return;
1888 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001889 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001890
Mathieu Chartier65db8802012-11-20 12:36:46 -08001891 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001892 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001893 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001894 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001895 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07001896 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001897 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001898 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001899}
1900
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001901void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001902 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1903 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1904 // a space it will hold its lock and can become a cause of jank.
1905 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1906 // forking.
1907
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001908 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1909 // because that only marks object heads, so a large array looks like lots of empty space. We
1910 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1911 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1912 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1913 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001914 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001915 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001916 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1917 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001918 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1919 // heap trim occurred in the last two seconds.
1920 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001921 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001922
1923 Thread* self = Thread::Current();
1924 {
1925 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1926 Runtime* runtime = Runtime::Current();
1927 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1928 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1929 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1930 // as we don't hold the lock while requesting the trim).
1931 return;
1932 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001933 }
Ian Rogers48931882013-01-22 14:35:16 -08001934
1935 SchedPolicy policy;
1936 get_sched_policy(self->GetTid(), &policy);
1937 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1938 // Don't trim the heap if we are a foreground or audio app.
1939 return;
1940 }
1941
Ian Rogers1d54e732013-05-02 21:10:01 -07001942 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001943 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001944 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1945 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001946 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1947 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001948 CHECK(!env->ExceptionCheck());
1949}
1950
Ian Rogers48931882013-01-22 14:35:16 -08001951size_t Heap::Trim() {
1952 // Handle a requested heap trim on a thread outside of the main GC thread.
1953 return alloc_space_->Trim();
1954}
1955
Ian Rogers1d54e732013-05-02 21:10:01 -07001956} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001957} // namespace art