blob: 64df6b8807f985129e224ff1c3748efa5bc4e9df [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 "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070055#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070056
57namespace art {
58
Mathieu Chartier2b82db42012-11-14 17:29:05 -080059static const uint64_t kSlowGcThreshold = MsToNs(100);
60static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080061static const bool kDumpGcPerformanceOnShutdown = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070062const double Heap::kDefaultTargetUtilization = 0.5;
63
Elliott Hughesae80b492012-04-24 10:43:17 -070064static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080065 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080066 std::vector<std::string> boot_class_path;
67 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070068 if (boot_class_path.empty()) {
69 LOG(FATAL) << "Failed to generate image because no boot class path specified";
70 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080071
72 std::vector<char*> arg_vector;
73
74 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070075 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080076 const char* dex2oat = dex2oat_string.c_str();
77 arg_vector.push_back(strdup(dex2oat));
78
79 std::string image_option_string("--image=");
80 image_option_string += image_file_name;
81 const char* image_option = image_option_string.c_str();
82 arg_vector.push_back(strdup(image_option));
83
84 arg_vector.push_back(strdup("--runtime-arg"));
85 arg_vector.push_back(strdup("-Xms64m"));
86
87 arg_vector.push_back(strdup("--runtime-arg"));
88 arg_vector.push_back(strdup("-Xmx64m"));
89
90 for (size_t i = 0; i < boot_class_path.size(); i++) {
91 std::string dex_file_option_string("--dex-file=");
92 dex_file_option_string += boot_class_path[i];
93 const char* dex_file_option = dex_file_option_string.c_str();
94 arg_vector.push_back(strdup(dex_file_option));
95 }
96
97 std::string oat_file_option_string("--oat-file=");
98 oat_file_option_string += image_file_name;
99 oat_file_option_string.erase(oat_file_option_string.size() - 3);
100 oat_file_option_string += "oat";
101 const char* oat_file_option = oat_file_option_string.c_str();
102 arg_vector.push_back(strdup(oat_file_option));
103
jeffhao8161c032012-10-31 15:50:00 -0700104 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
105 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800106
Brian Carlstrom265091e2013-01-30 14:08:26 -0800107 if (!kIsTargetBuild) {
108 arg_vector.push_back(strdup("--host"));
109 }
110
Elliott Hughes48436bb2012-02-07 15:23:28 -0800111 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800112 LOG(INFO) << command_line;
113
Elliott Hughes48436bb2012-02-07 15:23:28 -0800114 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800115 char** argv = &arg_vector[0];
116
117 // fork and exec dex2oat
118 pid_t pid = fork();
119 if (pid == 0) {
120 // no allocation allowed between fork and exec
121
122 // change process groups, so we don't get reaped by ProcessManager
123 setpgid(0, 0);
124
125 execv(dex2oat, argv);
126
127 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
128 return false;
129 } else {
130 STLDeleteElements(&arg_vector);
131
132 // wait for dex2oat to finish
133 int status;
134 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
135 if (got_pid != pid) {
136 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
137 return false;
138 }
139 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
140 LOG(ERROR) << dex2oat << " failed: " << command_line;
141 return false;
142 }
143 }
144 return true;
145}
146
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700147void Heap::UnReserveOatFileAddressRange() {
148 oat_file_map_.reset(NULL);
149}
150
Mathieu Chartier0051be62012-10-12 17:47:11 -0700151Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
152 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700153 const std::string& original_image_file_name, bool concurrent_gc)
154 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800155 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700156 concurrent_gc_(concurrent_gc),
157 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800158 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700159 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700160 enforce_heap_growth_rate_(false),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800161 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700162 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700163 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700164 concurrent_start_size_(128 * KB),
165 concurrent_min_free_(256 * KB),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800166 concurrent_start_bytes_(concurrent_gc ? initial_size - concurrent_start_size_ :
167 std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700168 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700169 total_bytes_freed_(0),
170 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700171 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800172 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700173 verify_missing_card_marks_(false),
174 verify_system_weaks_(false),
175 verify_pre_gc_heap_(false),
176 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700177 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700178 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700179 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700180 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700181 last_trim_time_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800182 allocation_rate_(0),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700183 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800184 reference_referent_offset_(0),
185 reference_queue_offset_(0),
186 reference_queueNext_offset_(0),
187 reference_pendingNext_offset_(0),
188 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700189 min_free_(min_free),
190 max_free_(max_free),
191 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700192 total_wait_time_(0),
193 measure_allocation_time_(false),
194 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700195 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800196 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800197 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700198 }
199
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700200 live_bitmap_.reset(new HeapBitmap(this));
201 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700202
Ian Rogers30fab402012-01-23 15:43:46 -0800203 // Requested begin for the alloc space, to follow the mapped image and oat files
204 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800205 std::string image_file_name(original_image_file_name);
206 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700207 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700208
Brian Carlstrom5643b782012-02-05 12:32:53 -0800209 if (OS::FileExists(image_file_name.c_str())) {
210 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700211 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800212 } else {
213 // If the /system file didn't exist, we need to use one from the art-cache.
214 // If the cache file exists, try to open, but if it fails, regenerate.
215 // If it does not exist, generate.
216 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
217 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700218 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800219 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700220 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700221 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700222 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800223 }
224 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700225
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700226 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700227 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800228 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
229 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800230 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
231 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700232
233 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
234 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800235 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700236 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
237 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800238 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700239
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800240 if (oat_file_end_addr > requested_begin) {
241 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700242 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700243 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700244 }
245
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700246 // Allocate the large object space.
247 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700248 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
249 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
250
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700251 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
252 growth_limit, capacity,
253 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700254 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700255 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700256 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700257 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700258
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700259 // Spaces are sorted in order of Begin().
260 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700261 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
262 if (spaces_.back()->IsAllocSpace()) {
263 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
264 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700265
Ian Rogers30fab402012-01-23 15:43:46 -0800266 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700267 // TODO: C++0x
268 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
269 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800270 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700271 ImageSpace* image_space = space->AsImageSpace();
272 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800273 }
274 }
275
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800276 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700277 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
278 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700279
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700280 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
281 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700282
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700283 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
284 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700285
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700286 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700287 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800289 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700290 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogersa40307e2013-02-22 11:32:44 -0800291 mark_stack_.reset(ObjectStack::Create("mark stack", default_mark_stack_size));
292 allocation_stack_.reset(ObjectStack::Create("allocation stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700293 max_allocation_stack_size_));
Ian Rogersa40307e2013-02-22 11:32:44 -0800294 live_stack_.reset(ObjectStack::Create("live stack",
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700295 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700296
Mathieu Chartier65db8802012-11-20 12:36:46 -0800297 // It's still too early to take a lock because there are no threads yet, but we can create locks
298 // now. We don't create it earlier to make it clear that you can't use locks during heap
299 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700300 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700301 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
302 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700303
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700304 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
305 reference_queue_lock_.reset(new Mutex("reference queue lock"));
306
Mathieu Chartier65db8802012-11-20 12:36:46 -0800307 last_gc_time_ = NanoTime();
308 last_gc_size_ = GetBytesAllocated();
309
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800310 // Create our garbage collectors.
311 for (size_t i = 0; i < 2; ++i) {
312 const bool concurrent = i != 0;
313 mark_sweep_collectors_.push_back(new MarkSweep(this, concurrent));
314 mark_sweep_collectors_.push_back(new PartialMarkSweep(this, concurrent));
315 mark_sweep_collectors_.push_back(new StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700316 }
317
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800318 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800319 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800320 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700321 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700322}
323
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700324void Heap::CreateThreadPool() {
325 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
326 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
327 // workers to complete.
328 thread_pool_.reset(new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
329}
330
331void Heap::DeleteThreadPool() {
332 thread_pool_.reset(NULL);
333}
334
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700335// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700336struct SpaceSorter {
337 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700338 return a->Begin() < b->Begin();
339 }
340};
341
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700342void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700343 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700344 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700345 DCHECK(space->GetLiveBitmap() != NULL);
346 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700347 DCHECK(space->GetMarkBitmap() != NULL);
348 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800349 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700350 if (space->IsAllocSpace()) {
351 alloc_space_ = space->AsAllocSpace();
352 }
353
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700354 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
355 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700356
357 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
358 // avoid redundant marking.
359 bool seen_zygote = false, seen_alloc = false;
360 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
361 Space* space = *it;
362 if (space->IsImageSpace()) {
363 DCHECK(!seen_zygote);
364 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700365 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700366 DCHECK(!seen_alloc);
367 seen_zygote = true;
368 } else if (space->IsAllocSpace()) {
369 seen_alloc = true;
370 }
371 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800372}
373
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700374void Heap::DumpGcPerformanceInfo() {
375 // Dump cumulative timings.
376 LOG(INFO) << "Dumping cumulative Gc timings";
377 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800378
379 // Dump cumulative loggers for each GC type.
380 // TODO: C++0x
381 uint64_t total_paused_time = 0;
382 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800383 it != mark_sweep_collectors_.end(); ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800384 MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800385 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800386 if (logger.GetTotalNs() != 0) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800387 LOG(INFO) << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800388 const uint64_t total_ns = logger.GetTotalNs();
389 const uint64_t total_pause_ns = (*it)->GetTotalPausedTime();
390 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
391 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
392 const uint64_t freed_objects = collector->GetTotalFreedObjects();
393 LOG(INFO)
394 << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
395 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
396 << collector->GetName() << " freed: " << freed_objects
397 << " objects with total size " << PrettySize(freed_bytes) << "\n"
398 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
399 << PrettySize(freed_bytes / seconds) << "/s\n";
400 total_duration += total_ns;
401 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700402 }
403 }
404 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
405 size_t total_objects_allocated = GetTotalObjectsAllocated();
406 size_t total_bytes_allocated = GetTotalBytesAllocated();
407 if (total_duration != 0) {
408 const double total_seconds = double(total_duration / 1000) / 1000000.0;
409 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
410 LOG(INFO) << "Mean GC size throughput: "
411 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
Elliott Hughes80537bb2013-01-04 16:37:26 -0800412 LOG(INFO) << "Mean GC object throughput: "
413 << (GetTotalObjectsFreed() / total_seconds) << " objects/s";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700414 }
415 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
416 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
417 if (measure_allocation_time_) {
418 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
419 LOG(INFO) << "Mean allocation time: "
420 << PrettyDuration(allocation_time / total_objects_allocated);
421 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800422 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time);
Elliott Hughes80537bb2013-01-04 16:37:26 -0800423 LOG(INFO) << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700424}
425
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800426Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700427 if (kDumpGcPerformanceOnShutdown) {
428 DumpGcPerformanceInfo();
429 }
430
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800431 STLDeleteElements(&mark_sweep_collectors_);
432
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700433 // If we don't reset then the mark stack complains in it's destructor.
434 allocation_stack_->Reset();
435 live_stack_->Reset();
436
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800437 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800438 // We can't take the heap lock here because there might be a daemon thread suspended with the
439 // heap lock held. We know though that no non-daemon threads are executing, and we know that
440 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
441 // 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 -0700442 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700443 delete gc_complete_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700444}
445
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800446ContinuousSpace* Heap::FindSpaceFromObject(const mirror::Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700447 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700448 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
449 if ((*it)->Contains(obj)) {
450 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700451 }
452 }
453 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
454 return NULL;
455}
456
457ImageSpace* Heap::GetImageSpace() {
458 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700459 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
460 if ((*it)->IsImageSpace()) {
461 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700462 }
463 }
464 return NULL;
465}
466
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700467DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700468 return alloc_space_;
469}
470
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700471static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700472 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700473 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700474 size_t chunk_free_bytes = chunk_size - used_bytes;
475 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
476 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700477 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700478}
479
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800480mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
481 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
483 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800484 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700485
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800486 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700487 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700488 uint64_t allocation_start = 0;
489 if (measure_allocation_time_) {
490 allocation_start = NanoTime();
491 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700492
493 // We need to have a zygote space or else our newly allocated large object can end up in the
494 // Zygote resulting in it being prematurely freed.
495 // We can only do this for primive objects since large objects will not be within the card table
496 // range. This also means that we rely on SetClass not dirtying the object's card.
497 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700498 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700499 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700500 // Make sure that our large object didn't get placed anywhere within the space interval or else
501 // it breaks the immune range.
502 DCHECK(obj == NULL ||
503 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
504 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700505 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700506 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700507
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700508 // Ensure that we did not allocate into a zygote space.
509 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
510 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700511 }
512
Mathieu Chartier037813d2012-08-23 16:44:59 -0700513 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700514 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700515
516 // Record allocation after since we want to use the atomic add for the atomic fence to guard
517 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700518 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700519
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700520 if (Dbg::IsAllocTrackingEnabled()) {
521 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700522 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700523 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700524 // We already have a request pending, no reason to start more until we update
525 // concurrent_start_bytes_.
526 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700527 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800528 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700529 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700530 }
531 VerifyObject(obj);
532
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700533 if (measure_allocation_time_) {
534 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
535 }
536
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700537 return obj;
538 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800539 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700540 int64_t total_bytes_free = GetFreeMemory();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800541 uint64_t alloc_space_size = alloc_space_->GetNumBytesAllocated();
542 uint64_t large_object_size = large_object_space_->GetNumObjectsAllocated();
543 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
544 << " free bytes; allocation space size " << alloc_space_size
545 << "; large object space size " << large_object_size;
546 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
547 if (total_bytes_free >= byte_count) {
548 size_t max_contiguous_allocation = 0;
549 // TODO: C++0x auto
550 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
551 if ((*it)->IsAllocSpace()) {
552 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
553 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700554 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800555 oss << "; failed due to fragmentation (largest possible contiguous allocation "
556 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700557 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800558 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700559 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700560}
561
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800562bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700563 // Note: we deliberately don't take the lock here, and mustn't test anything that would
564 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700565 if (obj == NULL) {
566 return true;
567 }
568 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700569 return false;
570 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800571 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800572 if (spaces_[i]->Contains(obj)) {
573 return true;
574 }
575 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700576 // Note: Doing this only works for the free list version of the large object space since the
577 // multiple memory map version uses a lock to do the contains check.
578 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700579}
580
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800581bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700582 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700583 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700584}
585
Elliott Hughes3e465b12011-09-02 18:26:12 -0700586#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700587void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700588 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700589 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700590 return;
591 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700592 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700593}
594#endif
595
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700596void Heap::DumpSpaces() {
597 // TODO: C++0x auto
598 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700599 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700600 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
601 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
602 LOG(INFO) << space << " " << *space << "\n"
603 << live_bitmap << " " << *live_bitmap << "\n"
604 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700605 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700606 if (large_object_space_.get() != NULL) {
607 large_object_space_->Dump(LOG(INFO));
608 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700609}
610
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800611void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700612 if (!IsAligned<kObjectAlignment>(obj)) {
613 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700614 }
615
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700616 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
617 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700618 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700619 // Check the allocation stack / live stack.
620 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
621 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
622 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700623 if (large_object_space_->GetLiveObjects()->Test(obj)) {
624 DumpSpaces();
625 LOG(FATAL) << "Object is dead: " << obj;
626 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700627 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700628 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700629
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700630 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700631 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700632 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800633 mirror::Object::ClassOffset().Int32Value();
634 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700635 if (c == NULL) {
636 LOG(FATAL) << "Null class in object: " << obj;
637 } else if (!IsAligned<kObjectAlignment>(c)) {
638 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
639 } else if (!GetLiveBitmap()->Test(c)) {
640 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
641 }
642 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
643 // Note: we don't use the accessors here as they have internal sanity checks
644 // that we don't want to run
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800645 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
646 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
647 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
648 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700649 CHECK_EQ(c_c, c_c_c);
650 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700651}
652
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800653void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700654 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700655 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656}
657
658void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700659 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700660 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700661}
662
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800663void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700664 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700665 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700666 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700667
668 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700669 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700670 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700671 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700672
673 // TODO: Update these atomically.
674 RuntimeStats* global_stats = Runtime::Current()->GetStats();
675 ++global_stats->allocated_objects;
676 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700677 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700678
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700679 // This is safe to do since the GC will never free objects which are neither in the allocation
680 // stack or the live bitmap.
681 while (!allocation_stack_->AtomicPushBack(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700682 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700683 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700684}
685
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700686void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700687 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
688 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700689
690 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700691 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700692 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700693 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700694
695 // TODO: Do this concurrently.
696 RuntimeStats* global_stats = Runtime::Current()->GetStats();
697 global_stats->freed_objects += freed_objects;
698 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700699 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700700}
701
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800702mirror::Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700703 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800704 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
705 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
706 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
707 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700708 return NULL;
709 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700710
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800711 if (enforce_heap_growth_rate_) {
712 if (grow) {
713 // Grow the heap by alloc_size extra bytes.
714 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
715 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
716 << " for a " << PrettySize(alloc_size) << " allocation";
717 } else {
718 return NULL;
719 }
720 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700721 }
722
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700723 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700724}
725
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800726mirror::Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700727 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
728 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700729 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700730 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700731
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800732 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700733 if (ptr != NULL) {
734 return ptr;
735 }
736
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700737 // The allocation failed. If the GC is running, block until it completes, and then retry the
738 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700739 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700740 if (last_gc != kGcTypeNone) {
741 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700742 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700743 if (ptr != NULL) {
744 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700745 }
746 }
747
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700748 // Loop through our different Gc types and try to Gc until we get enough free memory.
749 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
750 bool run_gc = false;
751 GcType gc_type = static_cast<GcType>(i);
752 switch (gc_type) {
753 case kGcTypeSticky: {
754 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700755 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
756 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700757 break;
758 }
759 case kGcTypePartial:
760 run_gc = have_zygote_space_;
761 break;
762 case kGcTypeFull:
763 run_gc = true;
764 break;
765 default:
766 break;
767 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700768
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700769 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700770 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700771 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800772 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700773 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700774
775 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700776 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700777 if (ptr != NULL) {
778 return ptr;
779 }
780 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700781 }
782
783 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700784 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700785 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700786 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700787 return ptr;
788 }
789
Elliott Hughes81ff3182012-03-23 20:35:56 -0700790 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
791 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
792 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700793
Elliott Hughes418dfe72011-10-06 18:56:27 -0700794 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700795 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
796 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700797
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700798 // We don't need a WaitForConcurrentGcToComplete here either.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700799 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700800 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700801}
802
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700803void Heap::SetTargetHeapUtilization(float target) {
804 DCHECK_GT(target, 0.0f); // asserted in Java code
805 DCHECK_LT(target, 1.0f);
806 target_utilization_ = target;
807}
808
809int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700810 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700811}
812
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700813int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700814 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700815}
816
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700817int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700818 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700819}
820
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700821size_t Heap::GetTotalBytesFreed() const {
822 return total_bytes_freed_;
823}
824
825size_t Heap::GetTotalObjectsFreed() const {
826 return total_objects_freed_;
827}
828
829size_t Heap::GetTotalObjectsAllocated() const {
830 size_t total = large_object_space_->GetTotalObjectsAllocated();
831 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
832 Space* space = *it;
833 if (space->IsAllocSpace()) {
834 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
835 }
836 }
837 return total;
838}
839
840size_t Heap::GetTotalBytesAllocated() const {
841 size_t total = large_object_space_->GetTotalBytesAllocated();
842 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
843 Space* space = *it;
844 if (space->IsAllocSpace()) {
845 total += space->AsAllocSpace()->GetTotalBytesAllocated();
846 }
847 }
848 return total;
849}
850
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700851class InstanceCounter {
852 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800853 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700854 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800855 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700856 }
857
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800858 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800859 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800860 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800861 if (use_is_assignable_from_) {
862 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
863 ++counts_[i];
864 }
865 } else {
866 if (instance_class == classes_[i]) {
867 ++counts_[i];
868 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700869 }
870 }
871 }
872
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700873 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800874 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800875 bool use_is_assignable_from_;
876 uint64_t* const counts_;
877
878 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700879};
880
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800881void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800882 uint64_t* counts) {
883 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
884 // is empty, so the live bitmap is the only place we need to look.
885 Thread* self = Thread::Current();
886 self->TransitionFromRunnableToSuspended(kNative);
887 CollectGarbage(false);
888 self->TransitionFromSuspendedToRunnable();
889
890 InstanceCounter counter(classes, use_is_assignable_from, counts);
891 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700892 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700893}
894
Elliott Hughes3b78c942013-01-15 17:35:41 -0800895class InstanceCollector {
896 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800897 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800898 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
899 : class_(c), max_count_(max_count), instances_(instances) {
900 }
901
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800902 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
903 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800904 if (instance_class == class_) {
905 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800906 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800907 }
908 }
909 }
910
911 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800912 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800913 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800914 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800915
916 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
917};
918
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800919void Heap::GetInstances(mirror::Class* c, int32_t max_count,
920 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800921 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
922 // is empty, so the live bitmap is the only place we need to look.
923 Thread* self = Thread::Current();
924 self->TransitionFromRunnableToSuspended(kNative);
925 CollectGarbage(false);
926 self->TransitionFromSuspendedToRunnable();
927
928 InstanceCollector collector(c, max_count, instances);
929 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
930 GetLiveBitmap()->Visit(collector);
931}
932
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800933class ReferringObjectsFinder {
934 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800935 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
936 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800937 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
938 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
939 }
940
941 // For bitmap Visit.
942 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
943 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800944 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800945 MarkSweep::VisitObjectReferences(o, *this);
946 }
947
948 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800949 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
950 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800951 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800952 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800953 }
954 }
955
956 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800957 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800958 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800959 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800960
961 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
962};
963
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800964void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
965 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800966 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
967 // is empty, so the live bitmap is the only place we need to look.
968 Thread* self = Thread::Current();
969 self->TransitionFromRunnableToSuspended(kNative);
970 CollectGarbage(false);
971 self->TransitionFromSuspendedToRunnable();
972
973 ReferringObjectsFinder finder(o, max_count, referring_objects);
974 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
975 GetLiveBitmap()->Visit(finder);
976}
977
Ian Rogers30fab402012-01-23 15:43:46 -0800978void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700979 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
980 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700981 Thread* self = Thread::Current();
982 WaitForConcurrentGcToComplete(self);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700983 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700984}
985
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700986void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700987 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800988 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
989 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700990 Thread* self = Thread::Current();
991 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700992
993 // Try to see if we have any Zygote spaces.
994 if (have_zygote_space_) {
995 return;
996 }
997
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700998 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
999
1000 {
1001 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001002 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001003 FlushAllocStack();
1004 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001005
1006 // Replace the first alloc space we find with a zygote space.
1007 // TODO: C++0x auto
1008 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1009 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001010 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001011
1012 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1013 // of the remaining available heap memory.
1014 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001015 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001016
1017 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001018 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001019 AddSpace(alloc_space_);
1020 have_zygote_space_ = true;
1021 break;
1022 }
1023 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001024
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001025 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001026 // TODO: C++0x
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001027 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
1028 it != mark_sweep_collectors_.end(); ++it) {
1029 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001030 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001031}
1032
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001033void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001034 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1035 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001036 allocation_stack_->Reset();
1037}
1038
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001039size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001040 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001041}
1042
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001043void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001044 mirror::Object** limit = stack->End();
1045 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1046 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001047 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001048 if (LIKELY(bitmap->HasAddress(obj))) {
1049 bitmap->Set(obj);
1050 } else {
1051 large_objects->Set(obj);
1052 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001053 }
1054}
1055
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001056void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001057 mirror::Object** limit = stack->End();
1058 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1059 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001060 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001061 if (LIKELY(bitmap->HasAddress(obj))) {
1062 bitmap->Clear(obj);
1063 } else {
1064 large_objects->Clear(obj);
1065 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001066 }
1067}
1068
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001069GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001070 Thread* self = Thread::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001071 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001072 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001073
Ian Rogers120f1c72012-09-28 17:17:10 -07001074 if (self->IsHandlingStackOverflow()) {
1075 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1076 }
1077
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001078 // Ensure there is only one GC at a time.
1079 bool start_collect = false;
1080 while (!start_collect) {
1081 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001082 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001083 if (!is_gc_running_) {
1084 is_gc_running_ = true;
1085 start_collect = true;
1086 }
1087 }
1088 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001089 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001090 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1091 // Not doing at the moment to ensure soft references are cleared.
1092 }
1093 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001094 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001095
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001096 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1097 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1098 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1099 }
1100
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001101 // We need to do partial GCs every now and then to avoid the heap growing too much and
1102 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001103 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001104 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001105 }
Mathieu Chartier0325e622012-09-05 14:22:51 -07001106 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001107 sticky_gc_count_ = 0;
1108 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001109
Mathieu Chartier65db8802012-11-20 12:36:46 -08001110 uint64_t gc_start_time = NanoTime();
1111 uint64_t gc_start_size = GetBytesAllocated();
1112 // Approximate allocation rate in bytes / second.
Jeff Hao9bd02812013-02-08 14:29:50 -08001113 if (UNLIKELY(gc_start_time == last_gc_time_)) {
1114 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1115 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001116 uint64_t ms_delta = NsToMs(gc_start_time - last_gc_time_);
1117 if (ms_delta != 0) {
1118 allocation_rate_ = (gc_start_size - last_gc_size_) * 1000 / ms_delta;
1119 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1120 }
1121
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001122 DCHECK_LT(gc_type, kGcTypeMax);
1123 DCHECK_NE(gc_type, kGcTypeNone);
1124 MarkSweep* collector = NULL;
1125 for (Collectors::iterator it = mark_sweep_collectors_.begin();
1126 it != mark_sweep_collectors_.end(); ++it) {
1127 MarkSweep* cur_collector = *it;
1128 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1129 collector = cur_collector;
1130 break;
1131 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001132 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001133 CHECK(collector != NULL)
1134 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1135 << " and type=" << gc_type;
1136 collector->clear_soft_references_ = clear_soft_references;
1137 collector->Run();
1138 total_objects_freed_ += collector->GetFreedObjects();
1139 total_bytes_freed_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001140
Mathieu Chartier65db8802012-11-20 12:36:46 -08001141 const size_t duration = collector->GetDuration();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001142 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1143 bool was_slow = duration > kSlowGcThreshold ||
1144 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1145 for (size_t i = 0; i < pauses.size(); ++i) {
1146 if (pauses[i] > kLongGcPauseThreshold) {
1147 was_slow = true;
1148 }
1149 }
1150
1151 if (was_slow) {
1152 const size_t percent_free = GetPercentFree();
1153 const size_t current_heap_size = GetUsedMemorySize();
1154 const size_t total_memory = GetTotalMemory();
1155 std::ostringstream pause_string;
1156 for (size_t i = 0; i < pauses.size(); ++i) {
1157 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1158 << ((i != pauses.size() - 1) ? ", " : "");
1159 }
1160 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001161 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1162 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1163 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1164 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001165 if (VLOG_IS_ON(heap)) {
Sameer Abu Asala8439542013-02-14 16:06:42 -08001166 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001167 }
1168 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001169
Ian Rogers15bf2d32012-08-28 17:33:04 -07001170 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001171 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001172 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001173 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001174 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001175 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001176 }
1177 // Inform DDMS that a GC completed.
1178 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001179 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001180}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001181
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001182void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001183 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001184 // 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 -07001185 // cards.
1186 return;
1187 }
1188
1189 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001190 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001191 zygote_mod_union_table_->Update();
1192 timings.AddSplit("UpdateZygoteModUnionTable");
1193
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001194 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001195 timings.AddSplit("ZygoteMarkReferences");
1196 }
1197
1198 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1199 mod_union_table_->Update();
1200 timings.AddSplit("UpdateModUnionTable");
1201
1202 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001203 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001204 timings.AddSplit("MarkImageToAllocSpaceReferences");
1205}
1206
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001207void Heap::RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
1208 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001209 if (root == obj) {
1210 LOG(INFO) << "Object " << obj << " is a root";
1211 }
1212}
1213
1214class ScanVisitor {
1215 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001216 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001217 LOG(INFO) << "Would have rescanned object " << obj;
1218 }
1219};
1220
1221class VerifyReferenceVisitor {
1222 public:
1223 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001224 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1225 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001226 : heap_(heap),
1227 failed_(failed) {
1228 }
1229
1230 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1231 // analysis.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001232 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
1233 const MemberOffset& /* offset */, bool /* is_static */) const
1234 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001235 // Verify that the reference is live.
1236 if (ref != NULL && !IsLive(ref)) {
1237 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001238 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1239 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001241 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001242 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1243 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1244 << "Obj type " << PrettyTypeOf(obj) << "\n"
1245 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001246 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001247 void* cover_begin = card_table->AddrFromCard(card_addr);
1248 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001249 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001250 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001251 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001252 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1253
1254 // Print out how the object is live.
1255 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001256 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1257 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001258 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1259 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1260 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001261 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1262 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001263 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001264 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001265 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001266 }
1267
1268 // Attempt to see if the card table missed the reference.
1269 ScanVisitor scan_visitor;
1270 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001271 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001272 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001273
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001274 // Search to see if any of the roots reference our object.
1275 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1276 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1277 *failed_ = true;
1278 }
1279 }
1280
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001281 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001282 if (heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001283 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001284 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001285 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001286 // 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 -08001287 // If the object is not either in the live bitmap or allocation stack, so the object must be
1288 // dead.
1289 return std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001290 }
1291
1292 private:
1293 Heap* heap_;
1294 bool* failed_;
1295};
1296
1297class VerifyObjectVisitor {
1298 public:
1299 VerifyObjectVisitor(Heap* heap)
1300 : heap_(heap),
1301 failed_(false) {
1302
1303 }
1304
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001305 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001306 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001307 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1308 MarkSweep::VisitObjectReferences(obj, visitor);
1309 }
1310
1311 bool Failed() const {
1312 return failed_;
1313 }
1314
1315 private:
1316 Heap* heap_;
1317 bool failed_;
1318};
1319
1320// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001321bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001322 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001323 // Lets sort our allocation stacks so that we can efficiently binary search them.
1324 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1325 std::sort(live_stack_->Begin(), live_stack_->End());
1326 // Perform the verification.
1327 VerifyObjectVisitor visitor(this);
1328 GetLiveBitmap()->Visit(visitor);
1329 // We don't want to verify the objects in the allocation stack since they themselves may be
1330 // pointing to dead objects if they are not reachable.
1331 if (visitor.Failed()) {
1332 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001333 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001334 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001335 return true;
1336}
1337
1338class VerifyReferenceCardVisitor {
1339 public:
1340 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1341 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1342 Locks::heap_bitmap_lock_)
1343 : heap_(heap),
1344 failed_(failed) {
1345 }
1346
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001347 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1348 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001349 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1350 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001351 // Filter out class references since changing an object's class does not mark the card as dirty.
1352 // Also handles large objects, since the only reference they hold is a class reference.
1353 if (ref != NULL && !ref->IsClass()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001354 CardTable* card_table = heap_->GetCardTable();
1355 // If the object is not dirty and it is referencing something in the live stack other than
1356 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001357 if (!card_table->AddrIsInCardTable(obj)) {
1358 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1359 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001360 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001361 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1362 // kCardDirty - 1 if it didnt get touched since we aged it.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001363 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001364 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001365 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1366 LOG(ERROR) << "Object " << obj << " found in live stack";
1367 }
1368 if (heap_->GetLiveBitmap()->Test(obj)) {
1369 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1370 }
1371 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1372 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1373
1374 // Print which field of the object is dead.
1375 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001376 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001377 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001378 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1379 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001380 CHECK(fields != NULL);
1381 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001382 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001383 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1384 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1385 << PrettyField(cur);
1386 break;
1387 }
1388 }
1389 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001390 const mirror::ObjectArray<mirror::Object>* object_array =
1391 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001392 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1393 if (object_array->Get(i) == ref) {
1394 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1395 }
1396 }
1397 }
1398
1399 *failed_ = true;
1400 }
1401 }
1402 }
1403 }
1404
1405 private:
1406 Heap* heap_;
1407 bool* failed_;
1408};
1409
1410class VerifyLiveStackReferences {
1411 public:
1412 VerifyLiveStackReferences(Heap* heap)
1413 : heap_(heap),
1414 failed_(false) {
1415
1416 }
1417
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001418 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001419 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1420 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1421 MarkSweep::VisitObjectReferences(obj, visitor);
1422 }
1423
1424 bool Failed() const {
1425 return failed_;
1426 }
1427
1428 private:
1429 Heap* heap_;
1430 bool failed_;
1431};
1432
1433bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001434 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001435
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001436 // We need to sort the live stack since we binary search it.
1437 std::sort(live_stack_->Begin(), live_stack_->End());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001438 VerifyLiveStackReferences visitor(this);
1439 GetLiveBitmap()->Visit(visitor);
1440
1441 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001442 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001443 visitor(*it);
1444 }
1445
1446 if (visitor.Failed()) {
1447 DumpSpaces();
1448 return false;
1449 }
1450 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001451}
1452
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001453void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001454 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001455
1456 // Sort the live stack so that we can quickly binary search it later.
1457 if (VERIFY_OBJECT_ENABLED) {
1458 std::sort(live_stack_->Begin(), live_stack_->End());
1459 }
1460}
1461
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001462void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001463 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1464 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1465 ContinuousSpace* space = *it;
1466 if (space->IsImageSpace()) {
1467 mod_union_table_->ClearCards(*it);
1468 timings.AddSplit("ModUnionClearCards");
1469 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1470 zygote_mod_union_table_->ClearCards(space);
1471 timings.AddSplit("ZygoteModUnionClearCards");
1472 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001473 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1474 // were dirty before the GC started.
1475 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1476 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001477 }
1478 }
1479}
1480
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001481void Heap::PreGcVerification(GarbageCollector* gc) {
1482 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1483 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001484
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001485 if (verify_pre_gc_heap_) {
1486 thread_list->SuspendAll();
1487 {
1488 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1489 if (!VerifyHeapReferences()) {
1490 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1491 }
1492 }
1493 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001494 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001495
1496 // Check that all objects which reference things in the live stack are on dirty cards.
1497 if (verify_missing_card_marks_) {
1498 thread_list->SuspendAll();
1499 {
1500 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1501 SwapStacks();
1502 // Sort the live stack so that we can quickly binary search it later.
1503 if (!VerifyMissingCardMarks()) {
1504 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1505 }
1506 SwapStacks();
1507 }
1508 thread_list->ResumeAll();
1509 }
1510
1511 if (verify_mod_union_table_) {
1512 thread_list->SuspendAll();
1513 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1514 zygote_mod_union_table_->Update();
1515 zygote_mod_union_table_->Verify();
1516 mod_union_table_->Update();
1517 mod_union_table_->Verify();
1518 thread_list->ResumeAll();
1519 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001520}
1521
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001522void Heap::PreSweepingGcVerification(GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001523 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001524 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001525
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001526 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1527 // reachable objects.
1528 if (verify_post_gc_heap_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001529 thread_list->SuspendAll();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001530 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1531 // Swapping bound bitmaps does nothing.
1532 live_bitmap_.swap(mark_bitmap_);
1533 if (!VerifyHeapReferences()) {
1534 LOG(FATAL) << "Post " << gc->GetName() << "Gc verification failed";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001535 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001536 live_bitmap_.swap(mark_bitmap_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001537 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001538 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001539}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001541void Heap::PostGcVerification(GarbageCollector* gc) {
1542 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001543
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001544 if (verify_system_weaks_) {
1545 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1546 MarkSweep* mark_sweep = down_cast<MarkSweep*>(gc);
1547 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001548 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001549}
1550
Ian Rogers81d425b2012-09-27 16:03:43 -07001551GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001552 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001553 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001554 bool do_wait;
1555 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556 {
1557 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001558 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001559 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001560 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001561 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001562 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001563 // We must wait, change thread state then sleep on gc_complete_cond_;
1564 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1565 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001566 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001567 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001568 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001569 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001570 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001571 wait_time = NanoTime() - wait_start;;
1572 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001573 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001574 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001575 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1576 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001577 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001578 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001579 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001580}
1581
Elliott Hughesc967f782012-04-16 10:23:15 -07001582void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001583 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1584 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001585 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001586}
1587
1588size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001589 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001590}
1591
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001592void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001593 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001594 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001595 << PrettySize(GetMaxMemory());
1596 max_allowed_footprint = GetMaxMemory();
1597 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001598 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001599}
1600
Mathieu Chartier65db8802012-11-20 12:36:46 -08001601void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001602 // We know what our utilization is at this moment.
1603 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001604 const size_t bytes_allocated = GetBytesAllocated();
1605 last_gc_size_ = bytes_allocated;
1606 last_gc_time_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001607
Mathieu Chartier65db8802012-11-20 12:36:46 -08001608 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1609 if (target_size > bytes_allocated + max_free_) {
1610 target_size = bytes_allocated + max_free_;
1611 } else if (target_size < bytes_allocated + min_free_) {
1612 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001613 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001614
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001615 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001616
1617 // Calculate when to perform the next ConcurrentGC if we have enough free memory.
1618 if (concurrent_gc_ && GetFreeMemory() >= concurrent_min_free_) {
1619 // Calculate the estimated GC duration.
1620 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1621 // Estimate how many remaining bytes we will have when we need to start the next GC.
1622 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1623 if (remaining_bytes < max_allowed_footprint_) {
1624 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1625 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1626 // right away.
1627 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1628 } else {
1629 // The estimated rate is so high that we should request another GC straight away.
1630 concurrent_start_bytes_ = bytes_allocated;
1631 }
1632 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1633 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1634 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001635}
1636
jeffhaoc1160702011-10-27 15:48:45 -07001637void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001638 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001639 alloc_space_->ClearGrowthLimit();
1640}
1641
Elliott Hughesadb460d2011-10-05 17:02:34 -07001642void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001643 MemberOffset reference_queue_offset,
1644 MemberOffset reference_queueNext_offset,
1645 MemberOffset reference_pendingNext_offset,
1646 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001647 reference_referent_offset_ = reference_referent_offset;
1648 reference_queue_offset_ = reference_queue_offset;
1649 reference_queueNext_offset_ = reference_queueNext_offset;
1650 reference_pendingNext_offset_ = reference_pendingNext_offset;
1651 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1652 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1653 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1654 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1655 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1656 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1657}
1658
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001659mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001660 DCHECK(reference != NULL);
1661 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001662 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001663}
1664
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001665void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001666 DCHECK(reference != NULL);
1667 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1668 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1669}
1670
1671// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001672bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001673 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001674 const mirror::Object* queue =
1675 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1676 const mirror::Object* queue_next =
1677 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001678 return (queue != NULL) && (queue_next == NULL);
1679}
1680
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001681void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001682 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001683 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1684 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001685 EnqueuePendingReference(ref, cleared_reference_list);
1686}
1687
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001688void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001689 DCHECK(ref != NULL);
1690 DCHECK(list != NULL);
1691
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001692 // TODO: Remove this lock, use atomic stacks for storing references.
1693 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001694 if (*list == NULL) {
1695 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1696 *list = ref;
1697 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001698 mirror::Object* head =
1699 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001700 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1701 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1702 }
1703}
1704
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001705mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001706 DCHECK(list != NULL);
1707 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001708 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1709 false);
1710 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001711
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001712 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1713 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001714 if (*list == head) {
1715 ref = *list;
1716 *list = NULL;
1717 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001718 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1719 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001720 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1721 ref = head;
1722 }
1723 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1724 return ref;
1725}
1726
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001727void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001728 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001729 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001730 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001731 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1732 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001733}
1734
1735size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001736 return num_bytes_allocated_;
1737}
1738
1739size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001740 size_t total = 0;
1741 // TODO: C++0x
1742 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1743 Space* space = *it;
1744 if (space->IsAllocSpace()) {
1745 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1746 }
1747 }
1748 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001749}
1750
1751size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001752 return concurrent_start_size_;
1753}
1754
1755size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001756 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001757}
1758
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001759void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001760 DCHECK(cleared != NULL);
1761 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001762 // When a runtime isn't started there are no reference queues to care about so ignore.
1763 if (LIKELY(Runtime::Current()->IsStarted())) {
1764 ScopedObjectAccess soa(Thread::Current());
1765 JValue args[1];
1766 args[0].SetL(*cleared);
1767 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1768 args, NULL);
1769 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001770 *cleared = NULL;
1771 }
1772}
1773
Ian Rogers1f539342012-10-03 21:09:42 -07001774void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001775 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001776 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001777 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001778 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001779 !runtime->IsConcurrentGcEnabled()) {
1780 return;
1781 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001782 {
1783 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1784 if (runtime->IsShuttingDown()) {
1785 return;
1786 }
1787 }
1788 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001789 return;
1790 }
1791
Ian Rogers120f1c72012-09-28 17:17:10 -07001792 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001793 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1794 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001795 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1796 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001797 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001798}
1799
Ian Rogers81d425b2012-09-27 16:03:43 -07001800void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001801 {
1802 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001803 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001804 return;
1805 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001806 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001807
Mathieu Chartier65db8802012-11-20 12:36:46 -08001808 // Wait for any GCs currently running to finish.
Ian Rogers81d425b2012-09-27 16:03:43 -07001809 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001810 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001811 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001812 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001813 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001814 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001815 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001816}
1817
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001818void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001819 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1820 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1821 // a space it will hold its lock and can become a cause of jank.
1822 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1823 // forking.
1824
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001825 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1826 // because that only marks object heads, so a large array looks like lots of empty space. We
1827 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1828 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1829 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1830 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001831 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001832 float utilization =
1833 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1834 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1835 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1836 // heap trim occurred in the last two seconds.
1837 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001838 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001839
1840 Thread* self = Thread::Current();
1841 {
1842 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1843 Runtime* runtime = Runtime::Current();
1844 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1845 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1846 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1847 // as we don't hold the lock while requesting the trim).
1848 return;
1849 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001850 }
Ian Rogers48931882013-01-22 14:35:16 -08001851
1852 SchedPolicy policy;
1853 get_sched_policy(self->GetTid(), &policy);
1854 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1855 // Don't trim the heap if we are a foreground or audio app.
1856 return;
1857 }
1858
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001859 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001860 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001861 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1862 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001863 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1864 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001865 CHECK(!env->ExceptionCheck());
1866}
1867
Ian Rogers48931882013-01-22 14:35:16 -08001868size_t Heap::Trim() {
1869 // Handle a requested heap trim on a thread outside of the main GC thread.
1870 return alloc_space_->Trim();
1871}
1872
Carl Shapiro69759ea2011-07-21 18:13:35 -07001873} // namespace art