blob: 9ec1f21243c65dbad08f5b57cb1660b634ad85f3 [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 Carlstrom265091e2013-01-30 14:08:26 -0800112 if (!kIsTargetBuild) {
113 arg_vector.push_back(strdup("--host"));
114 }
115
Elliott Hughes48436bb2012-02-07 15:23:28 -0800116 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800117 LOG(INFO) << command_line;
118
Elliott Hughes48436bb2012-02-07 15:23:28 -0800119 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800120 char** argv = &arg_vector[0];
121
122 // fork and exec dex2oat
123 pid_t pid = fork();
124 if (pid == 0) {
125 // no allocation allowed between fork and exec
126
127 // change process groups, so we don't get reaped by ProcessManager
128 setpgid(0, 0);
129
130 execv(dex2oat, argv);
131
132 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
133 return false;
134 } else {
135 STLDeleteElements(&arg_vector);
136
137 // wait for dex2oat to finish
138 int status;
139 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
140 if (got_pid != pid) {
141 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
142 return false;
143 }
144 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
145 LOG(ERROR) << dex2oat << " failed: " << command_line;
146 return false;
147 }
148 }
149 return true;
150}
151
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700152void Heap::UnReserveOatFileAddressRange() {
153 oat_file_map_.reset(NULL);
154}
155
Mathieu Chartier0051be62012-10-12 17:47:11 -0700156Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
157 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700158 const std::string& original_image_file_name, bool concurrent_gc)
159 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800160 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700161 concurrent_gc_(concurrent_gc),
162 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -0700163 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800164 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -0700165 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800166 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700167 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700168 max_allowed_footprint_(initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -0700169 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
170 : std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700171 sticky_gc_count_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700172 sticky_to_partial_gc_ratio_(10),
173 total_bytes_freed_ever_(0),
174 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700175 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800176 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700177 verify_missing_card_marks_(false),
178 verify_system_weaks_(false),
179 verify_pre_gc_heap_(false),
180 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700181 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700182 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700183 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700184 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800185 allocation_rate_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700186 max_allocation_stack_size_(kDesiredHeapVerification > kNoHeapVerification? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800187 reference_referent_offset_(0),
188 reference_queue_offset_(0),
189 reference_queueNext_offset_(0),
190 reference_pendingNext_offset_(0),
191 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700192 min_free_(min_free),
193 max_free_(max_free),
194 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700195 total_wait_time_(0),
196 measure_allocation_time_(false),
197 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700198 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800199 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800200 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700201 }
202
Ian Rogers1d54e732013-05-02 21:10:01 -0700203 live_bitmap_.reset(new accounting::HeapBitmap(this));
204 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700205
Ian Rogers30fab402012-01-23 15:43:46 -0800206 // Requested begin for the alloc space, to follow the mapped image and oat files
207 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800208 std::string image_file_name(original_image_file_name);
209 if (!image_file_name.empty()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700210 space::ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700211
Brian Carlstrom5643b782012-02-05 12:32:53 -0800212 if (OS::FileExists(image_file_name.c_str())) {
213 // If the /system file exists, it should be up-to-date, don't try to generate
Ian Rogers1d54e732013-05-02 21:10:01 -0700214 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800215 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -0700216 // If the /system file didn't exist, we need to use one from the dalvik-cache.
Brian Carlstrom5643b782012-02-05 12:32:53 -0800217 // If the cache file exists, try to open, but if it fails, regenerate.
218 // If it does not exist, generate.
Brian Carlstrom7675e162013-06-10 16:18:04 -0700219 image_file_name = GetDalvikCacheFilenameOrDie(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800220 if (OS::FileExists(image_file_name.c_str())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700221 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800222 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700223 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700224 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700225 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800226 }
227 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700228
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700229 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700230 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800231 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
232 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800233 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
234 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700235
236 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
237 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800238 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700239 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
240 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800241 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700242
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800243 if (oat_file_end_addr > requested_begin) {
244 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700245 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700246 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700247 }
248
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700249 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700250 const bool kUseFreeListSpaceForLOS = false;
251 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700252 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700253 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700254 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700255 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700256 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
257 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700258
Ian Rogers1d54e732013-05-02 21:10:01 -0700259 alloc_space_ = space::DlMallocSpace::Create("alloc space",
260 initial_size,
261 growth_limit, capacity,
262 requested_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700263 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700264 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700265 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700266
Ian Rogers1d54e732013-05-02 21:10:01 -0700267 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
268 byte* heap_begin = continuous_spaces_.front()->Begin();
269 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
270 if (continuous_spaces_.back()->IsDlMallocSpace()) {
271 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700272 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700273
Ian Rogers30fab402012-01-23 15:43:46 -0800274 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700275 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700276 typedef std::vector<space::ContinuousSpace*>::iterator It;
277 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
278 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800279 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700280 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700281 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800282 }
283 }
284
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800285 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700286 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700287 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700288
Ian Rogers1d54e732013-05-02 21:10:01 -0700289 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
290 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700291
Ian Rogers1d54e732013-05-02 21:10:01 -0700292 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700293 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700294
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700295 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700296 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800298 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700299 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700300 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
301 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
302 max_allocation_stack_size_));
303 live_stack_.reset(accounting::ObjectStack::Create("live stack",
304 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700305
Mathieu Chartier65db8802012-11-20 12:36:46 -0800306 // It's still too early to take a lock because there are no threads yet, but we can create locks
307 // now. We don't create it earlier to make it clear that you can't use locks during heap
308 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700309 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700310 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
311 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700312
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700313 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700314 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700315
Ian Rogers1d54e732013-05-02 21:10:01 -0700316 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800317 last_gc_size_ = GetBytesAllocated();
318
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800319 // Create our garbage collectors.
320 for (size_t i = 0; i < 2; ++i) {
321 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700322 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
323 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
324 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700325 }
326
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800327 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800328 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800329 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700330 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700331}
332
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700333void Heap::CreateThreadPool() {
334 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
335 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
336 // workers to complete.
Ian Rogers1d54e732013-05-02 21:10:01 -0700337 thread_pool_.reset(new ThreadPool(1)); // new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700338}
339
340void Heap::DeleteThreadPool() {
341 thread_pool_.reset(NULL);
342}
343
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700344// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700345struct ContinuousSpaceSorter {
346 bool operator ()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700347 return a->Begin() < b->Begin();
348 }
349};
350
Ian Rogers1d54e732013-05-02 21:10:01 -0700351void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700352 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700353 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700354 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700355 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700356 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700357 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
358 continuous_spaces_.push_back(space);
359 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
360 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700361 }
362
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700363 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700364 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700365
366 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
367 // avoid redundant marking.
368 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700369 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
370 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
371 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700372 if (space->IsImageSpace()) {
373 DCHECK(!seen_zygote);
374 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700375 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700376 DCHECK(!seen_alloc);
377 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700378 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700379 seen_alloc = true;
380 }
381 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800382}
383
Ian Rogers1d54e732013-05-02 21:10:01 -0700384void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
385 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
386 DCHECK(space != NULL);
387 DCHECK(space->GetLiveObjects() != NULL);
388 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
389 DCHECK(space->GetMarkObjects() != NULL);
390 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
391 discontinuous_spaces_.push_back(space);
392}
393
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700394void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700395 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700396 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700397 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800398
399 // Dump cumulative loggers for each GC type.
400 // TODO: C++0x
401 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700402 typedef std::vector<collector::MarkSweep*>::const_iterator It;
403 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800404 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700405 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800406 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800407 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700408 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800409 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700410 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800411 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
412 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
413 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700414 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
415 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
416 << collector->GetName() << " freed: " << freed_objects
417 << " objects with total size " << PrettySize(freed_bytes) << "\n"
418 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
419 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800420 total_duration += total_ns;
421 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700422 }
423 }
424 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700425 size_t total_objects_allocated = GetObjectsAllocatedEver();
426 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700427 if (total_duration != 0) {
428 const double total_seconds = double(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700429 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
430 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700431 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700432 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700433 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700434 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700435 os << "Total number of allocations: " << total_objects_allocated << "\n";
436 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700437 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700438 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
439 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
440 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700441 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700442 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
443 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700444}
445
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800446Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700447 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700448 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700449 }
450
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800451 STLDeleteElements(&mark_sweep_collectors_);
452
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700453 // If we don't reset then the mark stack complains in it's destructor.
454 allocation_stack_->Reset();
455 live_stack_->Reset();
456
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800457 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800458 // We can't take the heap lock here because there might be a daemon thread suspended with the
459 // heap lock held. We know though that no non-daemon threads are executing, and we know that
460 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
461 // 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 -0700462 STLDeleteElements(&continuous_spaces_);
463 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700465 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700466}
467
Ian Rogers1d54e732013-05-02 21:10:01 -0700468space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
469 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700470 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700471 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
472 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700473 if ((*it)->Contains(obj)) {
474 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700475 }
476 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700477 if (!fail_ok) {
478 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
479 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700480 return NULL;
481}
482
Ian Rogers1d54e732013-05-02 21:10:01 -0700483space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
484 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700485 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700486 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
487 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
488 if ((*it)->Contains(obj)) {
489 return *it;
490 }
491 }
492 if (!fail_ok) {
493 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
494 }
495 return NULL;
496}
497
498space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
499 space::Space* result = FindContinuousSpaceFromObject(obj, true);
500 if (result != NULL) {
501 return result;
502 }
503 return FindDiscontinuousSpaceFromObject(obj, true);
504}
505
506space::ImageSpace* Heap::GetImageSpace() const {
507 // TODO: C++0x auto
508 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
509 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700510 if ((*it)->IsImageSpace()) {
511 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700512 }
513 }
514 return NULL;
515}
516
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700517static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700518 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700519 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700520 size_t chunk_free_bytes = chunk_size - used_bytes;
521 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
522 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700523 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700524}
525
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800526mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
527 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700528 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
529 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800530 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700531
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800532 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700533 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700534 uint64_t allocation_start = 0;
535 if (measure_allocation_time_) {
536 allocation_start = NanoTime();
537 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700538
539 // We need to have a zygote space or else our newly allocated large object can end up in the
540 // Zygote resulting in it being prematurely freed.
541 // We can only do this for primive objects since large objects will not be within the card table
542 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers22a20862013-03-16 16:34:57 -0700543 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700544 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700545 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700546 // Make sure that our large object didn't get placed anywhere within the space interval or else
547 // it breaks the immune range.
548 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700549 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
550 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700551 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700552 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700553
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700554 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700555 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700556 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700557 }
558
Mathieu Chartier037813d2012-08-23 16:44:59 -0700559 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700561
562 // Record allocation after since we want to use the atomic add for the atomic fence to guard
563 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700564 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700565
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700566 if (Dbg::IsAllocTrackingEnabled()) {
567 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700568 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700569 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700570 // We already have a request pending, no reason to start more until we update
571 // concurrent_start_bytes_.
572 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700573 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800574 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700575 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700576 }
577 VerifyObject(obj);
578
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700579 if (measure_allocation_time_) {
580 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
581 }
582
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700583 return obj;
584 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800585 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700586 int64_t total_bytes_free = GetFreeMemory();
Ian Rogers1d54e732013-05-02 21:10:01 -0700587 uint64_t alloc_space_size = alloc_space_->GetBytesAllocated();
588 uint64_t large_object_size = large_object_space_->GetObjectsAllocated();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800589 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
590 << " free bytes; allocation space size " << alloc_space_size
591 << "; large object space size " << large_object_size;
592 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
593 if (total_bytes_free >= byte_count) {
594 size_t max_contiguous_allocation = 0;
595 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700596 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
597 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
598 space::ContinuousSpace* space = *it;
599 if (space->IsDlMallocSpace()) {
600 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800601 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700602 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800603 oss << "; failed due to fragmentation (largest possible contiguous allocation "
604 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700605 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800606 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700607 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700608}
609
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800610bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700611 // Note: we deliberately don't take the lock here, and mustn't test anything that would
612 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700613 if (obj == NULL) {
614 return true;
615 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700616 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700617 return false;
618 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700619 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700620}
621
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800622bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700623 //Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
624 if (obj == NULL) {
625 return false;
626 }
627 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
628 return false;
629 }
630 space::ContinuousSpace* cont_space = FindContinuousSpaceFromObject(obj, true);
631 if (cont_space != NULL) {
632 if (cont_space->GetLiveBitmap()->Test(obj)) {
633 return true;
634 }
635 } else {
636 space::DiscontinuousSpace* disc_space = FindDiscontinuousSpaceFromObject(obj, true);
637 if (disc_space != NULL) {
638 if (disc_space->GetLiveObjects()->Test(obj)) {
639 return true;
640 }
641 }
642 }
643 for (size_t i = 0; i < 5; ++i) {
644 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
645 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
646 return true;
647 }
648 NanoSleep(MsToNs(10));
649 }
650 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700651}
652
Ian Rogers04d7aa92013-03-16 14:29:17 -0700653void Heap::VerifyObjectImpl(const mirror::Object* obj) {
654 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700655 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700656 return;
657 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700658 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700659}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700660
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700661void Heap::DumpSpaces() {
662 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700663 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
664 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
665 space::ContinuousSpace* space = *it;
666 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
667 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700668 LOG(INFO) << space << " " << *space << "\n"
669 << live_bitmap << " " << *live_bitmap << "\n"
670 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700671 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700672 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
673 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
674 space::DiscontinuousSpace* space = *it;
675 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700676 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700677}
678
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800679void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800680 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700681 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700682 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800683 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
684 return;
685 }
686 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
687 mirror::Object::ClassOffset().Int32Value();
688 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
689 if (UNLIKELY(c == NULL)) {
690 LOG(FATAL) << "Null class in object: " << obj;
691 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
692 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
693 }
694 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
695 // Note: we don't use the accessors here as they have internal sanity checks
696 // that we don't want to run
697 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
698 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
699 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
700 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
701 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700702
Ian Rogers62d6c772013-02-27 08:32:07 -0800703 if (verify_object_mode_ != kVerifyAllFast) {
704 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
705 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700706 if (!IsLiveObjectLocked(obj)) {
707 DumpSpaces();
708 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700709 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700710 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700711 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
712 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700713 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700714}
715
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800716void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700717 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700718 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700719}
720
721void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700722 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700723 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700724}
725
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800726void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700727 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700728 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700729 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700730
731 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700732 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700733 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700734 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700735
736 // TODO: Update these atomically.
737 RuntimeStats* global_stats = Runtime::Current()->GetStats();
738 ++global_stats->allocated_objects;
739 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700740 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700741
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700742 // This is safe to do since the GC will never free objects which are neither in the allocation
743 // stack or the live bitmap.
744 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700745 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700746 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700747}
748
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700749void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700750 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
751 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700752
753 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700754 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700755 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700756 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700757
758 // TODO: Do this concurrently.
759 RuntimeStats* global_stats = Runtime::Current()->GetStats();
760 global_stats->freed_objects += freed_objects;
761 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700762 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700763}
764
Ian Rogers1d54e732013-05-02 21:10:01 -0700765mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
766 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700767 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800768 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
769 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
770 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
771 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700772 return NULL;
773 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700774 }
775
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700776 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700777}
778
Ian Rogers1d54e732013-05-02 21:10:01 -0700779mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700780 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
781 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700782 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700783 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700784
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800785 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700786 if (ptr != NULL) {
787 return ptr;
788 }
789
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700790 // The allocation failed. If the GC is running, block until it completes, and then retry the
791 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700792 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
793 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700794 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700795 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700796 if (ptr != NULL) {
797 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700798 }
799 }
800
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700801 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700802 for (size_t i = static_cast<size_t>(last_gc) + 1;
803 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700804 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700805 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700806 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700807 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700808 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700809 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
810 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700811 break;
812 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700813 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700814 run_gc = have_zygote_space_;
815 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700816 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700817 run_gc = true;
818 break;
819 default:
820 break;
821 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700822
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700823 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700824 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700825 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800826 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700827 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700828
829 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700830 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700831 if (ptr != NULL) {
832 return ptr;
833 }
834 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700835 }
836
837 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700838 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700839 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700840 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700841 return ptr;
842 }
843
Elliott Hughes81ff3182012-03-23 20:35:56 -0700844 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
845 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
846 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700847
Elliott Hughes418dfe72011-10-06 18:56:27 -0700848 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700849 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
850 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700851
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700852 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700853 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700854 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700855}
856
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700857void Heap::SetTargetHeapUtilization(float target) {
858 DCHECK_GT(target, 0.0f); // asserted in Java code
859 DCHECK_LT(target, 1.0f);
860 target_utilization_ = target;
861}
862
Ian Rogers1d54e732013-05-02 21:10:01 -0700863size_t Heap::GetObjectsAllocated() const {
864 size_t total = 0;
865 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
866 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
867 space::ContinuousSpace* space = *it;
868 if (space->IsDlMallocSpace()) {
869 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700870 }
871 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700872 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
873 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
874 space::DiscontinuousSpace* space = *it;
875 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
876 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700877 return total;
878}
879
Ian Rogers1d54e732013-05-02 21:10:01 -0700880size_t Heap::GetObjectsAllocatedEver() const {
881 size_t total = 0;
882 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
883 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
884 space::ContinuousSpace* space = *it;
885 if (space->IsDlMallocSpace()) {
886 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700887 }
888 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700889 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
890 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
891 space::DiscontinuousSpace* space = *it;
892 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
893 }
894 return total;
895}
896
897size_t Heap::GetBytesAllocatedEver() const {
898 size_t total = 0;
899 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
900 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
901 space::ContinuousSpace* space = *it;
902 if (space->IsDlMallocSpace()) {
903 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
904 }
905 }
906 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
907 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
908 space::DiscontinuousSpace* space = *it;
909 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
910 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700911 return total;
912}
913
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700914class InstanceCounter {
915 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800916 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700917 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800918 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700919 }
920
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800921 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800922 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800923 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800924 if (use_is_assignable_from_) {
925 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
926 ++counts_[i];
927 }
928 } else {
929 if (instance_class == classes_[i]) {
930 ++counts_[i];
931 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700932 }
933 }
934 }
935
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700936 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800937 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800938 bool use_is_assignable_from_;
939 uint64_t* const counts_;
940
941 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700942};
943
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800944void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800945 uint64_t* counts) {
946 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
947 // is empty, so the live bitmap is the only place we need to look.
948 Thread* self = Thread::Current();
949 self->TransitionFromRunnableToSuspended(kNative);
950 CollectGarbage(false);
951 self->TransitionFromSuspendedToRunnable();
952
953 InstanceCounter counter(classes, use_is_assignable_from, counts);
954 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700955 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700956}
957
Elliott Hughes3b78c942013-01-15 17:35:41 -0800958class InstanceCollector {
959 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800960 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800961 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
962 : class_(c), max_count_(max_count), instances_(instances) {
963 }
964
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800965 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
966 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800967 if (instance_class == class_) {
968 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800969 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800970 }
971 }
972 }
973
974 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800975 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800976 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800977 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800978
979 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
980};
981
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800982void Heap::GetInstances(mirror::Class* c, int32_t max_count,
983 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800984 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
985 // is empty, so the live bitmap is the only place we need to look.
986 Thread* self = Thread::Current();
987 self->TransitionFromRunnableToSuspended(kNative);
988 CollectGarbage(false);
989 self->TransitionFromSuspendedToRunnable();
990
991 InstanceCollector collector(c, max_count, instances);
992 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
993 GetLiveBitmap()->Visit(collector);
994}
995
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800996class ReferringObjectsFinder {
997 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800998 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
999 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001000 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1001 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1002 }
1003
1004 // For bitmap Visit.
1005 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1006 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001007 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001008 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001009 }
1010
1011 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001012 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
1013 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001014 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001015 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001016 }
1017 }
1018
1019 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001020 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001021 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001022 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001023
1024 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1025};
1026
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001027void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1028 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001029 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1030 // is empty, so the live bitmap is the only place we need to look.
1031 Thread* self = Thread::Current();
1032 self->TransitionFromRunnableToSuspended(kNative);
1033 CollectGarbage(false);
1034 self->TransitionFromSuspendedToRunnable();
1035
1036 ReferringObjectsFinder finder(o, max_count, referring_objects);
1037 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1038 GetLiveBitmap()->Visit(finder);
1039}
1040
Ian Rogers30fab402012-01-23 15:43:46 -08001041void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001042 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1043 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001044 Thread* self = Thread::Current();
1045 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001046 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001047}
1048
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001049void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001050 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001051 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1052 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001053 Thread* self = Thread::Current();
1054 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001055
1056 // Try to see if we have any Zygote spaces.
1057 if (have_zygote_space_) {
1058 return;
1059 }
1060
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001061 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1062
1063 {
1064 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001065 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001066 FlushAllocStack();
1067 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001068
Ian Rogers1d54e732013-05-02 21:10:01 -07001069 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1070 // of the remaining available heap memory.
1071 space::DlMallocSpace* zygote_space = alloc_space_;
1072 alloc_space_ = zygote_space->CreateZygoteSpace();
1073 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001074
Ian Rogers1d54e732013-05-02 21:10:01 -07001075 // Change the GC retention policy of the zygote space to only collect when full.
1076 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1077 AddContinuousSpace(alloc_space_);
1078 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001079
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001080 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001081 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001082 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1083 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1084 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001085 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001086 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001087}
1088
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001089void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001090 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1091 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092 allocation_stack_->Reset();
1093}
1094
Ian Rogers1d54e732013-05-02 21:10:01 -07001095void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1096 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001097 mirror::Object** limit = stack->End();
1098 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1099 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001100 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001101 if (LIKELY(bitmap->HasAddress(obj))) {
1102 bitmap->Set(obj);
1103 } else {
1104 large_objects->Set(obj);
1105 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001106 }
1107}
1108
Ian Rogers1d54e732013-05-02 21:10:01 -07001109void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1110 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001111 mirror::Object** limit = stack->End();
1112 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1113 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001114 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001115 if (LIKELY(bitmap->HasAddress(obj))) {
1116 bitmap->Clear(obj);
1117 } else {
1118 large_objects->Clear(obj);
1119 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001120 }
1121}
1122
Ian Rogers1d54e732013-05-02 21:10:01 -07001123collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1124 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001125 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001126
1127 switch (gc_cause) {
1128 case kGcCauseForAlloc:
1129 ATRACE_BEGIN("GC (alloc)");
1130 break;
1131 case kGcCauseBackground:
1132 ATRACE_BEGIN("GC (background)");
1133 break;
1134 case kGcCauseExplicit:
1135 ATRACE_BEGIN("GC (explicit)");
1136 break;
1137 }
1138
Mathieu Chartier65db8802012-11-20 12:36:46 -08001139 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001140 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001141
Ian Rogers120f1c72012-09-28 17:17:10 -07001142 if (self->IsHandlingStackOverflow()) {
1143 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1144 }
1145
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001146 // Ensure there is only one GC at a time.
1147 bool start_collect = false;
1148 while (!start_collect) {
1149 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001150 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001151 if (!is_gc_running_) {
1152 is_gc_running_ = true;
1153 start_collect = true;
1154 }
1155 }
1156 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001157 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001158 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1159 // Not doing at the moment to ensure soft references are cleared.
1160 }
1161 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001162 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001163
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001164 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1165 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1166 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1167 }
1168
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001169 // We need to do partial GCs every now and then to avoid the heap growing too much and
1170 // fragmenting.
Ian Rogers1d54e732013-05-02 21:10:01 -07001171 // TODO: if sticky GCs are failing to free memory then we should lower the
1172 // sticky_to_partial_gc_ratio_, if they are successful we can increase it.
1173 if (gc_type == collector::kGcTypeSticky) {
1174 ++sticky_gc_count_;
1175 if (sticky_gc_count_ >= sticky_to_partial_gc_ratio_) {
1176 gc_type = have_zygote_space_ ? collector::kGcTypePartial : collector::kGcTypeFull;
1177 sticky_gc_count_ = 0;
1178 }
1179 } else {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001180 sticky_gc_count_ = 0;
1181 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001182
Ian Rogers1d54e732013-05-02 21:10:01 -07001183 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001184 uint64_t gc_start_size = GetBytesAllocated();
1185 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001186 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001187 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1188 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001189 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001190 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001191 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001192 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1193 }
1194
Ian Rogers1d54e732013-05-02 21:10:01 -07001195 DCHECK_LT(gc_type, collector::kGcTypeMax);
1196 DCHECK_NE(gc_type, collector::kGcTypeNone);
1197 collector::MarkSweep* collector = NULL;
1198 typedef std::vector<collector::MarkSweep*>::iterator It;
1199 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1200 it != end; ++it) {
1201 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001202 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1203 collector = cur_collector;
1204 break;
1205 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001206 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001207 CHECK(collector != NULL)
1208 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1209 << " and type=" << gc_type;
1210 collector->clear_soft_references_ = clear_soft_references;
1211 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001212 total_objects_freed_ever_ += collector->GetFreedObjects();
1213 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001214
Ian Rogers1d54e732013-05-02 21:10:01 -07001215 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001216 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1217 bool was_slow = duration > kSlowGcThreshold ||
1218 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1219 for (size_t i = 0; i < pauses.size(); ++i) {
1220 if (pauses[i] > kLongGcPauseThreshold) {
1221 was_slow = true;
1222 }
1223 }
1224
1225 if (was_slow) {
1226 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001227 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001228 const size_t total_memory = GetTotalMemory();
1229 std::ostringstream pause_string;
1230 for (size_t i = 0; i < pauses.size(); ++i) {
1231 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1232 << ((i != pauses.size() - 1) ? ", " : "");
1233 }
1234 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001235 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1236 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1237 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1238 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001239 if (VLOG_IS_ON(heap)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001240 LOG(INFO) << Dumpable<base::NewTimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001241 }
1242 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001243
Ian Rogers15bf2d32012-08-28 17:33:04 -07001244 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001245 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001246 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001247 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001248 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001249 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001250 }
1251 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001252 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001253 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001254 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001255}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001256
Ian Rogers1d54e732013-05-02 21:10:01 -07001257void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::NewTimingLogger& timings,
1258 collector::GcType gc_type) {
1259 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001260 // 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 -07001261 // cards.
1262 return;
1263 }
1264
1265 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001266 if (gc_type == collector::kGcTypePartial) {
1267 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001268 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001269
Ian Rogers1d54e732013-05-02 21:10:01 -07001270 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001271 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001272 }
1273
1274 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001275 timings.NewSplit("UpdateModUnionTable");
1276 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001277
1278 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001279 timings.NewSplit("MarkImageToAllocSpaceReferences");
1280 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001281}
1282
Ian Rogers1d54e732013-05-02 21:10:01 -07001283static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001284 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001285 if (root == obj) {
1286 LOG(INFO) << "Object " << obj << " is a root";
1287 }
1288}
1289
1290class ScanVisitor {
1291 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001292 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001293 LOG(INFO) << "Would have rescanned object " << obj;
1294 }
1295};
1296
Ian Rogers1d54e732013-05-02 21:10:01 -07001297// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001298class VerifyReferenceVisitor {
1299 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001300 VerifyReferenceVisitor(Heap* heap)
1301 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
1302 : heap_(heap), failed_(false) {
1303 }
1304
1305 bool Failed() const {
1306 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001307 }
1308
1309 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001310 // analysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001311 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
Ian Rogers1d54e732013-05-02 21:10:01 -07001312 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001313 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001314 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001315 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1316 accounting::CardTable* card_table = heap_->GetCardTable();
1317 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1318 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001319
Ian Rogers1d54e732013-05-02 21:10:01 -07001320 if (obj != NULL) {
1321 byte* card_addr = card_table->CardFromAddr(obj);
1322 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1323 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1324 << "\nObj type " << PrettyTypeOf(obj)
1325 << "\nRef type " << PrettyTypeOf(ref);
1326 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1327 void* cover_begin = card_table->AddrFromCard(card_addr);
1328 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1329 accounting::CardTable::kCardSize);
1330 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1331 << "-" << cover_end;
1332 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001333
Ian Rogers1d54e732013-05-02 21:10:01 -07001334 // Print out how the object is live.
1335 if (bitmap != NULL && bitmap->Test(obj)) {
1336 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1337 }
1338 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
1339 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1340 }
1341 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
1342 LOG(ERROR) << "Object " << obj << " found in live stack";
1343 }
1344 // Attempt to see if the card table missed the reference.
1345 ScanVisitor scan_visitor;
1346 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1347 card_table->Scan(bitmap, byte_cover_begin,
1348 byte_cover_begin + accounting::CardTable::kCardSize,
1349 scan_visitor, VoidFunctor());
1350
1351 // Search to see if any of the roots reference our object.
1352 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1353 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1354
1355 // Search to see if any of the roots reference our reference.
1356 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1357 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1358 } else {
1359 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001360 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001361 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1362 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001363 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001364 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001365 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001366 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001367 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1368 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1369 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001370 }
1371 }
1372
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001373 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001374 return heap_->IsLiveObjectLocked(obj);
1375 }
1376
1377 static void VerifyRoots(const mirror::Object* root, void* arg) {
1378 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1379 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001380 }
1381
1382 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001383 Heap* const heap_;
1384 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001385};
1386
Ian Rogers1d54e732013-05-02 21:10:01 -07001387// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001388class VerifyObjectVisitor {
1389 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001390 VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001391 }
1392
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001393 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001394 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001395 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1396 // be live or else how did we find it in the live bitmap?
1397 VerifyReferenceVisitor visitor(heap_);
1398 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1399 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001400 }
1401
1402 bool Failed() const {
1403 return failed_;
1404 }
1405
1406 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001407 Heap* const heap_;
1408 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001409};
1410
1411// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001412bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001413 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001414 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001415 allocation_stack_->Sort();
1416 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001417 // Perform the verification.
1418 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001419 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001420 GetLiveBitmap()->Visit(visitor);
1421 // We don't want to verify the objects in the allocation stack since they themselves may be
1422 // pointing to dead objects if they are not reachable.
1423 if (visitor.Failed()) {
1424 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001425 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001426 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001427 return true;
1428}
1429
1430class VerifyReferenceCardVisitor {
1431 public:
1432 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1433 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1434 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001435 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001436 }
1437
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001438 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1439 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001440 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1441 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001442 // Filter out class references since changing an object's class does not mark the card as dirty.
1443 // Also handles large objects, since the only reference they hold is a class reference.
1444 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001445 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001446 // If the object is not dirty and it is referencing something in the live stack other than
1447 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001448 if (!card_table->AddrIsInCardTable(obj)) {
1449 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1450 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001451 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001452 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1453 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001454 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
1455 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1456 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001457 LOG(ERROR) << "Object " << obj << " found in live stack";
1458 }
1459 if (heap_->GetLiveBitmap()->Test(obj)) {
1460 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1461 }
1462 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1463 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1464
1465 // Print which field of the object is dead.
1466 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001467 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001468 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001469 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1470 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001471 CHECK(fields != NULL);
1472 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001473 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001474 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1475 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1476 << PrettyField(cur);
1477 break;
1478 }
1479 }
1480 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001481 const mirror::ObjectArray<mirror::Object>* object_array =
1482 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001483 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1484 if (object_array->Get(i) == ref) {
1485 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1486 }
1487 }
1488 }
1489
1490 *failed_ = true;
1491 }
1492 }
1493 }
1494 }
1495
1496 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001497 Heap* const heap_;
1498 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001499};
1500
1501class VerifyLiveStackReferences {
1502 public:
1503 VerifyLiveStackReferences(Heap* heap)
1504 : heap_(heap),
1505 failed_(false) {
1506
1507 }
1508
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001509 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001510 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1511 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001512 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001513 }
1514
1515 bool Failed() const {
1516 return failed_;
1517 }
1518
1519 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001520 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001521 bool failed_;
1522};
1523
1524bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001525 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001526
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001527 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001528 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001529 VerifyLiveStackReferences visitor(this);
1530 GetLiveBitmap()->Visit(visitor);
1531
1532 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001533 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001534 visitor(*it);
1535 }
1536
1537 if (visitor.Failed()) {
1538 DumpSpaces();
1539 return false;
1540 }
1541 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001542}
1543
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001544void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001545 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001546
1547 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001548 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001549 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001550 }
1551}
1552
Ian Rogers1d54e732013-05-02 21:10:01 -07001553void Heap::ProcessCards(base::NewTimingLogger& timings) {
1554 // Clear cards and keep track of cards cleared in the mod-union table.
1555 typedef std::vector<space::ContinuousSpace*>::iterator It;
1556 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1557 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001558 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001559 timings.NewSplit("ModUnionClearCards");
1560 image_mod_union_table_->ClearCards(space);
1561 } else if (space->IsZygoteSpace()) {
1562 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001563 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001564 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001565 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1566 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001567 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001568 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001569 }
1570 }
1571}
1572
Ian Rogers1d54e732013-05-02 21:10:01 -07001573void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001574 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1575 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001576
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001577 if (verify_pre_gc_heap_) {
1578 thread_list->SuspendAll();
1579 {
1580 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1581 if (!VerifyHeapReferences()) {
1582 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1583 }
1584 }
1585 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001586 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001587
1588 // Check that all objects which reference things in the live stack are on dirty cards.
1589 if (verify_missing_card_marks_) {
1590 thread_list->SuspendAll();
1591 {
1592 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1593 SwapStacks();
1594 // Sort the live stack so that we can quickly binary search it later.
1595 if (!VerifyMissingCardMarks()) {
1596 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1597 }
1598 SwapStacks();
1599 }
1600 thread_list->ResumeAll();
1601 }
1602
1603 if (verify_mod_union_table_) {
1604 thread_list->SuspendAll();
1605 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1606 zygote_mod_union_table_->Update();
1607 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001608 image_mod_union_table_->Update();
1609 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001610 thread_list->ResumeAll();
1611 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001612}
1613
Ian Rogers1d54e732013-05-02 21:10:01 -07001614void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001615 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001616
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001617 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1618 // reachable objects.
1619 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001620 Thread* self = Thread::Current();
1621 CHECK_NE(self->GetState(), kRunnable);
1622 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001623 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001624 {
1625 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1626 // Swapping bound bitmaps does nothing.
1627 gc->SwapBitmaps();
1628 if (!VerifyHeapReferences()) {
1629 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1630 }
1631 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001632 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001633 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001634 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001635 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001636}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001637
Ian Rogers1d54e732013-05-02 21:10:01 -07001638void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001639 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001640
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001641 if (verify_system_weaks_) {
1642 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001643 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001644 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001645 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001646}
1647
Ian Rogers1d54e732013-05-02 21:10:01 -07001648collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1649 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001650 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001651 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001652 bool do_wait;
1653 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001654 {
1655 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001656 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001657 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001658 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001659 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001660 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001661 // We must wait, change thread state then sleep on gc_complete_cond_;
1662 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1663 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001664 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001665 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001666 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001667 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001668 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001669 wait_time = NanoTime() - wait_start;;
1670 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001671 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001672 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001673 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1674 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001675 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001676 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001677 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001678 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001679}
1680
Elliott Hughesc967f782012-04-16 10:23:15 -07001681void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001682 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001683 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001684 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001685}
1686
1687size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001688 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001689}
1690
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001691void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001692 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001693 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001694 << PrettySize(GetMaxMemory());
1695 max_allowed_footprint = GetMaxMemory();
1696 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001697 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001698}
1699
Mathieu Chartier65db8802012-11-20 12:36:46 -08001700void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001701 // We know what our utilization is at this moment.
1702 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001703 const size_t bytes_allocated = GetBytesAllocated();
1704 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001705 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001706
Mathieu Chartier65db8802012-11-20 12:36:46 -08001707 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1708 if (target_size > bytes_allocated + max_free_) {
1709 target_size = bytes_allocated + max_free_;
1710 } else if (target_size < bytes_allocated + min_free_) {
1711 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001712 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001713
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001714 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001715
Ian Rogers1d54e732013-05-02 21:10:01 -07001716 // Calculate when to perform the next ConcurrentGC.
1717 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001718 // Calculate the estimated GC duration.
1719 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1720 // Estimate how many remaining bytes we will have when we need to start the next GC.
1721 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001722 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1723 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1724 // A never going to happen situation that from the estimated allocation rate we will exceed
1725 // the applications entire footprint with the given estimated allocation rate. Schedule
1726 // another GC straight away.
1727 concurrent_start_bytes_ = bytes_allocated;
1728 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001729 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1730 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1731 // right away.
1732 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001733 }
1734 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1735 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1736 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001737}
1738
jeffhaoc1160702011-10-27 15:48:45 -07001739void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001740 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001741 alloc_space_->ClearGrowthLimit();
1742}
1743
Elliott Hughesadb460d2011-10-05 17:02:34 -07001744void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001745 MemberOffset reference_queue_offset,
1746 MemberOffset reference_queueNext_offset,
1747 MemberOffset reference_pendingNext_offset,
1748 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001749 reference_referent_offset_ = reference_referent_offset;
1750 reference_queue_offset_ = reference_queue_offset;
1751 reference_queueNext_offset_ = reference_queueNext_offset;
1752 reference_pendingNext_offset_ = reference_pendingNext_offset;
1753 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1754 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1755 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1756 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1757 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1758 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1759}
1760
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001761mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001762 DCHECK(reference != NULL);
1763 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001764 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001765}
1766
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001767void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001768 DCHECK(reference != NULL);
1769 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1770 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1771}
1772
1773// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001774bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001775 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001776 const mirror::Object* queue =
1777 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1778 const mirror::Object* queue_next =
1779 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001780 return (queue != NULL) && (queue_next == NULL);
1781}
1782
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001783void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001784 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001785 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1786 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001787 EnqueuePendingReference(ref, cleared_reference_list);
1788}
1789
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001790void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001791 DCHECK(ref != NULL);
1792 DCHECK(list != NULL);
1793
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001794 // TODO: Remove this lock, use atomic stacks for storing references.
1795 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001796 if (*list == NULL) {
1797 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1798 *list = ref;
1799 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001800 mirror::Object* head =
1801 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001802 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1803 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1804 }
1805}
1806
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001807mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001808 DCHECK(list != NULL);
1809 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001810 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1811 false);
1812 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001813
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001814 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1815 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001816 if (*list == head) {
1817 ref = *list;
1818 *list = NULL;
1819 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001820 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1821 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001822 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1823 ref = head;
1824 }
1825 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1826 return ref;
1827}
1828
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001829void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001830 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001831 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001832 ArgArray arg_array(NULL, 0);
1833 arg_array.Append(reinterpret_cast<uint32_t>(object));
1834 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001835 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001836}
1837
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001838void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001839 DCHECK(cleared != NULL);
1840 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001841 // When a runtime isn't started there are no reference queues to care about so ignore.
1842 if (LIKELY(Runtime::Current()->IsStarted())) {
1843 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001844 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001845 ArgArray arg_array(NULL, 0);
1846 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1847 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001848 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001849 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001850 *cleared = NULL;
1851 }
1852}
1853
Ian Rogers1f539342012-10-03 21:09:42 -07001854void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001855 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001856 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001857 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001858 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001859 !runtime->IsConcurrentGcEnabled()) {
1860 return;
1861 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001862 {
1863 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1864 if (runtime->IsShuttingDown()) {
1865 return;
1866 }
1867 }
1868 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001869 return;
1870 }
1871
Ian Rogers120f1c72012-09-28 17:17:10 -07001872 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001873 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1874 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001875 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1876 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001877 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001878}
1879
Ian Rogers81d425b2012-09-27 16:03:43 -07001880void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001881 {
1882 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001883 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001884 return;
1885 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001886 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001887
Mathieu Chartier65db8802012-11-20 12:36:46 -08001888 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001889 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001890 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001891 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001892 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07001893 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001894 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001895 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001896}
1897
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001898void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001899 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1900 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1901 // a space it will hold its lock and can become a cause of jank.
1902 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1903 // forking.
1904
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001905 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1906 // because that only marks object heads, so a large array looks like lots of empty space. We
1907 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1908 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1909 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1910 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001911 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001912 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001913 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1914 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001915 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1916 // heap trim occurred in the last two seconds.
1917 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001918 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001919
1920 Thread* self = Thread::Current();
1921 {
1922 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1923 Runtime* runtime = Runtime::Current();
1924 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1925 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1926 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1927 // as we don't hold the lock while requesting the trim).
1928 return;
1929 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001930 }
Ian Rogers48931882013-01-22 14:35:16 -08001931
1932 SchedPolicy policy;
1933 get_sched_policy(self->GetTid(), &policy);
1934 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1935 // Don't trim the heap if we are a foreground or audio app.
1936 return;
1937 }
1938
Ian Rogers1d54e732013-05-02 21:10:01 -07001939 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001940 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001941 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1942 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001943 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1944 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001945 CHECK(!env->ExceptionCheck());
1946}
1947
Ian Rogers48931882013-01-22 14:35:16 -08001948size_t Heap::Trim() {
1949 // Handle a requested heap trim on a thread outside of the main GC thread.
1950 return alloc_space_->Trim();
1951}
1952
Ian Rogers1d54e732013-05-02 21:10:01 -07001953} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001954} // namespace art