blob: e531dc8010da8d9b7aa13886108288603721b5f2 [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"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/class-inl.h"
44#include "mirror/field-inl.h"
45#include "mirror/object.h"
46#include "mirror/object-inl.h"
47#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080048#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080049#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070050#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070051#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070052#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070053#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070054#include "timing_logger.h"
55#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
Elliott Hughes48436bb2012-02-07 15:23:28 -0800108 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800109 LOG(INFO) << command_line;
110
Elliott Hughes48436bb2012-02-07 15:23:28 -0800111 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800112 char** argv = &arg_vector[0];
113
114 // fork and exec dex2oat
115 pid_t pid = fork();
116 if (pid == 0) {
117 // no allocation allowed between fork and exec
118
119 // change process groups, so we don't get reaped by ProcessManager
120 setpgid(0, 0);
121
122 execv(dex2oat, argv);
123
124 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
125 return false;
126 } else {
127 STLDeleteElements(&arg_vector);
128
129 // wait for dex2oat to finish
130 int status;
131 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
132 if (got_pid != pid) {
133 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
134 return false;
135 }
136 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
137 LOG(ERROR) << dex2oat << " failed: " << command_line;
138 return false;
139 }
140 }
141 return true;
142}
143
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700144void Heap::UnReserveOatFileAddressRange() {
145 oat_file_map_.reset(NULL);
146}
147
Mathieu Chartier0051be62012-10-12 17:47:11 -0700148Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
149 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700150 const std::string& original_image_file_name, bool concurrent_gc)
151 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800152 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700153 concurrent_gc_(concurrent_gc),
154 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800155 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700156 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700157 enforce_heap_growth_rate_(false),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800158 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700159 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700160 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700161 concurrent_start_size_(128 * KB),
162 concurrent_min_free_(256 * KB),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800163 concurrent_start_bytes_(concurrent_gc ? initial_size - concurrent_start_size_ :
164 std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700165 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700166 total_bytes_freed_(0),
167 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700168 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800169 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700170 verify_missing_card_marks_(false),
171 verify_system_weaks_(false),
172 verify_pre_gc_heap_(false),
173 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700174 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700175 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700176 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700177 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700178 last_trim_time_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800179 allocation_rate_(0),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700180 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800181 reference_referent_offset_(0),
182 reference_queue_offset_(0),
183 reference_queueNext_offset_(0),
184 reference_pendingNext_offset_(0),
185 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700186 min_free_(min_free),
187 max_free_(max_free),
188 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700189 total_wait_time_(0),
190 measure_allocation_time_(false),
191 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700192 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800193 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800194 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700195 }
196
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700197 live_bitmap_.reset(new HeapBitmap(this));
198 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700199
Ian Rogers30fab402012-01-23 15:43:46 -0800200 // Requested begin for the alloc space, to follow the mapped image and oat files
201 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800202 std::string image_file_name(original_image_file_name);
203 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700204 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700205
Brian Carlstrom5643b782012-02-05 12:32:53 -0800206 if (OS::FileExists(image_file_name.c_str())) {
207 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700208 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800209 } else {
210 // If the /system file didn't exist, we need to use one from the art-cache.
211 // If the cache file exists, try to open, but if it fails, regenerate.
212 // If it does not exist, generate.
213 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
214 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700215 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800216 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700217 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700218 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700219 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800220 }
221 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700222
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700223 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700224 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800225 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
226 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800227 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
228 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700229
230 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
231 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800232 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700233 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
234 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800235 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700236
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800237 if (oat_file_end_addr > requested_begin) {
238 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700239 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700240 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700241 }
242
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700243 // Allocate the large object space.
244 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700245 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
246 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
247
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700248 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
249 growth_limit, capacity,
250 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700251 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700252 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700253 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700254 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700255
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700256 // Spaces are sorted in order of Begin().
257 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700258 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
259 if (spaces_.back()->IsAllocSpace()) {
260 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
261 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700262
Ian Rogers30fab402012-01-23 15:43:46 -0800263 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700264 // TODO: C++0x
265 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
266 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800267 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700268 ImageSpace* image_space = space->AsImageSpace();
269 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800270 }
271 }
272
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800273 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700274 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
275 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700276
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700277 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
278 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700279
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700280 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
281 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700282
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700283 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700284 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800286 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700287 static const size_t default_mark_stack_size = 64 * KB;
288 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
289 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700290 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700291 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
292 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700293
Mathieu Chartier65db8802012-11-20 12:36:46 -0800294 // It's still too early to take a lock because there are no threads yet, but we can create locks
295 // now. We don't create it earlier to make it clear that you can't use locks during heap
296 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700297 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700298 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
299 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700300
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700301 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
302 reference_queue_lock_.reset(new Mutex("reference queue lock"));
303
Mathieu Chartier65db8802012-11-20 12:36:46 -0800304 last_gc_time_ = NanoTime();
305 last_gc_size_ = GetBytesAllocated();
306
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800307 // Create our garbage collectors.
308 for (size_t i = 0; i < 2; ++i) {
309 const bool concurrent = i != 0;
310 mark_sweep_collectors_.push_back(new MarkSweep(this, concurrent));
311 mark_sweep_collectors_.push_back(new PartialMarkSweep(this, concurrent));
312 mark_sweep_collectors_.push_back(new StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700313 }
314
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800315 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800316 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800317 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700318 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700319}
320
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700321void Heap::CreateThreadPool() {
322 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
323 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
324 // workers to complete.
325 thread_pool_.reset(new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
326}
327
328void Heap::DeleteThreadPool() {
329 thread_pool_.reset(NULL);
330}
331
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700332// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700333struct SpaceSorter {
334 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700335 return a->Begin() < b->Begin();
336 }
337};
338
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700339void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700340 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700341 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700342 DCHECK(space->GetLiveBitmap() != NULL);
343 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700344 DCHECK(space->GetMarkBitmap() != NULL);
345 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800346 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700347 if (space->IsAllocSpace()) {
348 alloc_space_ = space->AsAllocSpace();
349 }
350
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700351 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
352 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700353
354 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
355 // avoid redundant marking.
356 bool seen_zygote = false, seen_alloc = false;
357 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
358 Space* space = *it;
359 if (space->IsImageSpace()) {
360 DCHECK(!seen_zygote);
361 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700362 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700363 DCHECK(!seen_alloc);
364 seen_zygote = true;
365 } else if (space->IsAllocSpace()) {
366 seen_alloc = true;
367 }
368 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800369}
370
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700371void Heap::DumpGcPerformanceInfo() {
372 // Dump cumulative timings.
373 LOG(INFO) << "Dumping cumulative Gc timings";
374 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800375
376 // Dump cumulative loggers for each GC type.
377 // TODO: C++0x
378 uint64_t total_paused_time = 0;
379 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
380 it != mark_sweep_collectors_.end(); ++it) {
381 MarkSweep* collector = *it;
382 const CumulativeLogger& logger = collector->GetCumulativeTimings();
383 if (logger.GetTotalNs() != 0) {
384 logger.Dump();
385 const uint64_t total_ns = logger.GetTotalNs();
386 const uint64_t total_pause_ns = (*it)->GetTotalPausedTime();
387 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
388 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
389 const uint64_t freed_objects = collector->GetTotalFreedObjects();
390 LOG(INFO)
391 << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
392 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
393 << collector->GetName() << " freed: " << freed_objects
394 << " objects with total size " << PrettySize(freed_bytes) << "\n"
395 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
396 << PrettySize(freed_bytes / seconds) << "/s\n";
397 total_duration += total_ns;
398 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700399 }
400 }
401 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
402 size_t total_objects_allocated = GetTotalObjectsAllocated();
403 size_t total_bytes_allocated = GetTotalBytesAllocated();
404 if (total_duration != 0) {
405 const double total_seconds = double(total_duration / 1000) / 1000000.0;
406 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
407 LOG(INFO) << "Mean GC size throughput: "
408 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
Elliott Hughes80537bb2013-01-04 16:37:26 -0800409 LOG(INFO) << "Mean GC object throughput: "
410 << (GetTotalObjectsFreed() / total_seconds) << " objects/s";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700411 }
412 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
413 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
414 if (measure_allocation_time_) {
415 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
416 LOG(INFO) << "Mean allocation time: "
417 << PrettyDuration(allocation_time / total_objects_allocated);
418 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800419 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time);
Elliott Hughes80537bb2013-01-04 16:37:26 -0800420 LOG(INFO) << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700421}
422
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800423Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700424 if (kDumpGcPerformanceOnShutdown) {
425 DumpGcPerformanceInfo();
426 }
427
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800428 STLDeleteElements(&mark_sweep_collectors_);
429
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700430 // If we don't reset then the mark stack complains in it's destructor.
431 allocation_stack_->Reset();
432 live_stack_->Reset();
433
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800434 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800435 // We can't take the heap lock here because there might be a daemon thread suspended with the
436 // heap lock held. We know though that no non-daemon threads are executing, and we know that
437 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
438 // 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 -0700439 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700440 delete gc_complete_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700441}
442
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800443ContinuousSpace* Heap::FindSpaceFromObject(const mirror::Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700444 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700445 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
446 if ((*it)->Contains(obj)) {
447 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700448 }
449 }
450 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
451 return NULL;
452}
453
454ImageSpace* Heap::GetImageSpace() {
455 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700456 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
457 if ((*it)->IsImageSpace()) {
458 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700459 }
460 }
461 return NULL;
462}
463
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700464DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700465 return alloc_space_;
466}
467
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700468static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700469 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700470 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700471 size_t chunk_free_bytes = chunk_size - used_bytes;
472 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
473 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700474 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700475}
476
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800477mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
478 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700479 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
480 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800481 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700482
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800483 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700484 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700485 uint64_t allocation_start = 0;
486 if (measure_allocation_time_) {
487 allocation_start = NanoTime();
488 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700489
490 // We need to have a zygote space or else our newly allocated large object can end up in the
491 // Zygote resulting in it being prematurely freed.
492 // We can only do this for primive objects since large objects will not be within the card table
493 // range. This also means that we rely on SetClass not dirtying the object's card.
494 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700495 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700496 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700497 // Make sure that our large object didn't get placed anywhere within the space interval or else
498 // it breaks the immune range.
499 DCHECK(obj == NULL ||
500 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
501 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700502 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700503 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700504
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700505 // Ensure that we did not allocate into a zygote space.
506 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
507 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700508 }
509
Mathieu Chartier037813d2012-08-23 16:44:59 -0700510 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700511 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700512
513 // Record allocation after since we want to use the atomic add for the atomic fence to guard
514 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700515 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700516
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700517 if (Dbg::IsAllocTrackingEnabled()) {
518 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700519 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700520 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700521 // We already have a request pending, no reason to start more until we update
522 // concurrent_start_bytes_.
523 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700524 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800525 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700526 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700527 }
528 VerifyObject(obj);
529
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700530 if (measure_allocation_time_) {
531 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
532 }
533
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700534 return obj;
535 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800536 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700537 int64_t total_bytes_free = GetFreeMemory();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800538 uint64_t alloc_space_size = alloc_space_->GetNumBytesAllocated();
539 uint64_t large_object_size = large_object_space_->GetNumObjectsAllocated();
540 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
541 << " free bytes; allocation space size " << alloc_space_size
542 << "; large object space size " << large_object_size;
543 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
544 if (total_bytes_free >= byte_count) {
545 size_t max_contiguous_allocation = 0;
546 // TODO: C++0x auto
547 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
548 if ((*it)->IsAllocSpace()) {
549 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
550 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700551 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800552 oss << "; failed due to fragmentation (largest possible contiguous allocation "
553 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700554 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800555 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700556 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700557}
558
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800559bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700560 // Note: we deliberately don't take the lock here, and mustn't test anything that would
561 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700562 if (obj == NULL) {
563 return true;
564 }
565 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700566 return false;
567 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800568 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800569 if (spaces_[i]->Contains(obj)) {
570 return true;
571 }
572 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700573 // Note: Doing this only works for the free list version of the large object space since the
574 // multiple memory map version uses a lock to do the contains check.
575 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700576}
577
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800578bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700579 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700580 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700581}
582
Elliott Hughes3e465b12011-09-02 18:26:12 -0700583#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700584void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700585 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700586 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700587 return;
588 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700589 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700590}
591#endif
592
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700593void Heap::DumpSpaces() {
594 // TODO: C++0x auto
595 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700596 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700597 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
598 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
599 LOG(INFO) << space << " " << *space << "\n"
600 << live_bitmap << " " << *live_bitmap << "\n"
601 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700602 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700603 if (large_object_space_.get() != NULL) {
604 large_object_space_->Dump(LOG(INFO));
605 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700606}
607
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800608void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700609 if (!IsAligned<kObjectAlignment>(obj)) {
610 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700611 }
612
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700613 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
614 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700615 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700616 // Check the allocation stack / live stack.
617 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
618 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
619 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700620 if (large_object_space_->GetLiveObjects()->Test(obj)) {
621 DumpSpaces();
622 LOG(FATAL) << "Object is dead: " << obj;
623 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700624 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700625 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700626
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700627 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700628 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700629 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800630 mirror::Object::ClassOffset().Int32Value();
631 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700632 if (c == NULL) {
633 LOG(FATAL) << "Null class in object: " << obj;
634 } else if (!IsAligned<kObjectAlignment>(c)) {
635 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
636 } else if (!GetLiveBitmap()->Test(c)) {
637 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
638 }
639 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
640 // Note: we don't use the accessors here as they have internal sanity checks
641 // that we don't want to run
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800642 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
643 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
644 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
645 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700646 CHECK_EQ(c_c, c_c_c);
647 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700648}
649
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800650void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700651 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700652 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700653}
654
655void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700656 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700657 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700658}
659
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800660void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700661 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700662 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700663 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700664
665 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700666 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700667 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700668 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700669
670 // TODO: Update these atomically.
671 RuntimeStats* global_stats = Runtime::Current()->GetStats();
672 ++global_stats->allocated_objects;
673 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700674 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700675
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700676 // This is safe to do since the GC will never free objects which are neither in the allocation
677 // stack or the live bitmap.
678 while (!allocation_stack_->AtomicPushBack(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700679 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700680 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700681}
682
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700683void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700684 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
685 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700686
687 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700688 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700689 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700690 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700691
692 // TODO: Do this concurrently.
693 RuntimeStats* global_stats = Runtime::Current()->GetStats();
694 global_stats->freed_objects += freed_objects;
695 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700696 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700697}
698
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800699mirror::Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700700 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800701 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
702 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
703 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
704 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700705 return NULL;
706 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700707
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800708 if (enforce_heap_growth_rate_) {
709 if (grow) {
710 // Grow the heap by alloc_size extra bytes.
711 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
712 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
713 << " for a " << PrettySize(alloc_size) << " allocation";
714 } else {
715 return NULL;
716 }
717 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700718 }
719
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700720 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700721}
722
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800723mirror::Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700724 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
725 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700726 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700727 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700728
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800729 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700730 if (ptr != NULL) {
731 return ptr;
732 }
733
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700734 // The allocation failed. If the GC is running, block until it completes, and then retry the
735 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700736 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700737 if (last_gc != kGcTypeNone) {
738 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700739 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700740 if (ptr != NULL) {
741 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700742 }
743 }
744
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700745 // Loop through our different Gc types and try to Gc until we get enough free memory.
746 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
747 bool run_gc = false;
748 GcType gc_type = static_cast<GcType>(i);
749 switch (gc_type) {
750 case kGcTypeSticky: {
751 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700752 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
753 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700754 break;
755 }
756 case kGcTypePartial:
757 run_gc = have_zygote_space_;
758 break;
759 case kGcTypeFull:
760 run_gc = true;
761 break;
762 default:
763 break;
764 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700765
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700766 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700767 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700768 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800769 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700770 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700771
772 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700773 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700774 if (ptr != NULL) {
775 return ptr;
776 }
777 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700778 }
779
780 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700781 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700782 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700783 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700784 return ptr;
785 }
786
Elliott Hughes81ff3182012-03-23 20:35:56 -0700787 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
788 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
789 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700790
Elliott Hughes418dfe72011-10-06 18:56:27 -0700791 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700792 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
793 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700794
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700795 // We don't need a WaitForConcurrentGcToComplete here either.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700796 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700797 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700798}
799
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700800void Heap::SetTargetHeapUtilization(float target) {
801 DCHECK_GT(target, 0.0f); // asserted in Java code
802 DCHECK_LT(target, 1.0f);
803 target_utilization_ = target;
804}
805
806int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700807 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700808}
809
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700810int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700811 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700812}
813
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700814int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700815 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700816}
817
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700818size_t Heap::GetTotalBytesFreed() const {
819 return total_bytes_freed_;
820}
821
822size_t Heap::GetTotalObjectsFreed() const {
823 return total_objects_freed_;
824}
825
826size_t Heap::GetTotalObjectsAllocated() const {
827 size_t total = large_object_space_->GetTotalObjectsAllocated();
828 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
829 Space* space = *it;
830 if (space->IsAllocSpace()) {
831 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
832 }
833 }
834 return total;
835}
836
837size_t Heap::GetTotalBytesAllocated() const {
838 size_t total = large_object_space_->GetTotalBytesAllocated();
839 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
840 Space* space = *it;
841 if (space->IsAllocSpace()) {
842 total += space->AsAllocSpace()->GetTotalBytesAllocated();
843 }
844 }
845 return total;
846}
847
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700848class InstanceCounter {
849 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800850 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700851 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800852 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700853 }
854
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800855 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800856 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800857 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800858 if (use_is_assignable_from_) {
859 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
860 ++counts_[i];
861 }
862 } else {
863 if (instance_class == classes_[i]) {
864 ++counts_[i];
865 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700866 }
867 }
868 }
869
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700870 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800871 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800872 bool use_is_assignable_from_;
873 uint64_t* const counts_;
874
875 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700876};
877
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800878void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800879 uint64_t* counts) {
880 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
881 // is empty, so the live bitmap is the only place we need to look.
882 Thread* self = Thread::Current();
883 self->TransitionFromRunnableToSuspended(kNative);
884 CollectGarbage(false);
885 self->TransitionFromSuspendedToRunnable();
886
887 InstanceCounter counter(classes, use_is_assignable_from, counts);
888 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700889 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700890}
891
Elliott Hughes3b78c942013-01-15 17:35:41 -0800892class InstanceCollector {
893 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800894 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800895 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
896 : class_(c), max_count_(max_count), instances_(instances) {
897 }
898
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800899 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
900 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800901 if (instance_class == class_) {
902 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800903 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800904 }
905 }
906 }
907
908 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800909 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800910 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800911 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800912
913 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
914};
915
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800916void Heap::GetInstances(mirror::Class* c, int32_t max_count,
917 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800918 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
919 // is empty, so the live bitmap is the only place we need to look.
920 Thread* self = Thread::Current();
921 self->TransitionFromRunnableToSuspended(kNative);
922 CollectGarbage(false);
923 self->TransitionFromSuspendedToRunnable();
924
925 InstanceCollector collector(c, max_count, instances);
926 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
927 GetLiveBitmap()->Visit(collector);
928}
929
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800930class ReferringObjectsFinder {
931 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800932 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
933 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800934 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
935 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
936 }
937
938 // For bitmap Visit.
939 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
940 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800941 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800942 MarkSweep::VisitObjectReferences(o, *this);
943 }
944
945 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800946 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
947 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800948 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800949 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800950 }
951 }
952
953 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800954 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800955 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800956 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800957
958 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
959};
960
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800961void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
962 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800963 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
964 // is empty, so the live bitmap is the only place we need to look.
965 Thread* self = Thread::Current();
966 self->TransitionFromRunnableToSuspended(kNative);
967 CollectGarbage(false);
968 self->TransitionFromSuspendedToRunnable();
969
970 ReferringObjectsFinder finder(o, max_count, referring_objects);
971 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
972 GetLiveBitmap()->Visit(finder);
973}
974
Ian Rogers30fab402012-01-23 15:43:46 -0800975void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700976 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
977 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700978 Thread* self = Thread::Current();
979 WaitForConcurrentGcToComplete(self);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700980 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700981}
982
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700983void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700984 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800985 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
986 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700987 Thread* self = Thread::Current();
988 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700989
990 // Try to see if we have any Zygote spaces.
991 if (have_zygote_space_) {
992 return;
993 }
994
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700995 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
996
997 {
998 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700999 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000 FlushAllocStack();
1001 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001002
1003 // Replace the first alloc space we find with a zygote space.
1004 // TODO: C++0x auto
1005 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1006 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001007 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001008
1009 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1010 // of the remaining available heap memory.
1011 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001012 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001013
1014 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001015 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001016 AddSpace(alloc_space_);
1017 have_zygote_space_ = true;
1018 break;
1019 }
1020 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001021
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001022 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001023 // TODO: C++0x
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001024 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
1025 it != mark_sweep_collectors_.end(); ++it) {
1026 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001027 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001028}
1029
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001030void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001031 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1032 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001033 allocation_stack_->Reset();
1034}
1035
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001036size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001037 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001038}
1039
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001040void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001041 mirror::Object** limit = stack->End();
1042 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1043 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001044 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001045 if (LIKELY(bitmap->HasAddress(obj))) {
1046 bitmap->Set(obj);
1047 } else {
1048 large_objects->Set(obj);
1049 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001050 }
1051}
1052
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001053void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001054 mirror::Object** limit = stack->End();
1055 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1056 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001057 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001058 if (LIKELY(bitmap->HasAddress(obj))) {
1059 bitmap->Clear(obj);
1060 } else {
1061 large_objects->Clear(obj);
1062 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001063 }
1064}
1065
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001066GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001067 Thread* self = Thread::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001068 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001069 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001070
Ian Rogers120f1c72012-09-28 17:17:10 -07001071 if (self->IsHandlingStackOverflow()) {
1072 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1073 }
1074
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001075 // Ensure there is only one GC at a time.
1076 bool start_collect = false;
1077 while (!start_collect) {
1078 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001079 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001080 if (!is_gc_running_) {
1081 is_gc_running_ = true;
1082 start_collect = true;
1083 }
1084 }
1085 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001086 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001087 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1088 // Not doing at the moment to ensure soft references are cleared.
1089 }
1090 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001091 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001093 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1094 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1095 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1096 }
1097
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001098 // We need to do partial GCs every now and then to avoid the heap growing too much and
1099 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001100 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001101 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001102 }
Mathieu Chartier0325e622012-09-05 14:22:51 -07001103 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001104 sticky_gc_count_ = 0;
1105 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001106
Mathieu Chartier65db8802012-11-20 12:36:46 -08001107 uint64_t gc_start_time = NanoTime();
1108 uint64_t gc_start_size = GetBytesAllocated();
1109 // Approximate allocation rate in bytes / second.
Jeff Hao9bd02812013-02-08 14:29:50 -08001110 if (UNLIKELY(gc_start_time == last_gc_time_)) {
1111 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1112 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001113 uint64_t ms_delta = NsToMs(gc_start_time - last_gc_time_);
1114 if (ms_delta != 0) {
1115 allocation_rate_ = (gc_start_size - last_gc_size_) * 1000 / ms_delta;
1116 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1117 }
1118
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001119 DCHECK_LT(gc_type, kGcTypeMax);
1120 DCHECK_NE(gc_type, kGcTypeNone);
1121 MarkSweep* collector = NULL;
1122 for (Collectors::iterator it = mark_sweep_collectors_.begin();
1123 it != mark_sweep_collectors_.end(); ++it) {
1124 MarkSweep* cur_collector = *it;
1125 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1126 collector = cur_collector;
1127 break;
1128 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001129 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001130 CHECK(collector != NULL)
1131 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1132 << " and type=" << gc_type;
1133 collector->clear_soft_references_ = clear_soft_references;
1134 collector->Run();
1135 total_objects_freed_ += collector->GetFreedObjects();
1136 total_bytes_freed_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001137
Mathieu Chartier65db8802012-11-20 12:36:46 -08001138 const size_t duration = collector->GetDuration();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001139 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1140 bool was_slow = duration > kSlowGcThreshold ||
1141 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1142 for (size_t i = 0; i < pauses.size(); ++i) {
1143 if (pauses[i] > kLongGcPauseThreshold) {
1144 was_slow = true;
1145 }
1146 }
1147
1148 if (was_slow) {
1149 const size_t percent_free = GetPercentFree();
1150 const size_t current_heap_size = GetUsedMemorySize();
1151 const size_t total_memory = GetTotalMemory();
1152 std::ostringstream pause_string;
1153 for (size_t i = 0; i < pauses.size(); ++i) {
1154 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1155 << ((i != pauses.size() - 1) ? ", " : "");
1156 }
1157 LOG(INFO) << gc_cause << " " << collector->GetName()
1158 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1159 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1160 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1161 << " total " << PrettyDuration((duration / 1000) * 1000);
1162 if (VLOG_IS_ON(heap)) {
1163 collector->GetTimings().Dump();
1164 }
1165 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001166
Ian Rogers15bf2d32012-08-28 17:33:04 -07001167 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001168 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001169 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001170 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001171 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001172 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001173 }
1174 // Inform DDMS that a GC completed.
1175 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001176 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001177}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001178
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001179void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001180 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001181 // 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 -07001182 // cards.
1183 return;
1184 }
1185
1186 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001187 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001188 zygote_mod_union_table_->Update();
1189 timings.AddSplit("UpdateZygoteModUnionTable");
1190
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001191 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001192 timings.AddSplit("ZygoteMarkReferences");
1193 }
1194
1195 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1196 mod_union_table_->Update();
1197 timings.AddSplit("UpdateModUnionTable");
1198
1199 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001200 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001201 timings.AddSplit("MarkImageToAllocSpaceReferences");
1202}
1203
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001204void Heap::RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
1205 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001206 if (root == obj) {
1207 LOG(INFO) << "Object " << obj << " is a root";
1208 }
1209}
1210
1211class ScanVisitor {
1212 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001213 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001214 LOG(INFO) << "Would have rescanned object " << obj;
1215 }
1216};
1217
1218class VerifyReferenceVisitor {
1219 public:
1220 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001221 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1222 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001223 : heap_(heap),
1224 failed_(failed) {
1225 }
1226
1227 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1228 // analysis.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001229 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
1230 const MemberOffset& /* offset */, bool /* is_static */) const
1231 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001232 // Verify that the reference is live.
1233 if (ref != NULL && !IsLive(ref)) {
1234 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001235 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1236 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001237
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001238 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001239 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1240 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1241 << "Obj type " << PrettyTypeOf(obj) << "\n"
1242 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001243 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001244 void* cover_begin = card_table->AddrFromCard(card_addr);
1245 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001246 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001247 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001248 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001249 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1250
1251 // Print out how the object is live.
1252 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001253 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1254 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001255 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1256 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1257 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001258 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1259 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001260 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001261 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001262 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001263 }
1264
1265 // Attempt to see if the card table missed the reference.
1266 ScanVisitor scan_visitor;
1267 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001268 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001269 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001270
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001271 // Search to see if any of the roots reference our object.
1272 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1273 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1274 *failed_ = true;
1275 }
1276 }
1277
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001278 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001279 if (heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001280 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001281 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001282 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001283 // 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 -08001284 // If the object is not either in the live bitmap or allocation stack, so the object must be
1285 // dead.
1286 return std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001287 }
1288
1289 private:
1290 Heap* heap_;
1291 bool* failed_;
1292};
1293
1294class VerifyObjectVisitor {
1295 public:
1296 VerifyObjectVisitor(Heap* heap)
1297 : heap_(heap),
1298 failed_(false) {
1299
1300 }
1301
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001302 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001303 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001304 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1305 MarkSweep::VisitObjectReferences(obj, visitor);
1306 }
1307
1308 bool Failed() const {
1309 return failed_;
1310 }
1311
1312 private:
1313 Heap* heap_;
1314 bool failed_;
1315};
1316
1317// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001318bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001319 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001320 // Lets sort our allocation stacks so that we can efficiently binary search them.
1321 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1322 std::sort(live_stack_->Begin(), live_stack_->End());
1323 // Perform the verification.
1324 VerifyObjectVisitor visitor(this);
1325 GetLiveBitmap()->Visit(visitor);
1326 // We don't want to verify the objects in the allocation stack since they themselves may be
1327 // pointing to dead objects if they are not reachable.
1328 if (visitor.Failed()) {
1329 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001330 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001331 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001332 return true;
1333}
1334
1335class VerifyReferenceCardVisitor {
1336 public:
1337 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1338 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1339 Locks::heap_bitmap_lock_)
1340 : heap_(heap),
1341 failed_(failed) {
1342 }
1343
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001344 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1345 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001346 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1347 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001348 // Filter out class references since changing an object's class does not mark the card as dirty.
1349 // Also handles large objects, since the only reference they hold is a class reference.
1350 if (ref != NULL && !ref->IsClass()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001351 CardTable* card_table = heap_->GetCardTable();
1352 // If the object is not dirty and it is referencing something in the live stack other than
1353 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001354 if (!card_table->AddrIsInCardTable(obj)) {
1355 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1356 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001357 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001358 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1359 // kCardDirty - 1 if it didnt get touched since we aged it.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001360 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001361 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001362 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1363 LOG(ERROR) << "Object " << obj << " found in live stack";
1364 }
1365 if (heap_->GetLiveBitmap()->Test(obj)) {
1366 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1367 }
1368 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1369 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1370
1371 // Print which field of the object is dead.
1372 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001373 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001374 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001375 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1376 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001377 CHECK(fields != NULL);
1378 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001379 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001380 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1381 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1382 << PrettyField(cur);
1383 break;
1384 }
1385 }
1386 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001387 const mirror::ObjectArray<mirror::Object>* object_array =
1388 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001389 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1390 if (object_array->Get(i) == ref) {
1391 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1392 }
1393 }
1394 }
1395
1396 *failed_ = true;
1397 }
1398 }
1399 }
1400 }
1401
1402 private:
1403 Heap* heap_;
1404 bool* failed_;
1405};
1406
1407class VerifyLiveStackReferences {
1408 public:
1409 VerifyLiveStackReferences(Heap* heap)
1410 : heap_(heap),
1411 failed_(false) {
1412
1413 }
1414
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001415 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001416 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1417 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1418 MarkSweep::VisitObjectReferences(obj, visitor);
1419 }
1420
1421 bool Failed() const {
1422 return failed_;
1423 }
1424
1425 private:
1426 Heap* heap_;
1427 bool failed_;
1428};
1429
1430bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001431 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001432
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001433 // We need to sort the live stack since we binary search it.
1434 std::sort(live_stack_->Begin(), live_stack_->End());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001435 VerifyLiveStackReferences visitor(this);
1436 GetLiveBitmap()->Visit(visitor);
1437
1438 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001439 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001440 visitor(*it);
1441 }
1442
1443 if (visitor.Failed()) {
1444 DumpSpaces();
1445 return false;
1446 }
1447 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001448}
1449
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001450void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001451 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001452
1453 // Sort the live stack so that we can quickly binary search it later.
1454 if (VERIFY_OBJECT_ENABLED) {
1455 std::sort(live_stack_->Begin(), live_stack_->End());
1456 }
1457}
1458
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001459void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001460 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1461 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1462 ContinuousSpace* space = *it;
1463 if (space->IsImageSpace()) {
1464 mod_union_table_->ClearCards(*it);
1465 timings.AddSplit("ModUnionClearCards");
1466 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1467 zygote_mod_union_table_->ClearCards(space);
1468 timings.AddSplit("ZygoteModUnionClearCards");
1469 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001470 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1471 // were dirty before the GC started.
1472 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1473 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001474 }
1475 }
1476}
1477
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001478void Heap::PreGcVerification(GarbageCollector* gc) {
1479 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1480 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001481
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001482 if (verify_pre_gc_heap_) {
1483 thread_list->SuspendAll();
1484 {
1485 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1486 if (!VerifyHeapReferences()) {
1487 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1488 }
1489 }
1490 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001491 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001492
1493 // Check that all objects which reference things in the live stack are on dirty cards.
1494 if (verify_missing_card_marks_) {
1495 thread_list->SuspendAll();
1496 {
1497 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1498 SwapStacks();
1499 // Sort the live stack so that we can quickly binary search it later.
1500 if (!VerifyMissingCardMarks()) {
1501 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1502 }
1503 SwapStacks();
1504 }
1505 thread_list->ResumeAll();
1506 }
1507
1508 if (verify_mod_union_table_) {
1509 thread_list->SuspendAll();
1510 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1511 zygote_mod_union_table_->Update();
1512 zygote_mod_union_table_->Verify();
1513 mod_union_table_->Update();
1514 mod_union_table_->Verify();
1515 thread_list->ResumeAll();
1516 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001517}
1518
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001519void Heap::PreSweepingGcVerification(GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001520 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001521 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001522
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001523 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1524 // reachable objects.
1525 if (verify_post_gc_heap_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001526 thread_list->SuspendAll();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001527 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1528 // Swapping bound bitmaps does nothing.
1529 live_bitmap_.swap(mark_bitmap_);
1530 if (!VerifyHeapReferences()) {
1531 LOG(FATAL) << "Post " << gc->GetName() << "Gc verification failed";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001532 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001533 live_bitmap_.swap(mark_bitmap_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001534 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001535 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001536}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001537
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001538void Heap::PostGcVerification(GarbageCollector* gc) {
1539 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001541 if (verify_system_weaks_) {
1542 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1543 MarkSweep* mark_sweep = down_cast<MarkSweep*>(gc);
1544 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001545 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001546}
1547
Ian Rogers81d425b2012-09-27 16:03:43 -07001548GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001549 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001550 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001551 bool do_wait;
1552 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001553 {
1554 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001555 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001556 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001557 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001558 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001559 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001560 // We must wait, change thread state then sleep on gc_complete_cond_;
1561 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1562 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001563 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001565 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001566 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001567 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001568 wait_time = NanoTime() - wait_start;;
1569 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001570 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001571 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001572 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1573 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001574 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001575 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001576 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001577}
1578
Elliott Hughesc967f782012-04-16 10:23:15 -07001579void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001580 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1581 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001582 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001583}
1584
1585size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001586 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001587}
1588
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001589void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001590 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001591 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001592 << PrettySize(GetMaxMemory());
1593 max_allowed_footprint = GetMaxMemory();
1594 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001595 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001596}
1597
Mathieu Chartier65db8802012-11-20 12:36:46 -08001598void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001599 // We know what our utilization is at this moment.
1600 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001601 const size_t bytes_allocated = GetBytesAllocated();
1602 last_gc_size_ = bytes_allocated;
1603 last_gc_time_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001604
Mathieu Chartier65db8802012-11-20 12:36:46 -08001605 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1606 if (target_size > bytes_allocated + max_free_) {
1607 target_size = bytes_allocated + max_free_;
1608 } else if (target_size < bytes_allocated + min_free_) {
1609 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001610 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001611
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001612 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001613
1614 // Calculate when to perform the next ConcurrentGC if we have enough free memory.
1615 if (concurrent_gc_ && GetFreeMemory() >= concurrent_min_free_) {
1616 // Calculate the estimated GC duration.
1617 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1618 // Estimate how many remaining bytes we will have when we need to start the next GC.
1619 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1620 if (remaining_bytes < max_allowed_footprint_) {
1621 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1622 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1623 // right away.
1624 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1625 } else {
1626 // The estimated rate is so high that we should request another GC straight away.
1627 concurrent_start_bytes_ = bytes_allocated;
1628 }
1629 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1630 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1631 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001632}
1633
jeffhaoc1160702011-10-27 15:48:45 -07001634void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001635 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001636 alloc_space_->ClearGrowthLimit();
1637}
1638
Elliott Hughesadb460d2011-10-05 17:02:34 -07001639void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001640 MemberOffset reference_queue_offset,
1641 MemberOffset reference_queueNext_offset,
1642 MemberOffset reference_pendingNext_offset,
1643 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001644 reference_referent_offset_ = reference_referent_offset;
1645 reference_queue_offset_ = reference_queue_offset;
1646 reference_queueNext_offset_ = reference_queueNext_offset;
1647 reference_pendingNext_offset_ = reference_pendingNext_offset;
1648 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1649 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1650 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1651 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1652 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1653 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1654}
1655
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001656mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001657 DCHECK(reference != NULL);
1658 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001659 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001660}
1661
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001662void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001663 DCHECK(reference != NULL);
1664 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1665 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1666}
1667
1668// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001669bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001670 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001671 const mirror::Object* queue =
1672 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1673 const mirror::Object* queue_next =
1674 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001675 return (queue != NULL) && (queue_next == NULL);
1676}
1677
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001678void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001679 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001680 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1681 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001682 EnqueuePendingReference(ref, cleared_reference_list);
1683}
1684
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001685void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001686 DCHECK(ref != NULL);
1687 DCHECK(list != NULL);
1688
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001689 // TODO: Remove this lock, use atomic stacks for storing references.
1690 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001691 if (*list == NULL) {
1692 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1693 *list = ref;
1694 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001695 mirror::Object* head =
1696 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001697 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1698 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1699 }
1700}
1701
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001702mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001703 DCHECK(list != NULL);
1704 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001705 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1706 false);
1707 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001708
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001709 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1710 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001711 if (*list == head) {
1712 ref = *list;
1713 *list = NULL;
1714 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001715 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1716 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001717 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1718 ref = head;
1719 }
1720 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1721 return ref;
1722}
1723
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001724void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001725 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001726 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001727 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001728 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1729 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001730}
1731
1732size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001733 return num_bytes_allocated_;
1734}
1735
1736size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001737 size_t total = 0;
1738 // TODO: C++0x
1739 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1740 Space* space = *it;
1741 if (space->IsAllocSpace()) {
1742 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1743 }
1744 }
1745 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001746}
1747
1748size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001749 return concurrent_start_size_;
1750}
1751
1752size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001753 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001754}
1755
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001756void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001757 DCHECK(cleared != NULL);
1758 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001759 // When a runtime isn't started there are no reference queues to care about so ignore.
1760 if (LIKELY(Runtime::Current()->IsStarted())) {
1761 ScopedObjectAccess soa(Thread::Current());
1762 JValue args[1];
1763 args[0].SetL(*cleared);
1764 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1765 args, NULL);
1766 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001767 *cleared = NULL;
1768 }
1769}
1770
Ian Rogers1f539342012-10-03 21:09:42 -07001771void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001772 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001773 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001774 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001775 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001776 !runtime->IsConcurrentGcEnabled()) {
1777 return;
1778 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001779 {
1780 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1781 if (runtime->IsShuttingDown()) {
1782 return;
1783 }
1784 }
1785 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001786 return;
1787 }
1788
Ian Rogers120f1c72012-09-28 17:17:10 -07001789 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001790 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1791 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001792 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1793 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001794 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001795}
1796
Ian Rogers81d425b2012-09-27 16:03:43 -07001797void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001798 {
1799 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001800 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001801 return;
1802 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001803 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001804
Mathieu Chartier65db8802012-11-20 12:36:46 -08001805 // Wait for any GCs currently running to finish.
Ian Rogers81d425b2012-09-27 16:03:43 -07001806 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001807 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001808 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001809 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001810 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001811 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001812 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001813}
1814
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001815void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001816 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1817 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1818 // a space it will hold its lock and can become a cause of jank.
1819 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1820 // forking.
1821
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001822 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1823 // because that only marks object heads, so a large array looks like lots of empty space. We
1824 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1825 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1826 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1827 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001828 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001829 float utilization =
1830 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1831 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1832 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1833 // heap trim occurred in the last two seconds.
1834 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001835 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001836
1837 Thread* self = Thread::Current();
1838 {
1839 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1840 Runtime* runtime = Runtime::Current();
1841 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1842 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1843 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1844 // as we don't hold the lock while requesting the trim).
1845 return;
1846 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001847 }
Ian Rogers48931882013-01-22 14:35:16 -08001848
1849 SchedPolicy policy;
1850 get_sched_policy(self->GetTid(), &policy);
1851 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1852 // Don't trim the heap if we are a foreground or audio app.
1853 return;
1854 }
1855
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001856 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001857 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001858 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1859 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001860 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1861 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001862 CHECK(!env->ExceptionCheck());
1863}
1864
Ian Rogers48931882013-01-22 14:35:16 -08001865size_t Heap::Trim() {
1866 // Handle a requested heap trim on a thread outside of the main GC thread.
1867 return alloc_space_->Trim();
1868}
1869
Carl Shapiro69759ea2011-07-21 18:13:35 -07001870} // namespace art