blob: f7abe0a210e0ba6f4e3663e72932be3c57775a74 [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
Elliott Hughes48436bb2012-02-07 15:23:28 -0800107 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800108 LOG(INFO) << command_line;
109
Elliott Hughes48436bb2012-02-07 15:23:28 -0800110 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800111 char** argv = &arg_vector[0];
112
113 // fork and exec dex2oat
114 pid_t pid = fork();
115 if (pid == 0) {
116 // no allocation allowed between fork and exec
117
118 // change process groups, so we don't get reaped by ProcessManager
119 setpgid(0, 0);
120
121 execv(dex2oat, argv);
122
123 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
124 return false;
125 } else {
126 STLDeleteElements(&arg_vector);
127
128 // wait for dex2oat to finish
129 int status;
130 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
131 if (got_pid != pid) {
132 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
133 return false;
134 }
135 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
136 LOG(ERROR) << dex2oat << " failed: " << command_line;
137 return false;
138 }
139 }
140 return true;
141}
142
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700143void Heap::UnReserveOatFileAddressRange() {
144 oat_file_map_.reset(NULL);
145}
146
Mathieu Chartier0051be62012-10-12 17:47:11 -0700147Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
148 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700149 const std::string& original_image_file_name, bool concurrent_gc)
150 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800151 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700152 concurrent_gc_(concurrent_gc),
153 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800154 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700155 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700156 enforce_heap_growth_rate_(false),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800157 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700158 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700159 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700160 concurrent_start_size_(128 * KB),
161 concurrent_min_free_(256 * KB),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800162 concurrent_start_bytes_(concurrent_gc ? initial_size - concurrent_start_size_ :
163 std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700164 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700165 total_bytes_freed_(0),
166 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700167 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800168 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700169 verify_missing_card_marks_(false),
170 verify_system_weaks_(false),
171 verify_pre_gc_heap_(false),
172 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700173 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700174 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700175 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700176 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700177 last_trim_time_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800178 allocation_rate_(0),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700179 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800180 reference_referent_offset_(0),
181 reference_queue_offset_(0),
182 reference_queueNext_offset_(0),
183 reference_pendingNext_offset_(0),
184 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700185 min_free_(min_free),
186 max_free_(max_free),
187 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700188 total_wait_time_(0),
189 measure_allocation_time_(false),
190 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700191 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800192 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800193 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700194 }
195
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700196 live_bitmap_.reset(new HeapBitmap(this));
197 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700198
Ian Rogers30fab402012-01-23 15:43:46 -0800199 // Requested begin for the alloc space, to follow the mapped image and oat files
200 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800201 std::string image_file_name(original_image_file_name);
202 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700203 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700204
Brian Carlstrom5643b782012-02-05 12:32:53 -0800205 if (OS::FileExists(image_file_name.c_str())) {
206 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700207 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800208 } else {
209 // If the /system file didn't exist, we need to use one from the art-cache.
210 // If the cache file exists, try to open, but if it fails, regenerate.
211 // If it does not exist, generate.
212 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
213 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700214 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800215 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700216 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700217 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700218 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800219 }
220 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700221
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700222 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700223 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800224 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
225 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800226 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
227 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700228
229 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
230 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800231 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700232 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
233 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800234 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700235
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800236 if (oat_file_end_addr > requested_begin) {
237 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700238 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700239 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700240 }
241
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700242 // Allocate the large object space.
243 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700244 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
245 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
246
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700247 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
248 growth_limit, capacity,
249 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700250 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700251 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700252 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700253 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700254
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700255 // Spaces are sorted in order of Begin().
256 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700257 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
258 if (spaces_.back()->IsAllocSpace()) {
259 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
260 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700261
Ian Rogers30fab402012-01-23 15:43:46 -0800262 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700263 // TODO: C++0x
264 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
265 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800266 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700267 ImageSpace* image_space = space->AsImageSpace();
268 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800269 }
270 }
271
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800272 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700273 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
274 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700275
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700276 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
277 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700278
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700279 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
280 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700281
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700282 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700283 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800285 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700286 static const size_t default_mark_stack_size = 64 * KB;
287 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
288 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700289 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700290 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
291 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700292
Mathieu Chartier65db8802012-11-20 12:36:46 -0800293 // It's still too early to take a lock because there are no threads yet, but we can create locks
294 // now. We don't create it earlier to make it clear that you can't use locks during heap
295 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700296 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700297 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
298 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700299
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700300 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
301 reference_queue_lock_.reset(new Mutex("reference queue lock"));
302
Mathieu Chartier65db8802012-11-20 12:36:46 -0800303 last_gc_time_ = NanoTime();
304 last_gc_size_ = GetBytesAllocated();
305
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800306 // Create our garbage collectors.
307 for (size_t i = 0; i < 2; ++i) {
308 const bool concurrent = i != 0;
309 mark_sweep_collectors_.push_back(new MarkSweep(this, concurrent));
310 mark_sweep_collectors_.push_back(new PartialMarkSweep(this, concurrent));
311 mark_sweep_collectors_.push_back(new StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700312 }
313
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800314 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800315 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800316 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700317 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700318}
319
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700320void Heap::CreateThreadPool() {
321 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
322 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
323 // workers to complete.
324 thread_pool_.reset(new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
325}
326
327void Heap::DeleteThreadPool() {
328 thread_pool_.reset(NULL);
329}
330
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700331// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700332struct SpaceSorter {
333 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700334 return a->Begin() < b->Begin();
335 }
336};
337
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700338void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700339 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700340 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700341 DCHECK(space->GetLiveBitmap() != NULL);
342 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700343 DCHECK(space->GetMarkBitmap() != NULL);
344 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800345 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700346 if (space->IsAllocSpace()) {
347 alloc_space_ = space->AsAllocSpace();
348 }
349
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700350 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
351 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700352
353 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
354 // avoid redundant marking.
355 bool seen_zygote = false, seen_alloc = false;
356 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
357 Space* space = *it;
358 if (space->IsImageSpace()) {
359 DCHECK(!seen_zygote);
360 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700361 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700362 DCHECK(!seen_alloc);
363 seen_zygote = true;
364 } else if (space->IsAllocSpace()) {
365 seen_alloc = true;
366 }
367 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800368}
369
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700370void Heap::DumpGcPerformanceInfo() {
371 // Dump cumulative timings.
372 LOG(INFO) << "Dumping cumulative Gc timings";
373 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800374
375 // Dump cumulative loggers for each GC type.
376 // TODO: C++0x
377 uint64_t total_paused_time = 0;
378 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800379 it != mark_sweep_collectors_.end(); ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800380 MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800381 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800382 if (logger.GetTotalNs() != 0) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800383 LOG(INFO) << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800384 const uint64_t total_ns = logger.GetTotalNs();
385 const uint64_t total_pause_ns = (*it)->GetTotalPausedTime();
386 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
387 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
388 const uint64_t freed_objects = collector->GetTotalFreedObjects();
389 LOG(INFO)
390 << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
391 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
392 << collector->GetName() << " freed: " << freed_objects
393 << " objects with total size " << PrettySize(freed_bytes) << "\n"
394 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
395 << PrettySize(freed_bytes / seconds) << "/s\n";
396 total_duration += total_ns;
397 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700398 }
399 }
400 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
401 size_t total_objects_allocated = GetTotalObjectsAllocated();
402 size_t total_bytes_allocated = GetTotalBytesAllocated();
403 if (total_duration != 0) {
404 const double total_seconds = double(total_duration / 1000) / 1000000.0;
405 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
406 LOG(INFO) << "Mean GC size throughput: "
407 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
Elliott Hughes80537bb2013-01-04 16:37:26 -0800408 LOG(INFO) << "Mean GC object throughput: "
409 << (GetTotalObjectsFreed() / total_seconds) << " objects/s";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700410 }
411 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
412 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
413 if (measure_allocation_time_) {
414 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
415 LOG(INFO) << "Mean allocation time: "
416 << PrettyDuration(allocation_time / total_objects_allocated);
417 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800418 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time);
Elliott Hughes80537bb2013-01-04 16:37:26 -0800419 LOG(INFO) << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700420}
421
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800422Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700423 if (kDumpGcPerformanceOnShutdown) {
424 DumpGcPerformanceInfo();
425 }
426
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800427 STLDeleteElements(&mark_sweep_collectors_);
428
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700429 // If we don't reset then the mark stack complains in it's destructor.
430 allocation_stack_->Reset();
431 live_stack_->Reset();
432
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800433 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800434 // We can't take the heap lock here because there might be a daemon thread suspended with the
435 // heap lock held. We know though that no non-daemon threads are executing, and we know that
436 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
437 // 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 -0700438 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700439 delete gc_complete_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700440}
441
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800442ContinuousSpace* Heap::FindSpaceFromObject(const mirror::Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700443 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700444 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
445 if ((*it)->Contains(obj)) {
446 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700447 }
448 }
449 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
450 return NULL;
451}
452
453ImageSpace* Heap::GetImageSpace() {
454 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700455 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
456 if ((*it)->IsImageSpace()) {
457 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700458 }
459 }
460 return NULL;
461}
462
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700463DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700464 return alloc_space_;
465}
466
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700467static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700468 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700469 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700470 size_t chunk_free_bytes = chunk_size - used_bytes;
471 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
472 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700473 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700474}
475
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800476mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
477 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
479 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800480 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700481
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800482 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700483 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700484 uint64_t allocation_start = 0;
485 if (measure_allocation_time_) {
486 allocation_start = NanoTime();
487 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700488
489 // We need to have a zygote space or else our newly allocated large object can end up in the
490 // Zygote resulting in it being prematurely freed.
491 // We can only do this for primive objects since large objects will not be within the card table
492 // range. This also means that we rely on SetClass not dirtying the object's card.
493 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700494 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700495 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700496 // Make sure that our large object didn't get placed anywhere within the space interval or else
497 // it breaks the immune range.
498 DCHECK(obj == NULL ||
499 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
500 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700501 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700502 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700503
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700504 // Ensure that we did not allocate into a zygote space.
505 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
506 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700507 }
508
Mathieu Chartier037813d2012-08-23 16:44:59 -0700509 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700511
512 // Record allocation after since we want to use the atomic add for the atomic fence to guard
513 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700514 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700515
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516 if (Dbg::IsAllocTrackingEnabled()) {
517 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700518 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700519 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700520 // We already have a request pending, no reason to start more until we update
521 // concurrent_start_bytes_.
522 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700523 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800524 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700525 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700526 }
527 VerifyObject(obj);
528
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700529 if (measure_allocation_time_) {
530 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
531 }
532
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700533 return obj;
534 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800535 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700536 int64_t total_bytes_free = GetFreeMemory();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800537 uint64_t alloc_space_size = alloc_space_->GetNumBytesAllocated();
538 uint64_t large_object_size = large_object_space_->GetNumObjectsAllocated();
539 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
540 << " free bytes; allocation space size " << alloc_space_size
541 << "; large object space size " << large_object_size;
542 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
543 if (total_bytes_free >= byte_count) {
544 size_t max_contiguous_allocation = 0;
545 // TODO: C++0x auto
546 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
547 if ((*it)->IsAllocSpace()) {
548 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
549 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700550 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800551 oss << "; failed due to fragmentation (largest possible contiguous allocation "
552 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700553 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800554 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700555 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700556}
557
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800558bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700559 // Note: we deliberately don't take the lock here, and mustn't test anything that would
560 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700561 if (obj == NULL) {
562 return true;
563 }
564 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700565 return false;
566 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800567 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800568 if (spaces_[i]->Contains(obj)) {
569 return true;
570 }
571 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700572 // Note: Doing this only works for the free list version of the large object space since the
573 // multiple memory map version uses a lock to do the contains check.
574 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700575}
576
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800577bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700578 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700579 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700580}
581
Elliott Hughes3e465b12011-09-02 18:26:12 -0700582#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700583void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700584 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700585 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700586 return;
587 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700588 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700589}
590#endif
591
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700592void Heap::DumpSpaces() {
593 // TODO: C++0x auto
594 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700595 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700596 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
597 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
598 LOG(INFO) << space << " " << *space << "\n"
599 << live_bitmap << " " << *live_bitmap << "\n"
600 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700601 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700602 if (large_object_space_.get() != NULL) {
603 large_object_space_->Dump(LOG(INFO));
604 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700605}
606
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800607void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700608 if (!IsAligned<kObjectAlignment>(obj)) {
609 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700610 }
611
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700612 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
613 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700614 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700615 // Check the allocation stack / live stack.
616 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
617 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
618 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700619 if (large_object_space_->GetLiveObjects()->Test(obj)) {
620 DumpSpaces();
621 LOG(FATAL) << "Object is dead: " << obj;
622 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700623 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700624 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700625
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700626 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700627 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700628 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800629 mirror::Object::ClassOffset().Int32Value();
630 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700631 if (c == NULL) {
632 LOG(FATAL) << "Null class in object: " << obj;
633 } else if (!IsAligned<kObjectAlignment>(c)) {
634 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
635 } else if (!GetLiveBitmap()->Test(c)) {
636 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
637 }
638 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
639 // Note: we don't use the accessors here as they have internal sanity checks
640 // that we don't want to run
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800641 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
642 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
643 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
644 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700645 CHECK_EQ(c_c, c_c_c);
646 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700647}
648
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800649void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700650 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700651 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700652}
653
654void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700655 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700656 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700657}
658
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800659void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700660 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700661 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700662 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700663
664 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700665 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700666 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700667 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700668
669 // TODO: Update these atomically.
670 RuntimeStats* global_stats = Runtime::Current()->GetStats();
671 ++global_stats->allocated_objects;
672 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700673 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700674
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700675 // This is safe to do since the GC will never free objects which are neither in the allocation
676 // stack or the live bitmap.
677 while (!allocation_stack_->AtomicPushBack(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700678 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700679 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700680}
681
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700682void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700683 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
684 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700685
686 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700687 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700688 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700689 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700690
691 // TODO: Do this concurrently.
692 RuntimeStats* global_stats = Runtime::Current()->GetStats();
693 global_stats->freed_objects += freed_objects;
694 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700695 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700696}
697
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800698mirror::Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700699 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800700 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
701 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
702 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
703 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700704 return NULL;
705 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700706
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800707 if (enforce_heap_growth_rate_) {
708 if (grow) {
709 // Grow the heap by alloc_size extra bytes.
710 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
711 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
712 << " for a " << PrettySize(alloc_size) << " allocation";
713 } else {
714 return NULL;
715 }
716 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700717 }
718
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700719 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700720}
721
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800722mirror::Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700723 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
724 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700725 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700726 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700727
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800728 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700729 if (ptr != NULL) {
730 return ptr;
731 }
732
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700733 // The allocation failed. If the GC is running, block until it completes, and then retry the
734 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700735 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700736 if (last_gc != kGcTypeNone) {
737 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700738 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700739 if (ptr != NULL) {
740 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700741 }
742 }
743
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700744 // Loop through our different Gc types and try to Gc until we get enough free memory.
745 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
746 bool run_gc = false;
747 GcType gc_type = static_cast<GcType>(i);
748 switch (gc_type) {
749 case kGcTypeSticky: {
750 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700751 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
752 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700753 break;
754 }
755 case kGcTypePartial:
756 run_gc = have_zygote_space_;
757 break;
758 case kGcTypeFull:
759 run_gc = true;
760 break;
761 default:
762 break;
763 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700764
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700765 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700766 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700767 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800768 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700769 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700770
771 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700772 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700773 if (ptr != NULL) {
774 return ptr;
775 }
776 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700777 }
778
779 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700780 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700781 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700782 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700783 return ptr;
784 }
785
Elliott Hughes81ff3182012-03-23 20:35:56 -0700786 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
787 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
788 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700789
Elliott Hughes418dfe72011-10-06 18:56:27 -0700790 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700791 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
792 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700793
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700794 // We don't need a WaitForConcurrentGcToComplete here either.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700795 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700796 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700797}
798
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700799void Heap::SetTargetHeapUtilization(float target) {
800 DCHECK_GT(target, 0.0f); // asserted in Java code
801 DCHECK_LT(target, 1.0f);
802 target_utilization_ = target;
803}
804
805int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700806 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700807}
808
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700809int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700810 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700811}
812
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700813int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700814 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700815}
816
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700817size_t Heap::GetTotalBytesFreed() const {
818 return total_bytes_freed_;
819}
820
821size_t Heap::GetTotalObjectsFreed() const {
822 return total_objects_freed_;
823}
824
825size_t Heap::GetTotalObjectsAllocated() const {
826 size_t total = large_object_space_->GetTotalObjectsAllocated();
827 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
828 Space* space = *it;
829 if (space->IsAllocSpace()) {
830 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
831 }
832 }
833 return total;
834}
835
836size_t Heap::GetTotalBytesAllocated() const {
837 size_t total = large_object_space_->GetTotalBytesAllocated();
838 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
839 Space* space = *it;
840 if (space->IsAllocSpace()) {
841 total += space->AsAllocSpace()->GetTotalBytesAllocated();
842 }
843 }
844 return total;
845}
846
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700847class InstanceCounter {
848 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800849 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700850 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800851 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700852 }
853
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800854 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800855 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800856 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800857 if (use_is_assignable_from_) {
858 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
859 ++counts_[i];
860 }
861 } else {
862 if (instance_class == classes_[i]) {
863 ++counts_[i];
864 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700865 }
866 }
867 }
868
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700869 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800870 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800871 bool use_is_assignable_from_;
872 uint64_t* const counts_;
873
874 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700875};
876
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800877void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800878 uint64_t* counts) {
879 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
880 // is empty, so the live bitmap is the only place we need to look.
881 Thread* self = Thread::Current();
882 self->TransitionFromRunnableToSuspended(kNative);
883 CollectGarbage(false);
884 self->TransitionFromSuspendedToRunnable();
885
886 InstanceCounter counter(classes, use_is_assignable_from, counts);
887 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700888 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700889}
890
Elliott Hughes3b78c942013-01-15 17:35:41 -0800891class InstanceCollector {
892 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800893 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800894 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
895 : class_(c), max_count_(max_count), instances_(instances) {
896 }
897
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800898 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
899 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800900 if (instance_class == class_) {
901 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800902 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800903 }
904 }
905 }
906
907 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800908 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800909 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800910 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800911
912 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
913};
914
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800915void Heap::GetInstances(mirror::Class* c, int32_t max_count,
916 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800917 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
918 // is empty, so the live bitmap is the only place we need to look.
919 Thread* self = Thread::Current();
920 self->TransitionFromRunnableToSuspended(kNative);
921 CollectGarbage(false);
922 self->TransitionFromSuspendedToRunnable();
923
924 InstanceCollector collector(c, max_count, instances);
925 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
926 GetLiveBitmap()->Visit(collector);
927}
928
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800929class ReferringObjectsFinder {
930 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800931 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
932 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800933 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
934 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
935 }
936
937 // For bitmap Visit.
938 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
939 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800940 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800941 MarkSweep::VisitObjectReferences(o, *this);
942 }
943
944 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800945 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
946 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800947 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800948 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800949 }
950 }
951
952 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800953 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800954 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800955 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800956
957 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
958};
959
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800960void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
961 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800962 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
963 // is empty, so the live bitmap is the only place we need to look.
964 Thread* self = Thread::Current();
965 self->TransitionFromRunnableToSuspended(kNative);
966 CollectGarbage(false);
967 self->TransitionFromSuspendedToRunnable();
968
969 ReferringObjectsFinder finder(o, max_count, referring_objects);
970 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
971 GetLiveBitmap()->Visit(finder);
972}
973
Ian Rogers30fab402012-01-23 15:43:46 -0800974void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700975 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
976 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700977 Thread* self = Thread::Current();
978 WaitForConcurrentGcToComplete(self);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700979 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700980}
981
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700982void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700983 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800984 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
985 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700986 Thread* self = Thread::Current();
987 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700988
989 // Try to see if we have any Zygote spaces.
990 if (have_zygote_space_) {
991 return;
992 }
993
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700994 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
995
996 {
997 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700998 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700999 FlushAllocStack();
1000 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001001
1002 // Replace the first alloc space we find with a zygote space.
1003 // TODO: C++0x auto
1004 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1005 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001006 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001007
1008 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1009 // of the remaining available heap memory.
1010 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001011 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001012
1013 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001014 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001015 AddSpace(alloc_space_);
1016 have_zygote_space_ = true;
1017 break;
1018 }
1019 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001020
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001021 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001022 // TODO: C++0x
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001023 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
1024 it != mark_sweep_collectors_.end(); ++it) {
1025 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001026 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001027}
1028
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001029void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001030 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1031 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001032 allocation_stack_->Reset();
1033}
1034
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001035size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001036 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001037}
1038
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001039void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001040 mirror::Object** limit = stack->End();
1041 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1042 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001043 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001044 if (LIKELY(bitmap->HasAddress(obj))) {
1045 bitmap->Set(obj);
1046 } else {
1047 large_objects->Set(obj);
1048 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001049 }
1050}
1051
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001052void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001053 mirror::Object** limit = stack->End();
1054 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1055 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001056 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001057 if (LIKELY(bitmap->HasAddress(obj))) {
1058 bitmap->Clear(obj);
1059 } else {
1060 large_objects->Clear(obj);
1061 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001062 }
1063}
1064
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001065GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001066 Thread* self = Thread::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001067 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001068 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001069
Ian Rogers120f1c72012-09-28 17:17:10 -07001070 if (self->IsHandlingStackOverflow()) {
1071 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1072 }
1073
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001074 // Ensure there is only one GC at a time.
1075 bool start_collect = false;
1076 while (!start_collect) {
1077 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001078 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001079 if (!is_gc_running_) {
1080 is_gc_running_ = true;
1081 start_collect = true;
1082 }
1083 }
1084 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001085 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001086 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1087 // Not doing at the moment to ensure soft references are cleared.
1088 }
1089 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001090 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001091
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001092 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1093 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1094 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1095 }
1096
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001097 // We need to do partial GCs every now and then to avoid the heap growing too much and
1098 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001099 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001100 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001101 }
Mathieu Chartier0325e622012-09-05 14:22:51 -07001102 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001103 sticky_gc_count_ = 0;
1104 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001105
Mathieu Chartier65db8802012-11-20 12:36:46 -08001106 uint64_t gc_start_time = NanoTime();
1107 uint64_t gc_start_size = GetBytesAllocated();
1108 // Approximate allocation rate in bytes / second.
Jeff Hao9bd02812013-02-08 14:29:50 -08001109 if (UNLIKELY(gc_start_time == last_gc_time_)) {
1110 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1111 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001112 uint64_t ms_delta = NsToMs(gc_start_time - last_gc_time_);
1113 if (ms_delta != 0) {
1114 allocation_rate_ = (gc_start_size - last_gc_size_) * 1000 / ms_delta;
1115 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1116 }
1117
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001118 DCHECK_LT(gc_type, kGcTypeMax);
1119 DCHECK_NE(gc_type, kGcTypeNone);
1120 MarkSweep* collector = NULL;
1121 for (Collectors::iterator it = mark_sweep_collectors_.begin();
1122 it != mark_sweep_collectors_.end(); ++it) {
1123 MarkSweep* cur_collector = *it;
1124 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1125 collector = cur_collector;
1126 break;
1127 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001128 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001129 CHECK(collector != NULL)
1130 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1131 << " and type=" << gc_type;
1132 collector->clear_soft_references_ = clear_soft_references;
1133 collector->Run();
1134 total_objects_freed_ += collector->GetFreedObjects();
1135 total_bytes_freed_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001136
Mathieu Chartier65db8802012-11-20 12:36:46 -08001137 const size_t duration = collector->GetDuration();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001138 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1139 bool was_slow = duration > kSlowGcThreshold ||
1140 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1141 for (size_t i = 0; i < pauses.size(); ++i) {
1142 if (pauses[i] > kLongGcPauseThreshold) {
1143 was_slow = true;
1144 }
1145 }
1146
1147 if (was_slow) {
1148 const size_t percent_free = GetPercentFree();
1149 const size_t current_heap_size = GetUsedMemorySize();
1150 const size_t total_memory = GetTotalMemory();
1151 std::ostringstream pause_string;
1152 for (size_t i = 0; i < pauses.size(); ++i) {
1153 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1154 << ((i != pauses.size() - 1) ? ", " : "");
1155 }
1156 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001157 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1158 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1159 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1160 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001161 if (VLOG_IS_ON(heap)) {
Sameer Abu Asala8439542013-02-14 16:06:42 -08001162 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001163 }
1164 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001165
Ian Rogers15bf2d32012-08-28 17:33:04 -07001166 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001167 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001168 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001169 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001170 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001171 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001172 }
1173 // Inform DDMS that a GC completed.
1174 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001175 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001176}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001177
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001178void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001179 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001180 // 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 -07001181 // cards.
1182 return;
1183 }
1184
1185 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001186 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001187 zygote_mod_union_table_->Update();
1188 timings.AddSplit("UpdateZygoteModUnionTable");
1189
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001190 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001191 timings.AddSplit("ZygoteMarkReferences");
1192 }
1193
1194 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1195 mod_union_table_->Update();
1196 timings.AddSplit("UpdateModUnionTable");
1197
1198 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001199 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001200 timings.AddSplit("MarkImageToAllocSpaceReferences");
1201}
1202
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001203void Heap::RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
1204 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001205 if (root == obj) {
1206 LOG(INFO) << "Object " << obj << " is a root";
1207 }
1208}
1209
1210class ScanVisitor {
1211 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001212 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001213 LOG(INFO) << "Would have rescanned object " << obj;
1214 }
1215};
1216
1217class VerifyReferenceVisitor {
1218 public:
1219 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001220 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1221 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001222 : heap_(heap),
1223 failed_(failed) {
1224 }
1225
1226 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1227 // analysis.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001228 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
1229 const MemberOffset& /* offset */, bool /* is_static */) const
1230 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001231 // Verify that the reference is live.
1232 if (ref != NULL && !IsLive(ref)) {
1233 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001234 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1235 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001236
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001237 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001238 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1239 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1240 << "Obj type " << PrettyTypeOf(obj) << "\n"
1241 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001242 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001243 void* cover_begin = card_table->AddrFromCard(card_addr);
1244 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001245 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001246 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001247 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001248 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1249
1250 // Print out how the object is live.
1251 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001252 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1253 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001254 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1255 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1256 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001257 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1258 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001259 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001260 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001261 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001262 }
1263
1264 // Attempt to see if the card table missed the reference.
1265 ScanVisitor scan_visitor;
1266 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001267 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001268 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001269
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001270 // Search to see if any of the roots reference our object.
1271 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1272 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1273 *failed_ = true;
1274 }
1275 }
1276
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001277 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001278 if (heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001279 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001280 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001281 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001282 // 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 -08001283 // If the object is not either in the live bitmap or allocation stack, so the object must be
1284 // dead.
1285 return std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001286 }
1287
1288 private:
1289 Heap* heap_;
1290 bool* failed_;
1291};
1292
1293class VerifyObjectVisitor {
1294 public:
1295 VerifyObjectVisitor(Heap* heap)
1296 : heap_(heap),
1297 failed_(false) {
1298
1299 }
1300
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001301 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001302 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001303 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1304 MarkSweep::VisitObjectReferences(obj, visitor);
1305 }
1306
1307 bool Failed() const {
1308 return failed_;
1309 }
1310
1311 private:
1312 Heap* heap_;
1313 bool failed_;
1314};
1315
1316// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001317bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001318 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001319 // Lets sort our allocation stacks so that we can efficiently binary search them.
1320 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1321 std::sort(live_stack_->Begin(), live_stack_->End());
1322 // Perform the verification.
1323 VerifyObjectVisitor visitor(this);
1324 GetLiveBitmap()->Visit(visitor);
1325 // We don't want to verify the objects in the allocation stack since they themselves may be
1326 // pointing to dead objects if they are not reachable.
1327 if (visitor.Failed()) {
1328 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001329 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001330 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001331 return true;
1332}
1333
1334class VerifyReferenceCardVisitor {
1335 public:
1336 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1337 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1338 Locks::heap_bitmap_lock_)
1339 : heap_(heap),
1340 failed_(failed) {
1341 }
1342
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001343 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1344 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001345 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1346 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001347 // Filter out class references since changing an object's class does not mark the card as dirty.
1348 // Also handles large objects, since the only reference they hold is a class reference.
1349 if (ref != NULL && !ref->IsClass()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001350 CardTable* card_table = heap_->GetCardTable();
1351 // If the object is not dirty and it is referencing something in the live stack other than
1352 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001353 if (!card_table->AddrIsInCardTable(obj)) {
1354 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1355 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001356 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001357 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1358 // kCardDirty - 1 if it didnt get touched since we aged it.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001359 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001360 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001361 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1362 LOG(ERROR) << "Object " << obj << " found in live stack";
1363 }
1364 if (heap_->GetLiveBitmap()->Test(obj)) {
1365 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1366 }
1367 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1368 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1369
1370 // Print which field of the object is dead.
1371 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001372 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001373 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001374 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1375 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001376 CHECK(fields != NULL);
1377 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001378 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001379 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1380 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1381 << PrettyField(cur);
1382 break;
1383 }
1384 }
1385 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001386 const mirror::ObjectArray<mirror::Object>* object_array =
1387 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001388 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1389 if (object_array->Get(i) == ref) {
1390 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1391 }
1392 }
1393 }
1394
1395 *failed_ = true;
1396 }
1397 }
1398 }
1399 }
1400
1401 private:
1402 Heap* heap_;
1403 bool* failed_;
1404};
1405
1406class VerifyLiveStackReferences {
1407 public:
1408 VerifyLiveStackReferences(Heap* heap)
1409 : heap_(heap),
1410 failed_(false) {
1411
1412 }
1413
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001414 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001415 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1416 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1417 MarkSweep::VisitObjectReferences(obj, visitor);
1418 }
1419
1420 bool Failed() const {
1421 return failed_;
1422 }
1423
1424 private:
1425 Heap* heap_;
1426 bool failed_;
1427};
1428
1429bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001430 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001431
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001432 // We need to sort the live stack since we binary search it.
1433 std::sort(live_stack_->Begin(), live_stack_->End());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001434 VerifyLiveStackReferences visitor(this);
1435 GetLiveBitmap()->Visit(visitor);
1436
1437 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001438 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001439 visitor(*it);
1440 }
1441
1442 if (visitor.Failed()) {
1443 DumpSpaces();
1444 return false;
1445 }
1446 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001447}
1448
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001449void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001450 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001451
1452 // Sort the live stack so that we can quickly binary search it later.
1453 if (VERIFY_OBJECT_ENABLED) {
1454 std::sort(live_stack_->Begin(), live_stack_->End());
1455 }
1456}
1457
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001458void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001459 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1460 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1461 ContinuousSpace* space = *it;
1462 if (space->IsImageSpace()) {
1463 mod_union_table_->ClearCards(*it);
1464 timings.AddSplit("ModUnionClearCards");
1465 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1466 zygote_mod_union_table_->ClearCards(space);
1467 timings.AddSplit("ZygoteModUnionClearCards");
1468 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001469 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1470 // were dirty before the GC started.
1471 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1472 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001473 }
1474 }
1475}
1476
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001477void Heap::PreGcVerification(GarbageCollector* gc) {
1478 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1479 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001480
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001481 if (verify_pre_gc_heap_) {
1482 thread_list->SuspendAll();
1483 {
1484 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1485 if (!VerifyHeapReferences()) {
1486 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1487 }
1488 }
1489 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001490 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001491
1492 // Check that all objects which reference things in the live stack are on dirty cards.
1493 if (verify_missing_card_marks_) {
1494 thread_list->SuspendAll();
1495 {
1496 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1497 SwapStacks();
1498 // Sort the live stack so that we can quickly binary search it later.
1499 if (!VerifyMissingCardMarks()) {
1500 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1501 }
1502 SwapStacks();
1503 }
1504 thread_list->ResumeAll();
1505 }
1506
1507 if (verify_mod_union_table_) {
1508 thread_list->SuspendAll();
1509 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1510 zygote_mod_union_table_->Update();
1511 zygote_mod_union_table_->Verify();
1512 mod_union_table_->Update();
1513 mod_union_table_->Verify();
1514 thread_list->ResumeAll();
1515 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001516}
1517
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001518void Heap::PreSweepingGcVerification(GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001519 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001520 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001521
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001522 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1523 // reachable objects.
1524 if (verify_post_gc_heap_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001525 thread_list->SuspendAll();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001526 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1527 // Swapping bound bitmaps does nothing.
1528 live_bitmap_.swap(mark_bitmap_);
1529 if (!VerifyHeapReferences()) {
1530 LOG(FATAL) << "Post " << gc->GetName() << "Gc verification failed";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001531 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001532 live_bitmap_.swap(mark_bitmap_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001533 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001534 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001535}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001536
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001537void Heap::PostGcVerification(GarbageCollector* gc) {
1538 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001539
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001540 if (verify_system_weaks_) {
1541 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1542 MarkSweep* mark_sweep = down_cast<MarkSweep*>(gc);
1543 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001544 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001545}
1546
Ian Rogers81d425b2012-09-27 16:03:43 -07001547GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001548 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001549 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001550 bool do_wait;
1551 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001552 {
1553 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001554 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001555 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001556 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001558 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001559 // We must wait, change thread state then sleep on gc_complete_cond_;
1560 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1561 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001562 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001563 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001564 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001565 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001566 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001567 wait_time = NanoTime() - wait_start;;
1568 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001569 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001570 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001571 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1572 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001573 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001574 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001575 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001576}
1577
Elliott Hughesc967f782012-04-16 10:23:15 -07001578void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001579 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1580 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001581 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001582}
1583
1584size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001585 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001586}
1587
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001588void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001589 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001590 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001591 << PrettySize(GetMaxMemory());
1592 max_allowed_footprint = GetMaxMemory();
1593 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001594 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001595}
1596
Mathieu Chartier65db8802012-11-20 12:36:46 -08001597void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001598 // We know what our utilization is at this moment.
1599 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001600 const size_t bytes_allocated = GetBytesAllocated();
1601 last_gc_size_ = bytes_allocated;
1602 last_gc_time_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001603
Mathieu Chartier65db8802012-11-20 12:36:46 -08001604 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1605 if (target_size > bytes_allocated + max_free_) {
1606 target_size = bytes_allocated + max_free_;
1607 } else if (target_size < bytes_allocated + min_free_) {
1608 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001609 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001610
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001611 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001612
1613 // Calculate when to perform the next ConcurrentGC if we have enough free memory.
1614 if (concurrent_gc_ && GetFreeMemory() >= concurrent_min_free_) {
1615 // Calculate the estimated GC duration.
1616 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1617 // Estimate how many remaining bytes we will have when we need to start the next GC.
1618 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1619 if (remaining_bytes < max_allowed_footprint_) {
1620 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1621 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1622 // right away.
1623 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1624 } else {
1625 // The estimated rate is so high that we should request another GC straight away.
1626 concurrent_start_bytes_ = bytes_allocated;
1627 }
1628 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1629 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1630 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001631}
1632
jeffhaoc1160702011-10-27 15:48:45 -07001633void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001634 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001635 alloc_space_->ClearGrowthLimit();
1636}
1637
Elliott Hughesadb460d2011-10-05 17:02:34 -07001638void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001639 MemberOffset reference_queue_offset,
1640 MemberOffset reference_queueNext_offset,
1641 MemberOffset reference_pendingNext_offset,
1642 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001643 reference_referent_offset_ = reference_referent_offset;
1644 reference_queue_offset_ = reference_queue_offset;
1645 reference_queueNext_offset_ = reference_queueNext_offset;
1646 reference_pendingNext_offset_ = reference_pendingNext_offset;
1647 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1648 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1649 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1650 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1651 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1652 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1653}
1654
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001655mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001656 DCHECK(reference != NULL);
1657 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001658 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001659}
1660
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001661void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001662 DCHECK(reference != NULL);
1663 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1664 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1665}
1666
1667// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001668bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001669 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001670 const mirror::Object* queue =
1671 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1672 const mirror::Object* queue_next =
1673 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001674 return (queue != NULL) && (queue_next == NULL);
1675}
1676
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001677void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001678 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001679 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1680 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001681 EnqueuePendingReference(ref, cleared_reference_list);
1682}
1683
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001684void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001685 DCHECK(ref != NULL);
1686 DCHECK(list != NULL);
1687
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001688 // TODO: Remove this lock, use atomic stacks for storing references.
1689 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001690 if (*list == NULL) {
1691 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1692 *list = ref;
1693 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001694 mirror::Object* head =
1695 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001696 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1697 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1698 }
1699}
1700
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001701mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001702 DCHECK(list != NULL);
1703 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001704 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1705 false);
1706 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001707
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001708 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1709 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001710 if (*list == head) {
1711 ref = *list;
1712 *list = NULL;
1713 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001714 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1715 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001716 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1717 ref = head;
1718 }
1719 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1720 return ref;
1721}
1722
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001723void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001724 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001725 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001726 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001727 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1728 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001729}
1730
1731size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001732 return num_bytes_allocated_;
1733}
1734
1735size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001736 size_t total = 0;
1737 // TODO: C++0x
1738 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1739 Space* space = *it;
1740 if (space->IsAllocSpace()) {
1741 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1742 }
1743 }
1744 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001745}
1746
1747size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001748 return concurrent_start_size_;
1749}
1750
1751size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001752 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001753}
1754
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001755void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001756 DCHECK(cleared != NULL);
1757 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001758 // When a runtime isn't started there are no reference queues to care about so ignore.
1759 if (LIKELY(Runtime::Current()->IsStarted())) {
1760 ScopedObjectAccess soa(Thread::Current());
1761 JValue args[1];
1762 args[0].SetL(*cleared);
1763 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1764 args, NULL);
1765 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001766 *cleared = NULL;
1767 }
1768}
1769
Ian Rogers1f539342012-10-03 21:09:42 -07001770void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001771 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001772 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001773 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001774 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001775 !runtime->IsConcurrentGcEnabled()) {
1776 return;
1777 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001778 {
1779 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1780 if (runtime->IsShuttingDown()) {
1781 return;
1782 }
1783 }
1784 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001785 return;
1786 }
1787
Ian Rogers120f1c72012-09-28 17:17:10 -07001788 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001789 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1790 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001791 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1792 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001793 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001794}
1795
Ian Rogers81d425b2012-09-27 16:03:43 -07001796void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001797 {
1798 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001799 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001800 return;
1801 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001802 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001803
Mathieu Chartier65db8802012-11-20 12:36:46 -08001804 // Wait for any GCs currently running to finish.
Ian Rogers81d425b2012-09-27 16:03:43 -07001805 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001806 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001807 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001808 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001809 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001810 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001811 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001812}
1813
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001814void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001815 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1816 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1817 // a space it will hold its lock and can become a cause of jank.
1818 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1819 // forking.
1820
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001821 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1822 // because that only marks object heads, so a large array looks like lots of empty space. We
1823 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1824 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1825 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1826 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001827 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001828 float utilization =
1829 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1830 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1831 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1832 // heap trim occurred in the last two seconds.
1833 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001834 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001835
1836 Thread* self = Thread::Current();
1837 {
1838 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1839 Runtime* runtime = Runtime::Current();
1840 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1841 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1842 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1843 // as we don't hold the lock while requesting the trim).
1844 return;
1845 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001846 }
Ian Rogers48931882013-01-22 14:35:16 -08001847
1848 SchedPolicy policy;
1849 get_sched_policy(self->GetTid(), &policy);
1850 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1851 // Don't trim the heap if we are a foreground or audio app.
1852 return;
1853 }
1854
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001855 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001856 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001857 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1858 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001859 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1860 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001861 CHECK(!env->ExceptionCheck());
1862}
1863
Ian Rogers48931882013-01-22 14:35:16 -08001864size_t Heap::Trim() {
1865 // Handle a requested heap trim on a thread outside of the main GC thread.
1866 return alloc_space_->Trim();
1867}
1868
Carl Shapiro69759ea2011-07-21 18:13:35 -07001869} // namespace art