blob: e6d3a81fa7c5806eb8aa364b7bc4038e7c6bb46b [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070018
Brian Carlstrom5643b782012-02-05 12:32:53 -080019#include <sys/types.h>
20#include <sys/wait.h>
21
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
24
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
Ian Rogers48931882013-01-22 14:35:16 -080026#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070027#include "debugger.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070028#include "gc/atomic_stack.h"
29#include "gc/card_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "gc/card_table-inl.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070031#include "gc/heap_bitmap.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "gc/heap_bitmap-inl.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070033#include "gc/large_object_space.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070034#include "gc/mark_sweep.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "gc/mark_sweep-inl.h"
Mathieu Chartier2b82db42012-11-14 17:29:05 -080036#include "gc/partial_mark_sweep.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "gc/space_bitmap-inl.h"
Mathieu Chartier2b82db42012-11-14 17:29:05 -080038#include "gc/sticky_mark_sweep.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070039#include "gc/mod_union_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "gc/mod_union_table-inl.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070041#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070042#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080043#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/class-inl.h"
45#include "mirror/field-inl.h"
46#include "mirror/object.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080049#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080050#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070051#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070052#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070053#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070054#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070055#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070056#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070057
58namespace art {
59
Mathieu Chartier2b82db42012-11-14 17:29:05 -080060static const uint64_t kSlowGcThreshold = MsToNs(100);
61static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080062static const bool kDumpGcPerformanceOnShutdown = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070063const double Heap::kDefaultTargetUtilization = 0.5;
64
Elliott Hughesae80b492012-04-24 10:43:17 -070065static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080066 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080067 std::vector<std::string> boot_class_path;
68 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070069 if (boot_class_path.empty()) {
70 LOG(FATAL) << "Failed to generate image because no boot class path specified";
71 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080072
73 std::vector<char*> arg_vector;
74
75 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070076 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080077 const char* dex2oat = dex2oat_string.c_str();
78 arg_vector.push_back(strdup(dex2oat));
79
80 std::string image_option_string("--image=");
81 image_option_string += image_file_name;
82 const char* image_option = image_option_string.c_str();
83 arg_vector.push_back(strdup(image_option));
84
85 arg_vector.push_back(strdup("--runtime-arg"));
86 arg_vector.push_back(strdup("-Xms64m"));
87
88 arg_vector.push_back(strdup("--runtime-arg"));
89 arg_vector.push_back(strdup("-Xmx64m"));
90
91 for (size_t i = 0; i < boot_class_path.size(); i++) {
92 std::string dex_file_option_string("--dex-file=");
93 dex_file_option_string += boot_class_path[i];
94 const char* dex_file_option = dex_file_option_string.c_str();
95 arg_vector.push_back(strdup(dex_file_option));
96 }
97
98 std::string oat_file_option_string("--oat-file=");
99 oat_file_option_string += image_file_name;
100 oat_file_option_string.erase(oat_file_option_string.size() - 3);
101 oat_file_option_string += "oat";
102 const char* oat_file_option = oat_file_option_string.c_str();
103 arg_vector.push_back(strdup(oat_file_option));
104
jeffhao8161c032012-10-31 15:50:00 -0700105 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
106 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800107
Brian Carlstrom265091e2013-01-30 14:08:26 -0800108 if (!kIsTargetBuild) {
109 arg_vector.push_back(strdup("--host"));
110 }
111
Elliott Hughes48436bb2012-02-07 15:23:28 -0800112 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800113 LOG(INFO) << command_line;
114
Elliott Hughes48436bb2012-02-07 15:23:28 -0800115 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800116 char** argv = &arg_vector[0];
117
118 // fork and exec dex2oat
119 pid_t pid = fork();
120 if (pid == 0) {
121 // no allocation allowed between fork and exec
122
123 // change process groups, so we don't get reaped by ProcessManager
124 setpgid(0, 0);
125
126 execv(dex2oat, argv);
127
128 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
129 return false;
130 } else {
131 STLDeleteElements(&arg_vector);
132
133 // wait for dex2oat to finish
134 int status;
135 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
136 if (got_pid != pid) {
137 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
138 return false;
139 }
140 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
141 LOG(ERROR) << dex2oat << " failed: " << command_line;
142 return false;
143 }
144 }
145 return true;
146}
147
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700148void Heap::UnReserveOatFileAddressRange() {
149 oat_file_map_.reset(NULL);
150}
151
Mathieu Chartier0051be62012-10-12 17:47:11 -0700152Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
153 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700154 const std::string& original_image_file_name, bool concurrent_gc)
155 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800156 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700157 concurrent_gc_(concurrent_gc),
158 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800159 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700160 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700161 enforce_heap_growth_rate_(false),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800162 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700163 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700164 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700165 concurrent_start_size_(128 * KB),
166 concurrent_min_free_(256 * KB),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800167 concurrent_start_bytes_(concurrent_gc ? initial_size - concurrent_start_size_ :
168 std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700169 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700170 total_bytes_freed_(0),
171 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700172 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800173 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700174 verify_missing_card_marks_(false),
175 verify_system_weaks_(false),
176 verify_pre_gc_heap_(false),
177 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700178 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700179 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700180 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700181 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700182 last_trim_time_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800183 allocation_rate_(0),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700184 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800185 reference_referent_offset_(0),
186 reference_queue_offset_(0),
187 reference_queueNext_offset_(0),
188 reference_pendingNext_offset_(0),
189 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700190 min_free_(min_free),
191 max_free_(max_free),
192 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700193 total_wait_time_(0),
194 measure_allocation_time_(false),
195 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700196 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800197 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800198 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700199 }
200
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700201 live_bitmap_.reset(new HeapBitmap(this));
202 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700203
Ian Rogers30fab402012-01-23 15:43:46 -0800204 // Requested begin for the alloc space, to follow the mapped image and oat files
205 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800206 std::string image_file_name(original_image_file_name);
207 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700208 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700209
Brian Carlstrom5643b782012-02-05 12:32:53 -0800210 if (OS::FileExists(image_file_name.c_str())) {
211 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700212 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800213 } else {
214 // If the /system file didn't exist, we need to use one from the art-cache.
215 // If the cache file exists, try to open, but if it fails, regenerate.
216 // If it does not exist, generate.
217 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
218 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700219 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800220 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700221 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700222 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700223 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800224 }
225 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700226
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700227 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700228 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800229 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
230 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800231 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
232 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700233
234 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
235 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800236 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700237 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
238 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800239 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700240
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800241 if (oat_file_end_addr > requested_begin) {
242 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700243 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700244 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700245 }
246
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700247 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700248 const bool kUseFreeListSpaceForLOS = false;
249 if (kUseFreeListSpaceForLOS) {
250 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
251 } else {
252 large_object_space_.reset(LargeObjectMapSpace::Create("large object space"));
253 }
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700254 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
255 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
256
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700257 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
258 growth_limit, capacity,
259 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700260 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700261 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700262 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700263 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700264
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700265 // Spaces are sorted in order of Begin().
266 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700267 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
268 if (spaces_.back()->IsAllocSpace()) {
269 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
270 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700271
Ian Rogers30fab402012-01-23 15:43:46 -0800272 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700273 // TODO: C++0x
274 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
275 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800276 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700277 ImageSpace* image_space = space->AsImageSpace();
278 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800279 }
280 }
281
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800282 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700283 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
284 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700285
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700286 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
287 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700288
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700289 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
290 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700291
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700292 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700293 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800295 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700296 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogersa40307e2013-02-22 11:32:44 -0800297 mark_stack_.reset(ObjectStack::Create("mark stack", default_mark_stack_size));
298 allocation_stack_.reset(ObjectStack::Create("allocation stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700299 max_allocation_stack_size_));
Ian Rogersa40307e2013-02-22 11:32:44 -0800300 live_stack_.reset(ObjectStack::Create("live stack",
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700301 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700302
Mathieu Chartier65db8802012-11-20 12:36:46 -0800303 // It's still too early to take a lock because there are no threads yet, but we can create locks
304 // now. We don't create it earlier to make it clear that you can't use locks during heap
305 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700306 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700307 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
308 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700309
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700310 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
311 reference_queue_lock_.reset(new Mutex("reference queue lock"));
312
Mathieu Chartier65db8802012-11-20 12:36:46 -0800313 last_gc_time_ = NanoTime();
314 last_gc_size_ = GetBytesAllocated();
315
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800316 // Create our garbage collectors.
317 for (size_t i = 0; i < 2; ++i) {
318 const bool concurrent = i != 0;
319 mark_sweep_collectors_.push_back(new MarkSweep(this, concurrent));
320 mark_sweep_collectors_.push_back(new PartialMarkSweep(this, concurrent));
321 mark_sweep_collectors_.push_back(new StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700322 }
323
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800324 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800325 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800326 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700327 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700328}
329
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700330void Heap::CreateThreadPool() {
331 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
332 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
333 // workers to complete.
334 thread_pool_.reset(new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
335}
336
337void Heap::DeleteThreadPool() {
338 thread_pool_.reset(NULL);
339}
340
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700341// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700342struct SpaceSorter {
343 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700344 return a->Begin() < b->Begin();
345 }
346};
347
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700348void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700349 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700350 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700351 DCHECK(space->GetLiveBitmap() != NULL);
352 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700353 DCHECK(space->GetMarkBitmap() != NULL);
354 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800355 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700356 if (space->IsAllocSpace()) {
357 alloc_space_ = space->AsAllocSpace();
358 }
359
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700360 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
361 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700362
363 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
364 // avoid redundant marking.
365 bool seen_zygote = false, seen_alloc = false;
366 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
367 Space* space = *it;
368 if (space->IsImageSpace()) {
369 DCHECK(!seen_zygote);
370 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700371 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700372 DCHECK(!seen_alloc);
373 seen_zygote = true;
374 } else if (space->IsAllocSpace()) {
375 seen_alloc = true;
376 }
377 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800378}
379
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700380void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700381 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700382 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700383 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800384
385 // Dump cumulative loggers for each GC type.
386 // TODO: C++0x
387 uint64_t total_paused_time = 0;
388 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800389 it != mark_sweep_collectors_.end(); ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800390 MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800391 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800392 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700393 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800394 const uint64_t total_ns = logger.GetTotalNs();
395 const uint64_t total_pause_ns = (*it)->GetTotalPausedTime();
396 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
397 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
398 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700399 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
400 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
401 << collector->GetName() << " freed: " << freed_objects
402 << " objects with total size " << PrettySize(freed_bytes) << "\n"
403 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
404 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800405 total_duration += total_ns;
406 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700407 }
408 }
409 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
410 size_t total_objects_allocated = GetTotalObjectsAllocated();
411 size_t total_bytes_allocated = GetTotalBytesAllocated();
412 if (total_duration != 0) {
413 const double total_seconds = double(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700414 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
415 os << "Mean GC size throughput: "
416 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s\n";
417 os << "Mean GC object throughput: "
418 << (GetTotalObjectsFreed() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700419 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700420 os << "Total number of allocations: " << total_objects_allocated << "\n";
421 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700422 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700423 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
424 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
425 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700426 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700427 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
428 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700429}
430
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800431Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700432 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700433 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700434 }
435
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800436 STLDeleteElements(&mark_sweep_collectors_);
437
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700438 // If we don't reset then the mark stack complains in it's destructor.
439 allocation_stack_->Reset();
440 live_stack_->Reset();
441
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800442 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800443 // We can't take the heap lock here because there might be a daemon thread suspended with the
444 // heap lock held. We know though that no non-daemon threads are executing, and we know that
445 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
446 // those threads can't resume. We're the only running thread, and we can do whatever we like...
Carl Shapiro58551df2011-07-24 03:09:51 -0700447 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448 delete gc_complete_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700449}
450
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800451ContinuousSpace* Heap::FindSpaceFromObject(const mirror::Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700452 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700453 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
454 if ((*it)->Contains(obj)) {
455 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700456 }
457 }
458 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
459 return NULL;
460}
461
462ImageSpace* Heap::GetImageSpace() {
463 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700464 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
465 if ((*it)->IsImageSpace()) {
466 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700467 }
468 }
469 return NULL;
470}
471
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700472DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700473 return alloc_space_;
474}
475
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700476static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700477 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700478 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700479 size_t chunk_free_bytes = chunk_size - used_bytes;
480 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
481 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700482 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700483}
484
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800485mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
486 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
488 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800489 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700490
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800491 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700492 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700493 uint64_t allocation_start = 0;
494 if (measure_allocation_time_) {
495 allocation_start = NanoTime();
496 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700497
498 // We need to have a zygote space or else our newly allocated large object can end up in the
499 // Zygote resulting in it being prematurely freed.
500 // We can only do this for primive objects since large objects will not be within the card table
501 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers22a20862013-03-16 16:34:57 -0700502 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700503 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700504 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700505 // Make sure that our large object didn't get placed anywhere within the space interval or else
506 // it breaks the immune range.
507 DCHECK(obj == NULL ||
508 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
509 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700510 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700511 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700512
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700513 // Ensure that we did not allocate into a zygote space.
514 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
515 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700516 }
517
Mathieu Chartier037813d2012-08-23 16:44:59 -0700518 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700520
521 // Record allocation after since we want to use the atomic add for the atomic fence to guard
522 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700523 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700524
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700525 if (Dbg::IsAllocTrackingEnabled()) {
526 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700527 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700528 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700529 // We already have a request pending, no reason to start more until we update
530 // concurrent_start_bytes_.
531 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700532 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800533 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700534 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700535 }
536 VerifyObject(obj);
537
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700538 if (measure_allocation_time_) {
539 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
540 }
541
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700542 return obj;
543 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800544 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700545 int64_t total_bytes_free = GetFreeMemory();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800546 uint64_t alloc_space_size = alloc_space_->GetNumBytesAllocated();
547 uint64_t large_object_size = large_object_space_->GetNumObjectsAllocated();
548 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
549 << " free bytes; allocation space size " << alloc_space_size
550 << "; large object space size " << large_object_size;
551 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
552 if (total_bytes_free >= byte_count) {
553 size_t max_contiguous_allocation = 0;
554 // TODO: C++0x auto
555 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
556 if ((*it)->IsAllocSpace()) {
557 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
558 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700559 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800560 oss << "; failed due to fragmentation (largest possible contiguous allocation "
561 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700562 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800563 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700564 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700565}
566
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800567bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700568 // Note: we deliberately don't take the lock here, and mustn't test anything that would
569 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700570 if (obj == NULL) {
571 return true;
572 }
573 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700574 return false;
575 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800576 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800577 if (spaces_[i]->Contains(obj)) {
578 return true;
579 }
580 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700581 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700582}
583
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800584bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700585 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700586 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700587}
588
Ian Rogers04d7aa92013-03-16 14:29:17 -0700589void Heap::VerifyObjectImpl(const mirror::Object* obj) {
590 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700591 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700592 return;
593 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700594 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700595}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700596
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700597void Heap::DumpSpaces() {
598 // TODO: C++0x auto
599 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700600 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700601 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
602 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
603 LOG(INFO) << space << " " << *space << "\n"
604 << live_bitmap << " " << *live_bitmap << "\n"
605 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700606 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700607 if (large_object_space_.get() != NULL) {
608 large_object_space_->Dump(LOG(INFO));
609 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700610}
611
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800612void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800613 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700614 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700615 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800616 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
617 return;
618 }
619 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
620 mirror::Object::ClassOffset().Int32Value();
621 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
622 if (UNLIKELY(c == NULL)) {
623 LOG(FATAL) << "Null class in object: " << obj;
624 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
625 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
626 }
627 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
628 // Note: we don't use the accessors here as they have internal sanity checks
629 // that we don't want to run
630 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
631 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
632 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
633 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
634 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700635
Ian Rogers62d6c772013-02-27 08:32:07 -0800636 if (verify_object_mode_ != kVerifyAllFast) {
637 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
638 // heap_bitmap_lock_.
639 if (!GetLiveBitmap()->Test(obj)) {
640 // Check the allocation stack / live stack.
641 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
642 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
643 allocation_stack_->End()) {
644 if (large_object_space_->GetLiveObjects()->Test(obj)) {
645 DumpSpaces();
646 LOG(FATAL) << "Object is dead: " << obj;
647 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700648 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700649 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800650 if (!GetLiveBitmap()->Test(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700651 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
652 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700653 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700654}
655
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800656void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700657 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700658 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700659}
660
661void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700662 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700663 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700664}
665
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800666void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700667 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700668 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700669 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700670
671 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700672 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700673 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700674 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700675
676 // TODO: Update these atomically.
677 RuntimeStats* global_stats = Runtime::Current()->GetStats();
678 ++global_stats->allocated_objects;
679 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700680 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700681
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700682 // This is safe to do since the GC will never free objects which are neither in the allocation
683 // stack or the live bitmap.
684 while (!allocation_stack_->AtomicPushBack(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700685 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700686 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700687}
688
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700689void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700690 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
691 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700692
693 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700694 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700695 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700696 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700697
698 // TODO: Do this concurrently.
699 RuntimeStats* global_stats = Runtime::Current()->GetStats();
700 global_stats->freed_objects += freed_objects;
701 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700702 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700703}
704
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800705mirror::Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700706 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800707 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
708 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
709 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
710 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700711 return NULL;
712 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700713
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800714 if (enforce_heap_growth_rate_) {
715 if (grow) {
716 // Grow the heap by alloc_size extra bytes.
717 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
718 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
719 << " for a " << PrettySize(alloc_size) << " allocation";
720 } else {
721 return NULL;
722 }
723 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700724 }
725
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700726 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700727}
728
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800729mirror::Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700730 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
731 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700732 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700733 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700734
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800735 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700736 if (ptr != NULL) {
737 return ptr;
738 }
739
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700740 // The allocation failed. If the GC is running, block until it completes, and then retry the
741 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700742 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700743 if (last_gc != kGcTypeNone) {
744 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700745 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700746 if (ptr != NULL) {
747 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700748 }
749 }
750
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700751 // Loop through our different Gc types and try to Gc until we get enough free memory.
752 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
753 bool run_gc = false;
754 GcType gc_type = static_cast<GcType>(i);
755 switch (gc_type) {
756 case kGcTypeSticky: {
757 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700758 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
759 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700760 break;
761 }
762 case kGcTypePartial:
763 run_gc = have_zygote_space_;
764 break;
765 case kGcTypeFull:
766 run_gc = true;
767 break;
768 default:
769 break;
770 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700771
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700772 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700773 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700774 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800775 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700776 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700777
778 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700779 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700780 if (ptr != NULL) {
781 return ptr;
782 }
783 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700784 }
785
786 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700787 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700788 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700789 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700790 return ptr;
791 }
792
Elliott Hughes81ff3182012-03-23 20:35:56 -0700793 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
794 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
795 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700796
Elliott Hughes418dfe72011-10-06 18:56:27 -0700797 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700798 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
799 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700800
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700801 // We don't need a WaitForConcurrentGcToComplete here either.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700802 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700803 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700804}
805
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700806void Heap::SetTargetHeapUtilization(float target) {
807 DCHECK_GT(target, 0.0f); // asserted in Java code
808 DCHECK_LT(target, 1.0f);
809 target_utilization_ = target;
810}
811
812int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700813 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700814}
815
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700816int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700817 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700818}
819
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700820int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700821 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700822}
823
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700824size_t Heap::GetTotalBytesFreed() const {
825 return total_bytes_freed_;
826}
827
828size_t Heap::GetTotalObjectsFreed() const {
829 return total_objects_freed_;
830}
831
832size_t Heap::GetTotalObjectsAllocated() const {
833 size_t total = large_object_space_->GetTotalObjectsAllocated();
834 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
835 Space* space = *it;
836 if (space->IsAllocSpace()) {
837 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
838 }
839 }
840 return total;
841}
842
843size_t Heap::GetTotalBytesAllocated() const {
844 size_t total = large_object_space_->GetTotalBytesAllocated();
845 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
846 Space* space = *it;
847 if (space->IsAllocSpace()) {
848 total += space->AsAllocSpace()->GetTotalBytesAllocated();
849 }
850 }
851 return total;
852}
853
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700854class InstanceCounter {
855 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800856 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700857 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800858 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700859 }
860
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800861 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800862 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800863 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800864 if (use_is_assignable_from_) {
865 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
866 ++counts_[i];
867 }
868 } else {
869 if (instance_class == classes_[i]) {
870 ++counts_[i];
871 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700872 }
873 }
874 }
875
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700876 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800877 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800878 bool use_is_assignable_from_;
879 uint64_t* const counts_;
880
881 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700882};
883
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800884void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800885 uint64_t* counts) {
886 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
887 // is empty, so the live bitmap is the only place we need to look.
888 Thread* self = Thread::Current();
889 self->TransitionFromRunnableToSuspended(kNative);
890 CollectGarbage(false);
891 self->TransitionFromSuspendedToRunnable();
892
893 InstanceCounter counter(classes, use_is_assignable_from, counts);
894 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700895 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700896}
897
Elliott Hughes3b78c942013-01-15 17:35:41 -0800898class InstanceCollector {
899 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800900 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800901 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
902 : class_(c), max_count_(max_count), instances_(instances) {
903 }
904
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800905 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
906 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800907 if (instance_class == class_) {
908 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800909 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800910 }
911 }
912 }
913
914 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800915 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800916 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800917 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800918
919 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
920};
921
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800922void Heap::GetInstances(mirror::Class* c, int32_t max_count,
923 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800924 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
925 // is empty, so the live bitmap is the only place we need to look.
926 Thread* self = Thread::Current();
927 self->TransitionFromRunnableToSuspended(kNative);
928 CollectGarbage(false);
929 self->TransitionFromSuspendedToRunnable();
930
931 InstanceCollector collector(c, max_count, instances);
932 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
933 GetLiveBitmap()->Visit(collector);
934}
935
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800936class ReferringObjectsFinder {
937 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800938 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
939 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800940 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
941 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
942 }
943
944 // For bitmap Visit.
945 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
946 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800947 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800948 MarkSweep::VisitObjectReferences(o, *this);
949 }
950
951 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800952 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
953 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800954 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800955 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800956 }
957 }
958
959 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800960 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800961 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800962 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800963
964 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
965};
966
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800967void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
968 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800969 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
970 // is empty, so the live bitmap is the only place we need to look.
971 Thread* self = Thread::Current();
972 self->TransitionFromRunnableToSuspended(kNative);
973 CollectGarbage(false);
974 self->TransitionFromSuspendedToRunnable();
975
976 ReferringObjectsFinder finder(o, max_count, referring_objects);
977 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
978 GetLiveBitmap()->Visit(finder);
979}
980
Ian Rogers30fab402012-01-23 15:43:46 -0800981void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700982 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
983 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700984 Thread* self = Thread::Current();
985 WaitForConcurrentGcToComplete(self);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700986 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700987}
988
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700989void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700990 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800991 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
992 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700993 Thread* self = Thread::Current();
994 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700995
996 // Try to see if we have any Zygote spaces.
997 if (have_zygote_space_) {
998 return;
999 }
1000
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001001 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1002
1003 {
1004 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001005 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001006 FlushAllocStack();
1007 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001008
1009 // Replace the first alloc space we find with a zygote space.
1010 // TODO: C++0x auto
1011 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1012 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001013 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001014
1015 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1016 // of the remaining available heap memory.
1017 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001018 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001019
1020 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001021 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001022 AddSpace(alloc_space_);
1023 have_zygote_space_ = true;
1024 break;
1025 }
1026 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001027
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001028 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001029 // TODO: C++0x
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001030 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
1031 it != mark_sweep_collectors_.end(); ++it) {
1032 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001033 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001034}
1035
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001036void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001037 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1038 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001039 allocation_stack_->Reset();
1040}
1041
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001042size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001043 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001044}
1045
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001046void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001047 mirror::Object** limit = stack->End();
1048 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1049 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001050 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001051 if (LIKELY(bitmap->HasAddress(obj))) {
1052 bitmap->Set(obj);
1053 } else {
1054 large_objects->Set(obj);
1055 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001056 }
1057}
1058
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001059void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001060 mirror::Object** limit = stack->End();
1061 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1062 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001063 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001064 if (LIKELY(bitmap->HasAddress(obj))) {
1065 bitmap->Clear(obj);
1066 } else {
1067 large_objects->Clear(obj);
1068 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001069 }
1070}
1071
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001072GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001073 Thread* self = Thread::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001074 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001075 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001076
Ian Rogers120f1c72012-09-28 17:17:10 -07001077 if (self->IsHandlingStackOverflow()) {
1078 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1079 }
1080
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001081 // Ensure there is only one GC at a time.
1082 bool start_collect = false;
1083 while (!start_collect) {
1084 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001085 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001086 if (!is_gc_running_) {
1087 is_gc_running_ = true;
1088 start_collect = true;
1089 }
1090 }
1091 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001092 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001093 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1094 // Not doing at the moment to ensure soft references are cleared.
1095 }
1096 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001097 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001098
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001099 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1100 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1101 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1102 }
1103
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001104 // We need to do partial GCs every now and then to avoid the heap growing too much and
1105 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001106 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001107 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001108 }
Mathieu Chartier0325e622012-09-05 14:22:51 -07001109 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001110 sticky_gc_count_ = 0;
1111 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001112
Mathieu Chartier65db8802012-11-20 12:36:46 -08001113 uint64_t gc_start_time = NanoTime();
1114 uint64_t gc_start_size = GetBytesAllocated();
1115 // Approximate allocation rate in bytes / second.
Jeff Hao9bd02812013-02-08 14:29:50 -08001116 if (UNLIKELY(gc_start_time == last_gc_time_)) {
1117 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1118 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001119 uint64_t ms_delta = NsToMs(gc_start_time - last_gc_time_);
1120 if (ms_delta != 0) {
1121 allocation_rate_ = (gc_start_size - last_gc_size_) * 1000 / ms_delta;
1122 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1123 }
1124
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001125 DCHECK_LT(gc_type, kGcTypeMax);
1126 DCHECK_NE(gc_type, kGcTypeNone);
1127 MarkSweep* collector = NULL;
1128 for (Collectors::iterator it = mark_sweep_collectors_.begin();
1129 it != mark_sweep_collectors_.end(); ++it) {
1130 MarkSweep* cur_collector = *it;
1131 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1132 collector = cur_collector;
1133 break;
1134 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001135 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001136 CHECK(collector != NULL)
1137 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1138 << " and type=" << gc_type;
1139 collector->clear_soft_references_ = clear_soft_references;
1140 collector->Run();
1141 total_objects_freed_ += collector->GetFreedObjects();
1142 total_bytes_freed_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001143
Mathieu Chartier65db8802012-11-20 12:36:46 -08001144 const size_t duration = collector->GetDuration();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001145 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1146 bool was_slow = duration > kSlowGcThreshold ||
1147 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1148 for (size_t i = 0; i < pauses.size(); ++i) {
1149 if (pauses[i] > kLongGcPauseThreshold) {
1150 was_slow = true;
1151 }
1152 }
1153
1154 if (was_slow) {
1155 const size_t percent_free = GetPercentFree();
1156 const size_t current_heap_size = GetUsedMemorySize();
1157 const size_t total_memory = GetTotalMemory();
1158 std::ostringstream pause_string;
1159 for (size_t i = 0; i < pauses.size(); ++i) {
1160 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1161 << ((i != pauses.size() - 1) ? ", " : "");
1162 }
1163 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001164 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1165 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1166 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1167 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001168 if (VLOG_IS_ON(heap)) {
Sameer Abu Asala8439542013-02-14 16:06:42 -08001169 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001170 }
1171 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001172
Ian Rogers15bf2d32012-08-28 17:33:04 -07001173 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001174 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001175 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001176 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001177 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001178 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001179 }
1180 // Inform DDMS that a GC completed.
1181 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001182 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001183}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001184
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001185void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001186 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001187 // 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 -07001188 // cards.
1189 return;
1190 }
1191
1192 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001193 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001194 zygote_mod_union_table_->Update();
1195 timings.AddSplit("UpdateZygoteModUnionTable");
1196
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001197 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001198 timings.AddSplit("ZygoteMarkReferences");
1199 }
1200
1201 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1202 mod_union_table_->Update();
1203 timings.AddSplit("UpdateModUnionTable");
1204
1205 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001206 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001207 timings.AddSplit("MarkImageToAllocSpaceReferences");
1208}
1209
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001210void Heap::RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
1211 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001212 if (root == obj) {
1213 LOG(INFO) << "Object " << obj << " is a root";
1214 }
1215}
1216
1217class ScanVisitor {
1218 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001219 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001220 LOG(INFO) << "Would have rescanned object " << obj;
1221 }
1222};
1223
1224class VerifyReferenceVisitor {
1225 public:
1226 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001227 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1228 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001229 : heap_(heap),
1230 failed_(failed) {
1231 }
1232
1233 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1234 // analysis.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001235 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
1236 const MemberOffset& /* offset */, bool /* is_static */) const
1237 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001238 // Verify that the reference is live.
1239 if (ref != NULL && !IsLive(ref)) {
1240 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001241 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1242 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001243
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001244 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001245 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1246 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1247 << "Obj type " << PrettyTypeOf(obj) << "\n"
1248 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001249 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001250 void* cover_begin = card_table->AddrFromCard(card_addr);
1251 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001252 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001253 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001254 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001255 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1256
1257 // Print out how the object is live.
1258 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001259 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1260 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001261 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1262 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1263 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001264 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1265 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001266 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001267 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001268 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001269 }
1270
1271 // Attempt to see if the card table missed the reference.
1272 ScanVisitor scan_visitor;
1273 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001274 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001275 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001276
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001277 // Search to see if any of the roots reference our object.
1278 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1279 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1280 *failed_ = true;
1281 }
1282 }
1283
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001284 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001285 if (heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001286 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001287 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001288 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001289 // At this point we need to search the allocation since things in the live stack may get swept.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001290 // If the object is not either in the live bitmap or allocation stack, so the object must be
1291 // dead.
1292 return std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001293 }
1294
1295 private:
1296 Heap* heap_;
1297 bool* failed_;
1298};
1299
1300class VerifyObjectVisitor {
1301 public:
1302 VerifyObjectVisitor(Heap* heap)
1303 : heap_(heap),
1304 failed_(false) {
1305
1306 }
1307
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001308 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001309 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001310 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1311 MarkSweep::VisitObjectReferences(obj, visitor);
1312 }
1313
1314 bool Failed() const {
1315 return failed_;
1316 }
1317
1318 private:
1319 Heap* heap_;
1320 bool failed_;
1321};
1322
1323// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001324bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001325 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001326 // Lets sort our allocation stacks so that we can efficiently binary search them.
1327 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1328 std::sort(live_stack_->Begin(), live_stack_->End());
1329 // Perform the verification.
1330 VerifyObjectVisitor visitor(this);
1331 GetLiveBitmap()->Visit(visitor);
1332 // We don't want to verify the objects in the allocation stack since they themselves may be
1333 // pointing to dead objects if they are not reachable.
1334 if (visitor.Failed()) {
1335 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001336 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001337 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001338 return true;
1339}
1340
1341class VerifyReferenceCardVisitor {
1342 public:
1343 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1344 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1345 Locks::heap_bitmap_lock_)
1346 : heap_(heap),
1347 failed_(failed) {
1348 }
1349
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001350 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1351 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001352 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1353 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001354 // Filter out class references since changing an object's class does not mark the card as dirty.
1355 // Also handles large objects, since the only reference they hold is a class reference.
1356 if (ref != NULL && !ref->IsClass()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001357 CardTable* card_table = heap_->GetCardTable();
1358 // If the object is not dirty and it is referencing something in the live stack other than
1359 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001360 if (!card_table->AddrIsInCardTable(obj)) {
1361 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1362 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001363 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001364 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1365 // kCardDirty - 1 if it didnt get touched since we aged it.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001366 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001367 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001368 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1369 LOG(ERROR) << "Object " << obj << " found in live stack";
1370 }
1371 if (heap_->GetLiveBitmap()->Test(obj)) {
1372 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1373 }
1374 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1375 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1376
1377 // Print which field of the object is dead.
1378 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001379 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001380 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001381 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1382 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001383 CHECK(fields != NULL);
1384 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001385 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001386 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1387 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1388 << PrettyField(cur);
1389 break;
1390 }
1391 }
1392 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001393 const mirror::ObjectArray<mirror::Object>* object_array =
1394 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001395 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1396 if (object_array->Get(i) == ref) {
1397 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1398 }
1399 }
1400 }
1401
1402 *failed_ = true;
1403 }
1404 }
1405 }
1406 }
1407
1408 private:
1409 Heap* heap_;
1410 bool* failed_;
1411};
1412
1413class VerifyLiveStackReferences {
1414 public:
1415 VerifyLiveStackReferences(Heap* heap)
1416 : heap_(heap),
1417 failed_(false) {
1418
1419 }
1420
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001421 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001422 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1423 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1424 MarkSweep::VisitObjectReferences(obj, visitor);
1425 }
1426
1427 bool Failed() const {
1428 return failed_;
1429 }
1430
1431 private:
1432 Heap* heap_;
1433 bool failed_;
1434};
1435
1436bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001437 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001438
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001439 // We need to sort the live stack since we binary search it.
1440 std::sort(live_stack_->Begin(), live_stack_->End());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001441 VerifyLiveStackReferences visitor(this);
1442 GetLiveBitmap()->Visit(visitor);
1443
1444 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001445 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001446 visitor(*it);
1447 }
1448
1449 if (visitor.Failed()) {
1450 DumpSpaces();
1451 return false;
1452 }
1453 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001454}
1455
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001456void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001457 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001458
1459 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001460 if (verify_object_mode_ > kNoHeapVerification) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001461 std::sort(live_stack_->Begin(), live_stack_->End());
1462 }
1463}
1464
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001465void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001466 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1467 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1468 ContinuousSpace* space = *it;
1469 if (space->IsImageSpace()) {
1470 mod_union_table_->ClearCards(*it);
1471 timings.AddSplit("ModUnionClearCards");
1472 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1473 zygote_mod_union_table_->ClearCards(space);
1474 timings.AddSplit("ZygoteModUnionClearCards");
1475 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001476 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1477 // were dirty before the GC started.
1478 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1479 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001480 }
1481 }
1482}
1483
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001484void Heap::PreGcVerification(GarbageCollector* gc) {
1485 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1486 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001487
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001488 if (verify_pre_gc_heap_) {
1489 thread_list->SuspendAll();
1490 {
1491 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1492 if (!VerifyHeapReferences()) {
1493 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1494 }
1495 }
1496 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001497 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001498
1499 // Check that all objects which reference things in the live stack are on dirty cards.
1500 if (verify_missing_card_marks_) {
1501 thread_list->SuspendAll();
1502 {
1503 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1504 SwapStacks();
1505 // Sort the live stack so that we can quickly binary search it later.
1506 if (!VerifyMissingCardMarks()) {
1507 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1508 }
1509 SwapStacks();
1510 }
1511 thread_list->ResumeAll();
1512 }
1513
1514 if (verify_mod_union_table_) {
1515 thread_list->SuspendAll();
1516 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1517 zygote_mod_union_table_->Update();
1518 zygote_mod_union_table_->Verify();
1519 mod_union_table_->Update();
1520 mod_union_table_->Verify();
1521 thread_list->ResumeAll();
1522 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001523}
1524
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001525void Heap::PreSweepingGcVerification(GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001526 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001527 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001528
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001529 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1530 // reachable objects.
1531 if (verify_post_gc_heap_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001532 thread_list->SuspendAll();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001533 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1534 // Swapping bound bitmaps does nothing.
1535 live_bitmap_.swap(mark_bitmap_);
1536 if (!VerifyHeapReferences()) {
1537 LOG(FATAL) << "Post " << gc->GetName() << "Gc verification failed";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001538 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001539 live_bitmap_.swap(mark_bitmap_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001541 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001542}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001543
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001544void Heap::PostGcVerification(GarbageCollector* gc) {
1545 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001546
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001547 if (verify_system_weaks_) {
1548 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1549 MarkSweep* mark_sweep = down_cast<MarkSweep*>(gc);
1550 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001551 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001552}
1553
Ian Rogers81d425b2012-09-27 16:03:43 -07001554GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001555 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001557 bool do_wait;
1558 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001559 {
1560 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001561 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001562 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001563 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001565 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001566 // We must wait, change thread state then sleep on gc_complete_cond_;
1567 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1568 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001569 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001570 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001571 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001572 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001573 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001574 wait_time = NanoTime() - wait_start;;
1575 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001576 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001577 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001578 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1579 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001580 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001581 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001582 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001583}
1584
Elliott Hughesc967f782012-04-16 10:23:15 -07001585void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001586 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1587 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001588 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001589}
1590
1591size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001592 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001593}
1594
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001595void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001596 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001597 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001598 << PrettySize(GetMaxMemory());
1599 max_allowed_footprint = GetMaxMemory();
1600 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001601 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001602}
1603
Mathieu Chartier65db8802012-11-20 12:36:46 -08001604void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001605 // We know what our utilization is at this moment.
1606 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001607 const size_t bytes_allocated = GetBytesAllocated();
1608 last_gc_size_ = bytes_allocated;
1609 last_gc_time_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001610
Mathieu Chartier65db8802012-11-20 12:36:46 -08001611 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1612 if (target_size > bytes_allocated + max_free_) {
1613 target_size = bytes_allocated + max_free_;
1614 } else if (target_size < bytes_allocated + min_free_) {
1615 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001616 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001617
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001618 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001619
1620 // Calculate when to perform the next ConcurrentGC if we have enough free memory.
1621 if (concurrent_gc_ && GetFreeMemory() >= concurrent_min_free_) {
1622 // Calculate the estimated GC duration.
1623 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1624 // Estimate how many remaining bytes we will have when we need to start the next GC.
1625 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1626 if (remaining_bytes < max_allowed_footprint_) {
1627 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1628 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1629 // right away.
1630 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1631 } else {
1632 // The estimated rate is so high that we should request another GC straight away.
1633 concurrent_start_bytes_ = bytes_allocated;
1634 }
1635 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1636 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1637 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001638}
1639
jeffhaoc1160702011-10-27 15:48:45 -07001640void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001641 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001642 alloc_space_->ClearGrowthLimit();
1643}
1644
Elliott Hughesadb460d2011-10-05 17:02:34 -07001645void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001646 MemberOffset reference_queue_offset,
1647 MemberOffset reference_queueNext_offset,
1648 MemberOffset reference_pendingNext_offset,
1649 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001650 reference_referent_offset_ = reference_referent_offset;
1651 reference_queue_offset_ = reference_queue_offset;
1652 reference_queueNext_offset_ = reference_queueNext_offset;
1653 reference_pendingNext_offset_ = reference_pendingNext_offset;
1654 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1655 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1656 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1657 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1658 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1659 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1660}
1661
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001662mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001663 DCHECK(reference != NULL);
1664 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001665 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001666}
1667
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001668void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001669 DCHECK(reference != NULL);
1670 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1671 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1672}
1673
1674// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001675bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001676 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001677 const mirror::Object* queue =
1678 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1679 const mirror::Object* queue_next =
1680 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001681 return (queue != NULL) && (queue_next == NULL);
1682}
1683
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001684void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001685 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001686 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1687 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001688 EnqueuePendingReference(ref, cleared_reference_list);
1689}
1690
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001691void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001692 DCHECK(ref != NULL);
1693 DCHECK(list != NULL);
1694
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001695 // TODO: Remove this lock, use atomic stacks for storing references.
1696 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001697 if (*list == NULL) {
1698 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1699 *list = ref;
1700 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001701 mirror::Object* head =
1702 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001703 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1704 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1705 }
1706}
1707
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001708mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001709 DCHECK(list != NULL);
1710 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001711 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1712 false);
1713 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001714
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001715 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1716 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001717 if (*list == head) {
1718 ref = *list;
1719 *list = NULL;
1720 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001721 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1722 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001723 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1724 ref = head;
1725 }
1726 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1727 return ref;
1728}
1729
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001730void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001731 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001732 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001733 ArgArray arg_array(NULL, 0);
1734 arg_array.Append(reinterpret_cast<uint32_t>(object));
1735 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001736 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001737}
1738
1739size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001740 return num_bytes_allocated_;
1741}
1742
1743size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001744 size_t total = 0;
1745 // TODO: C++0x
1746 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1747 Space* space = *it;
1748 if (space->IsAllocSpace()) {
1749 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1750 }
1751 }
1752 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001753}
1754
1755size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001756 return concurrent_start_size_;
1757}
1758
1759size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001760 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001761}
1762
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001763void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001764 DCHECK(cleared != NULL);
1765 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001766 // When a runtime isn't started there are no reference queues to care about so ignore.
1767 if (LIKELY(Runtime::Current()->IsStarted())) {
1768 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001769 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001770 ArgArray arg_array(NULL, 0);
1771 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1772 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001773 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001774 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001775 *cleared = NULL;
1776 }
1777}
1778
Ian Rogers1f539342012-10-03 21:09:42 -07001779void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001780 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001781 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001782 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001783 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001784 !runtime->IsConcurrentGcEnabled()) {
1785 return;
1786 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001787 {
1788 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1789 if (runtime->IsShuttingDown()) {
1790 return;
1791 }
1792 }
1793 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001794 return;
1795 }
1796
Ian Rogers120f1c72012-09-28 17:17:10 -07001797 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001798 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1799 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001800 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1801 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001802 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001803}
1804
Ian Rogers81d425b2012-09-27 16:03:43 -07001805void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001806 {
1807 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001808 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001809 return;
1810 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001811 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001812
Mathieu Chartier65db8802012-11-20 12:36:46 -08001813 // Wait for any GCs currently running to finish.
Ian Rogers81d425b2012-09-27 16:03:43 -07001814 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001815 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001816 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001817 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001818 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001819 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001820 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001821}
1822
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001823void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001824 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1825 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1826 // a space it will hold its lock and can become a cause of jank.
1827 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1828 // forking.
1829
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001830 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1831 // because that only marks object heads, so a large array looks like lots of empty space. We
1832 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1833 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1834 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1835 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001836 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001837 float utilization =
1838 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1839 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1840 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1841 // heap trim occurred in the last two seconds.
1842 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001843 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001844
1845 Thread* self = Thread::Current();
1846 {
1847 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1848 Runtime* runtime = Runtime::Current();
1849 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1850 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1851 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1852 // as we don't hold the lock while requesting the trim).
1853 return;
1854 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001855 }
Ian Rogers48931882013-01-22 14:35:16 -08001856
1857 SchedPolicy policy;
1858 get_sched_policy(self->GetTid(), &policy);
1859 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1860 // Don't trim the heap if we are a foreground or audio app.
1861 return;
1862 }
1863
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001864 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001865 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001866 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1867 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001868 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1869 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001870 CHECK(!env->ExceptionCheck());
1871}
1872
Ian Rogers48931882013-01-22 14:35:16 -08001873size_t Heap::Trim() {
1874 // Handle a requested heap trim on a thread outside of the main GC thread.
1875 return alloc_space_->Trim();
1876}
1877
Carl Shapiro69759ea2011-07-21 18:13:35 -07001878} // namespace art