blob: 311052bfab4a623cd47c8bffc34228cc60c126d2 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070018
Brian Carlstrom5643b782012-02-05 12:32:53 -080019#include <sys/types.h>
20#include <sys/wait.h>
21
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
24
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
Ian Rogers48931882013-01-22 14:35:16 -080026#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070027#include "debugger.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070028#include "gc/atomic_stack.h"
29#include "gc/card_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "gc/card_table-inl.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070031#include "gc/heap_bitmap.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "gc/heap_bitmap-inl.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070033#include "gc/large_object_space.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070034#include "gc/mark_sweep.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "gc/mark_sweep-inl.h"
Mathieu Chartier2b82db42012-11-14 17:29:05 -080036#include "gc/partial_mark_sweep.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "gc/space_bitmap-inl.h"
Mathieu Chartier2b82db42012-11-14 17:29:05 -080038#include "gc/sticky_mark_sweep.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070039#include "gc/mod_union_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "gc/mod_union_table-inl.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070041#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070042#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080043#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/class-inl.h"
45#include "mirror/field-inl.h"
46#include "mirror/object.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080049#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080050#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070051#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070052#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070053#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070054#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070055#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070056#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070057
58namespace art {
59
Mathieu Chartier2b82db42012-11-14 17:29:05 -080060static const uint64_t kSlowGcThreshold = MsToNs(100);
61static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080062static const bool kDumpGcPerformanceOnShutdown = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070063const double Heap::kDefaultTargetUtilization = 0.5;
64
Elliott Hughesae80b492012-04-24 10:43:17 -070065static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080066 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080067 std::vector<std::string> boot_class_path;
68 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070069 if (boot_class_path.empty()) {
70 LOG(FATAL) << "Failed to generate image because no boot class path specified";
71 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080072
73 std::vector<char*> arg_vector;
74
75 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070076 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080077 const char* dex2oat = dex2oat_string.c_str();
78 arg_vector.push_back(strdup(dex2oat));
79
80 std::string image_option_string("--image=");
81 image_option_string += image_file_name;
82 const char* image_option = image_option_string.c_str();
83 arg_vector.push_back(strdup(image_option));
84
85 arg_vector.push_back(strdup("--runtime-arg"));
86 arg_vector.push_back(strdup("-Xms64m"));
87
88 arg_vector.push_back(strdup("--runtime-arg"));
89 arg_vector.push_back(strdup("-Xmx64m"));
90
91 for (size_t i = 0; i < boot_class_path.size(); i++) {
92 std::string dex_file_option_string("--dex-file=");
93 dex_file_option_string += boot_class_path[i];
94 const char* dex_file_option = dex_file_option_string.c_str();
95 arg_vector.push_back(strdup(dex_file_option));
96 }
97
98 std::string oat_file_option_string("--oat-file=");
99 oat_file_option_string += image_file_name;
100 oat_file_option_string.erase(oat_file_option_string.size() - 3);
101 oat_file_option_string += "oat";
102 const char* oat_file_option = oat_file_option_string.c_str();
103 arg_vector.push_back(strdup(oat_file_option));
104
jeffhao8161c032012-10-31 15:50:00 -0700105 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
106 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800107
Brian Carlstrom265091e2013-01-30 14:08:26 -0800108 if (!kIsTargetBuild) {
109 arg_vector.push_back(strdup("--host"));
110 }
111
Elliott Hughes48436bb2012-02-07 15:23:28 -0800112 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800113 LOG(INFO) << command_line;
114
Elliott Hughes48436bb2012-02-07 15:23:28 -0800115 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800116 char** argv = &arg_vector[0];
117
118 // fork and exec dex2oat
119 pid_t pid = fork();
120 if (pid == 0) {
121 // no allocation allowed between fork and exec
122
123 // change process groups, so we don't get reaped by ProcessManager
124 setpgid(0, 0);
125
126 execv(dex2oat, argv);
127
128 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
129 return false;
130 } else {
131 STLDeleteElements(&arg_vector);
132
133 // wait for dex2oat to finish
134 int status;
135 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
136 if (got_pid != pid) {
137 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
138 return false;
139 }
140 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
141 LOG(ERROR) << dex2oat << " failed: " << command_line;
142 return false;
143 }
144 }
145 return true;
146}
147
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700148void Heap::UnReserveOatFileAddressRange() {
149 oat_file_map_.reset(NULL);
150}
151
Mathieu Chartier0051be62012-10-12 17:47:11 -0700152Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
153 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700154 const std::string& original_image_file_name, bool concurrent_gc)
155 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800156 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700157 concurrent_gc_(concurrent_gc),
158 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800159 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700160 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700161 enforce_heap_growth_rate_(false),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800162 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700163 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700164 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700165 concurrent_start_size_(128 * KB),
166 concurrent_min_free_(256 * KB),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800167 concurrent_start_bytes_(concurrent_gc ? initial_size - concurrent_start_size_ :
168 std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700169 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700170 total_bytes_freed_(0),
171 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700172 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800173 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700174 verify_missing_card_marks_(false),
175 verify_system_weaks_(false),
176 verify_pre_gc_heap_(false),
177 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700178 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700179 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700180 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700181 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700182 last_trim_time_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800183 allocation_rate_(0),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700184 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800185 reference_referent_offset_(0),
186 reference_queue_offset_(0),
187 reference_queueNext_offset_(0),
188 reference_pendingNext_offset_(0),
189 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700190 min_free_(min_free),
191 max_free_(max_free),
192 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700193 total_wait_time_(0),
194 measure_allocation_time_(false),
195 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700196 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800197 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800198 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700199 }
200
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700201 live_bitmap_.reset(new HeapBitmap(this));
202 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700203
Ian Rogers30fab402012-01-23 15:43:46 -0800204 // Requested begin for the alloc space, to follow the mapped image and oat files
205 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800206 std::string image_file_name(original_image_file_name);
207 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700208 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700209
Brian Carlstrom5643b782012-02-05 12:32:53 -0800210 if (OS::FileExists(image_file_name.c_str())) {
211 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700212 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800213 } else {
214 // If the /system file didn't exist, we need to use one from the art-cache.
215 // If the cache file exists, try to open, but if it fails, regenerate.
216 // If it does not exist, generate.
217 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
218 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700219 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800220 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700221 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700222 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700223 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800224 }
225 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700226
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700227 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700228 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800229 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
230 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800231 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
232 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700233
234 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
235 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800236 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700237 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
238 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800239 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700240
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800241 if (oat_file_end_addr > requested_begin) {
242 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700243 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700244 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700245 }
246
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700247 // Allocate the large object space.
248 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700249 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
250 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
251
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700252 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
253 growth_limit, capacity,
254 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700255 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700256 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700257 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700258 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700259
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700260 // Spaces are sorted in order of Begin().
261 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700262 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
263 if (spaces_.back()->IsAllocSpace()) {
264 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
265 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700266
Ian Rogers30fab402012-01-23 15:43:46 -0800267 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700268 // TODO: C++0x
269 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
270 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800271 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700272 ImageSpace* image_space = space->AsImageSpace();
273 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800274 }
275 }
276
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800277 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700278 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
279 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700280
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700281 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
282 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700283
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700284 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
285 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700286
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700287 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700288 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700289
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800290 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700291 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogersa40307e2013-02-22 11:32:44 -0800292 mark_stack_.reset(ObjectStack::Create("mark stack", default_mark_stack_size));
293 allocation_stack_.reset(ObjectStack::Create("allocation stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700294 max_allocation_stack_size_));
Ian Rogersa40307e2013-02-22 11:32:44 -0800295 live_stack_.reset(ObjectStack::Create("live stack",
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700296 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700297
Mathieu Chartier65db8802012-11-20 12:36:46 -0800298 // It's still too early to take a lock because there are no threads yet, but we can create locks
299 // now. We don't create it earlier to make it clear that you can't use locks during heap
300 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700301 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700302 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
303 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700304
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700305 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
306 reference_queue_lock_.reset(new Mutex("reference queue lock"));
307
Mathieu Chartier65db8802012-11-20 12:36:46 -0800308 last_gc_time_ = NanoTime();
309 last_gc_size_ = GetBytesAllocated();
310
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800311 // Create our garbage collectors.
312 for (size_t i = 0; i < 2; ++i) {
313 const bool concurrent = i != 0;
314 mark_sweep_collectors_.push_back(new MarkSweep(this, concurrent));
315 mark_sweep_collectors_.push_back(new PartialMarkSweep(this, concurrent));
316 mark_sweep_collectors_.push_back(new StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700317 }
318
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800319 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800320 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800321 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700322 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700323}
324
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700325void Heap::CreateThreadPool() {
326 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
327 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
328 // workers to complete.
329 thread_pool_.reset(new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
330}
331
332void Heap::DeleteThreadPool() {
333 thread_pool_.reset(NULL);
334}
335
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700336// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700337struct SpaceSorter {
338 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700339 return a->Begin() < b->Begin();
340 }
341};
342
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700343void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700344 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700345 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700346 DCHECK(space->GetLiveBitmap() != NULL);
347 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700348 DCHECK(space->GetMarkBitmap() != NULL);
349 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800350 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700351 if (space->IsAllocSpace()) {
352 alloc_space_ = space->AsAllocSpace();
353 }
354
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700355 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
356 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700357
358 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
359 // avoid redundant marking.
360 bool seen_zygote = false, seen_alloc = false;
361 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
362 Space* space = *it;
363 if (space->IsImageSpace()) {
364 DCHECK(!seen_zygote);
365 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700366 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700367 DCHECK(!seen_alloc);
368 seen_zygote = true;
369 } else if (space->IsAllocSpace()) {
370 seen_alloc = true;
371 }
372 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800373}
374
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700375void Heap::DumpGcPerformanceInfo() {
376 // Dump cumulative timings.
377 LOG(INFO) << "Dumping cumulative Gc timings";
378 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800379
380 // Dump cumulative loggers for each GC type.
381 // TODO: C++0x
382 uint64_t total_paused_time = 0;
383 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800384 it != mark_sweep_collectors_.end(); ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800385 MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800386 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800387 if (logger.GetTotalNs() != 0) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800388 LOG(INFO) << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800389 const uint64_t total_ns = logger.GetTotalNs();
390 const uint64_t total_pause_ns = (*it)->GetTotalPausedTime();
391 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
392 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
393 const uint64_t freed_objects = collector->GetTotalFreedObjects();
394 LOG(INFO)
395 << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
396 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
397 << collector->GetName() << " freed: " << freed_objects
398 << " objects with total size " << PrettySize(freed_bytes) << "\n"
399 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
400 << PrettySize(freed_bytes / seconds) << "/s\n";
401 total_duration += total_ns;
402 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700403 }
404 }
405 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
406 size_t total_objects_allocated = GetTotalObjectsAllocated();
407 size_t total_bytes_allocated = GetTotalBytesAllocated();
408 if (total_duration != 0) {
409 const double total_seconds = double(total_duration / 1000) / 1000000.0;
410 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
411 LOG(INFO) << "Mean GC size throughput: "
412 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
Elliott Hughes80537bb2013-01-04 16:37:26 -0800413 LOG(INFO) << "Mean GC object throughput: "
414 << (GetTotalObjectsFreed() / total_seconds) << " objects/s";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700415 }
416 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
417 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
418 if (measure_allocation_time_) {
419 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
420 LOG(INFO) << "Mean allocation time: "
421 << PrettyDuration(allocation_time / total_objects_allocated);
422 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800423 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time);
Elliott Hughes80537bb2013-01-04 16:37:26 -0800424 LOG(INFO) << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700425}
426
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800427Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700428 if (kDumpGcPerformanceOnShutdown) {
429 DumpGcPerformanceInfo();
430 }
431
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800432 STLDeleteElements(&mark_sweep_collectors_);
433
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700434 // If we don't reset then the mark stack complains in it's destructor.
435 allocation_stack_->Reset();
436 live_stack_->Reset();
437
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800438 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800439 // We can't take the heap lock here because there might be a daemon thread suspended with the
440 // heap lock held. We know though that no non-daemon threads are executing, and we know that
441 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
442 // 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 -0700443 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700444 delete gc_complete_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700445}
446
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800447ContinuousSpace* Heap::FindSpaceFromObject(const mirror::Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700448 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700449 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
450 if ((*it)->Contains(obj)) {
451 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700452 }
453 }
454 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
455 return NULL;
456}
457
458ImageSpace* Heap::GetImageSpace() {
459 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700460 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
461 if ((*it)->IsImageSpace()) {
462 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700463 }
464 }
465 return NULL;
466}
467
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700468DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700469 return alloc_space_;
470}
471
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700472static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700473 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700474 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700475 size_t chunk_free_bytes = chunk_size - used_bytes;
476 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
477 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700478 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700479}
480
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800481mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
482 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700483 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
484 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800485 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700486
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800487 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700488 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700489 uint64_t allocation_start = 0;
490 if (measure_allocation_time_) {
491 allocation_start = NanoTime();
492 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700493
494 // We need to have a zygote space or else our newly allocated large object can end up in the
495 // Zygote resulting in it being prematurely freed.
496 // We can only do this for primive objects since large objects will not be within the card table
497 // range. This also means that we rely on SetClass not dirtying the object's card.
Brian Carlstrom84923ff2013-03-14 17:14:40 -0700498 //
499 // TODO: note "false && " to temporarily disable large object space
500 // due to issues on occam and mantaray. We were seeing objects in
501 // the large object space with NULL klass_ fields.
502 if (false && byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700503 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700504 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700505 // Make sure that our large object didn't get placed anywhere within the space interval or else
506 // it breaks the immune range.
507 DCHECK(obj == NULL ||
508 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
509 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700510 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700511 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700512
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700513 // Ensure that we did not allocate into a zygote space.
514 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
515 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700516 }
517
Mathieu Chartier037813d2012-08-23 16:44:59 -0700518 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700520
521 // Record allocation after since we want to use the atomic add for the atomic fence to guard
522 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700523 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700524
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700525 if (Dbg::IsAllocTrackingEnabled()) {
526 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700527 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700528 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700529 // We already have a request pending, no reason to start more until we update
530 // concurrent_start_bytes_.
531 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700532 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800533 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700534 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700535 }
536 VerifyObject(obj);
537
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700538 if (measure_allocation_time_) {
539 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
540 }
541
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700542 return obj;
543 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800544 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700545 int64_t total_bytes_free = GetFreeMemory();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800546 uint64_t alloc_space_size = alloc_space_->GetNumBytesAllocated();
547 uint64_t large_object_size = large_object_space_->GetNumObjectsAllocated();
548 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
549 << " free bytes; allocation space size " << alloc_space_size
550 << "; large object space size " << large_object_size;
551 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
552 if (total_bytes_free >= byte_count) {
553 size_t max_contiguous_allocation = 0;
554 // TODO: C++0x auto
555 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
556 if ((*it)->IsAllocSpace()) {
557 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
558 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700559 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800560 oss << "; failed due to fragmentation (largest possible contiguous allocation "
561 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700562 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800563 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700564 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700565}
566
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800567bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700568 // Note: we deliberately don't take the lock here, and mustn't test anything that would
569 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700570 if (obj == NULL) {
571 return true;
572 }
573 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700574 return false;
575 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800576 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800577 if (spaces_[i]->Contains(obj)) {
578 return true;
579 }
580 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700581 // Note: Doing this only works for the free list version of the large object space since the
582 // multiple memory map version uses a lock to do the contains check.
583 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700584}
585
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800586bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700587 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700588 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700589}
590
Elliott Hughes3e465b12011-09-02 18:26:12 -0700591#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700592void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700593 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700594 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700595 return;
596 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700597 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700598}
599#endif
600
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700601void Heap::DumpSpaces() {
602 // TODO: C++0x auto
603 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700604 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700605 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
606 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
607 LOG(INFO) << space << " " << *space << "\n"
608 << live_bitmap << " " << *live_bitmap << "\n"
609 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700610 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700611 if (large_object_space_.get() != NULL) {
612 large_object_space_->Dump(LOG(INFO));
613 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700614}
615
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800616void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700617 if (!IsAligned<kObjectAlignment>(obj)) {
618 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700619 }
620
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700621 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
622 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700623 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700624 // Check the allocation stack / live stack.
625 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
626 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
627 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700628 if (large_object_space_->GetLiveObjects()->Test(obj)) {
629 DumpSpaces();
630 LOG(FATAL) << "Object is dead: " << obj;
631 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700632 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700633 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700634
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700635 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700636 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700637 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800638 mirror::Object::ClassOffset().Int32Value();
639 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700640 if (c == NULL) {
641 LOG(FATAL) << "Null class in object: " << obj;
642 } else if (!IsAligned<kObjectAlignment>(c)) {
643 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
644 } else if (!GetLiveBitmap()->Test(c)) {
645 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
646 }
647 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
648 // Note: we don't use the accessors here as they have internal sanity checks
649 // that we don't want to run
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800650 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
651 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
652 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
653 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700654 CHECK_EQ(c_c, c_c_c);
655 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656}
657
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800658void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700659 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700660 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700661}
662
663void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700664 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700665 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700666}
667
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800668void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700669 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700670 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700671 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700672
673 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700674 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700675 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700676 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700677
678 // TODO: Update these atomically.
679 RuntimeStats* global_stats = Runtime::Current()->GetStats();
680 ++global_stats->allocated_objects;
681 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700682 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700683
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700684 // This is safe to do since the GC will never free objects which are neither in the allocation
685 // stack or the live bitmap.
686 while (!allocation_stack_->AtomicPushBack(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700687 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700688 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700689}
690
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700691void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700692 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
693 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700694
695 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700696 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700697 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700698 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700699
700 // TODO: Do this concurrently.
701 RuntimeStats* global_stats = Runtime::Current()->GetStats();
702 global_stats->freed_objects += freed_objects;
703 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700704 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700705}
706
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800707mirror::Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700708 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800709 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
710 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
711 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
712 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700713 return NULL;
714 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700715
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800716 if (enforce_heap_growth_rate_) {
717 if (grow) {
718 // Grow the heap by alloc_size extra bytes.
719 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
720 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
721 << " for a " << PrettySize(alloc_size) << " allocation";
722 } else {
723 return NULL;
724 }
725 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700726 }
727
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700728 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700729}
730
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800731mirror::Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700732 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
733 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700734 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700735 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700736
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800737 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700738 if (ptr != NULL) {
739 return ptr;
740 }
741
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700742 // The allocation failed. If the GC is running, block until it completes, and then retry the
743 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700744 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700745 if (last_gc != kGcTypeNone) {
746 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700747 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700748 if (ptr != NULL) {
749 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700750 }
751 }
752
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700753 // Loop through our different Gc types and try to Gc until we get enough free memory.
754 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
755 bool run_gc = false;
756 GcType gc_type = static_cast<GcType>(i);
757 switch (gc_type) {
758 case kGcTypeSticky: {
759 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700760 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
761 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700762 break;
763 }
764 case kGcTypePartial:
765 run_gc = have_zygote_space_;
766 break;
767 case kGcTypeFull:
768 run_gc = true;
769 break;
770 default:
771 break;
772 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700773
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700774 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700775 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700776 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800777 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700778 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700779
780 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700781 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700782 if (ptr != NULL) {
783 return ptr;
784 }
785 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700786 }
787
788 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700789 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700790 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700791 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700792 return ptr;
793 }
794
Elliott Hughes81ff3182012-03-23 20:35:56 -0700795 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
796 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
797 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700798
Elliott Hughes418dfe72011-10-06 18:56:27 -0700799 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700800 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
801 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700802
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700803 // We don't need a WaitForConcurrentGcToComplete here either.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700804 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700805 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700806}
807
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700808void Heap::SetTargetHeapUtilization(float target) {
809 DCHECK_GT(target, 0.0f); // asserted in Java code
810 DCHECK_LT(target, 1.0f);
811 target_utilization_ = target;
812}
813
814int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700815 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700816}
817
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700818int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700819 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700820}
821
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700822int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700823 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700824}
825
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700826size_t Heap::GetTotalBytesFreed() const {
827 return total_bytes_freed_;
828}
829
830size_t Heap::GetTotalObjectsFreed() const {
831 return total_objects_freed_;
832}
833
834size_t Heap::GetTotalObjectsAllocated() const {
835 size_t total = large_object_space_->GetTotalObjectsAllocated();
836 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
837 Space* space = *it;
838 if (space->IsAllocSpace()) {
839 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
840 }
841 }
842 return total;
843}
844
845size_t Heap::GetTotalBytesAllocated() const {
846 size_t total = large_object_space_->GetTotalBytesAllocated();
847 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
848 Space* space = *it;
849 if (space->IsAllocSpace()) {
850 total += space->AsAllocSpace()->GetTotalBytesAllocated();
851 }
852 }
853 return total;
854}
855
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700856class InstanceCounter {
857 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800858 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700859 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800860 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700861 }
862
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800863 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800864 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800865 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800866 if (use_is_assignable_from_) {
867 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
868 ++counts_[i];
869 }
870 } else {
871 if (instance_class == classes_[i]) {
872 ++counts_[i];
873 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700874 }
875 }
876 }
877
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700878 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800879 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800880 bool use_is_assignable_from_;
881 uint64_t* const counts_;
882
883 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700884};
885
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800886void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800887 uint64_t* counts) {
888 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
889 // is empty, so the live bitmap is the only place we need to look.
890 Thread* self = Thread::Current();
891 self->TransitionFromRunnableToSuspended(kNative);
892 CollectGarbage(false);
893 self->TransitionFromSuspendedToRunnable();
894
895 InstanceCounter counter(classes, use_is_assignable_from, counts);
896 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700897 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700898}
899
Elliott Hughes3b78c942013-01-15 17:35:41 -0800900class InstanceCollector {
901 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800902 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800903 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
904 : class_(c), max_count_(max_count), instances_(instances) {
905 }
906
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800907 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
908 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800909 if (instance_class == class_) {
910 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800911 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800912 }
913 }
914 }
915
916 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800917 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800918 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800919 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800920
921 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
922};
923
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800924void Heap::GetInstances(mirror::Class* c, int32_t max_count,
925 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800926 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
927 // is empty, so the live bitmap is the only place we need to look.
928 Thread* self = Thread::Current();
929 self->TransitionFromRunnableToSuspended(kNative);
930 CollectGarbage(false);
931 self->TransitionFromSuspendedToRunnable();
932
933 InstanceCollector collector(c, max_count, instances);
934 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
935 GetLiveBitmap()->Visit(collector);
936}
937
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800938class ReferringObjectsFinder {
939 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800940 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
941 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800942 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
943 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
944 }
945
946 // For bitmap Visit.
947 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
948 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800949 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800950 MarkSweep::VisitObjectReferences(o, *this);
951 }
952
953 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800954 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
955 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800956 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800957 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800958 }
959 }
960
961 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800962 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800963 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800964 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800965
966 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
967};
968
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800969void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
970 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800971 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
972 // is empty, so the live bitmap is the only place we need to look.
973 Thread* self = Thread::Current();
974 self->TransitionFromRunnableToSuspended(kNative);
975 CollectGarbage(false);
976 self->TransitionFromSuspendedToRunnable();
977
978 ReferringObjectsFinder finder(o, max_count, referring_objects);
979 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
980 GetLiveBitmap()->Visit(finder);
981}
982
Ian Rogers30fab402012-01-23 15:43:46 -0800983void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700984 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
985 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700986 Thread* self = Thread::Current();
987 WaitForConcurrentGcToComplete(self);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700988 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700989}
990
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700991void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700992 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800993 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
994 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700995 Thread* self = Thread::Current();
996 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700997
998 // Try to see if we have any Zygote spaces.
999 if (have_zygote_space_) {
1000 return;
1001 }
1002
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001003 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1004
1005 {
1006 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001007 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001008 FlushAllocStack();
1009 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001010
1011 // Replace the first alloc space we find with a zygote space.
1012 // TODO: C++0x auto
1013 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1014 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001015 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001016
1017 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1018 // of the remaining available heap memory.
1019 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001020 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001021
1022 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001023 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001024 AddSpace(alloc_space_);
1025 have_zygote_space_ = true;
1026 break;
1027 }
1028 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001029
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001030 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001031 // TODO: C++0x
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001032 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
1033 it != mark_sweep_collectors_.end(); ++it) {
1034 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001035 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001036}
1037
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001038void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001039 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1040 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001041 allocation_stack_->Reset();
1042}
1043
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001044size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001045 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001046}
1047
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001048void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001049 mirror::Object** limit = stack->End();
1050 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1051 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001052 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001053 if (LIKELY(bitmap->HasAddress(obj))) {
1054 bitmap->Set(obj);
1055 } else {
1056 large_objects->Set(obj);
1057 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001058 }
1059}
1060
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001061void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001062 mirror::Object** limit = stack->End();
1063 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1064 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001065 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001066 if (LIKELY(bitmap->HasAddress(obj))) {
1067 bitmap->Clear(obj);
1068 } else {
1069 large_objects->Clear(obj);
1070 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001071 }
1072}
1073
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001074GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001075 Thread* self = Thread::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001076 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001077 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001078
Ian Rogers120f1c72012-09-28 17:17:10 -07001079 if (self->IsHandlingStackOverflow()) {
1080 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1081 }
1082
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001083 // Ensure there is only one GC at a time.
1084 bool start_collect = false;
1085 while (!start_collect) {
1086 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001087 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001088 if (!is_gc_running_) {
1089 is_gc_running_ = true;
1090 start_collect = true;
1091 }
1092 }
1093 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001094 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001095 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1096 // Not doing at the moment to ensure soft references are cleared.
1097 }
1098 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001099 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001100
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001101 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1102 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1103 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1104 }
1105
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001106 // We need to do partial GCs every now and then to avoid the heap growing too much and
1107 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001108 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001109 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001110 }
Mathieu Chartier0325e622012-09-05 14:22:51 -07001111 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001112 sticky_gc_count_ = 0;
1113 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001114
Mathieu Chartier65db8802012-11-20 12:36:46 -08001115 uint64_t gc_start_time = NanoTime();
1116 uint64_t gc_start_size = GetBytesAllocated();
1117 // Approximate allocation rate in bytes / second.
Jeff Hao9bd02812013-02-08 14:29:50 -08001118 if (UNLIKELY(gc_start_time == last_gc_time_)) {
1119 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1120 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001121 uint64_t ms_delta = NsToMs(gc_start_time - last_gc_time_);
1122 if (ms_delta != 0) {
1123 allocation_rate_ = (gc_start_size - last_gc_size_) * 1000 / ms_delta;
1124 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1125 }
1126
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001127 DCHECK_LT(gc_type, kGcTypeMax);
1128 DCHECK_NE(gc_type, kGcTypeNone);
1129 MarkSweep* collector = NULL;
1130 for (Collectors::iterator it = mark_sweep_collectors_.begin();
1131 it != mark_sweep_collectors_.end(); ++it) {
1132 MarkSweep* cur_collector = *it;
1133 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1134 collector = cur_collector;
1135 break;
1136 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001137 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001138 CHECK(collector != NULL)
1139 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1140 << " and type=" << gc_type;
1141 collector->clear_soft_references_ = clear_soft_references;
1142 collector->Run();
1143 total_objects_freed_ += collector->GetFreedObjects();
1144 total_bytes_freed_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001145
Mathieu Chartier65db8802012-11-20 12:36:46 -08001146 const size_t duration = collector->GetDuration();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001147 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1148 bool was_slow = duration > kSlowGcThreshold ||
1149 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1150 for (size_t i = 0; i < pauses.size(); ++i) {
1151 if (pauses[i] > kLongGcPauseThreshold) {
1152 was_slow = true;
1153 }
1154 }
1155
1156 if (was_slow) {
1157 const size_t percent_free = GetPercentFree();
1158 const size_t current_heap_size = GetUsedMemorySize();
1159 const size_t total_memory = GetTotalMemory();
1160 std::ostringstream pause_string;
1161 for (size_t i = 0; i < pauses.size(); ++i) {
1162 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1163 << ((i != pauses.size() - 1) ? ", " : "");
1164 }
1165 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001166 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1167 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1168 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1169 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001170 if (VLOG_IS_ON(heap)) {
Sameer Abu Asala8439542013-02-14 16:06:42 -08001171 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001172 }
1173 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001174
Ian Rogers15bf2d32012-08-28 17:33:04 -07001175 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001176 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001177 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001178 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001179 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001180 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001181 }
1182 // Inform DDMS that a GC completed.
1183 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001184 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001185}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001186
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001187void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001188 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001189 // 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 -07001190 // cards.
1191 return;
1192 }
1193
1194 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001195 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001196 zygote_mod_union_table_->Update();
1197 timings.AddSplit("UpdateZygoteModUnionTable");
1198
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001199 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001200 timings.AddSplit("ZygoteMarkReferences");
1201 }
1202
1203 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1204 mod_union_table_->Update();
1205 timings.AddSplit("UpdateModUnionTable");
1206
1207 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001208 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001209 timings.AddSplit("MarkImageToAllocSpaceReferences");
1210}
1211
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001212void Heap::RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
1213 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001214 if (root == obj) {
1215 LOG(INFO) << "Object " << obj << " is a root";
1216 }
1217}
1218
1219class ScanVisitor {
1220 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001221 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001222 LOG(INFO) << "Would have rescanned object " << obj;
1223 }
1224};
1225
1226class VerifyReferenceVisitor {
1227 public:
1228 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1230 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001231 : heap_(heap),
1232 failed_(failed) {
1233 }
1234
1235 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1236 // analysis.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001237 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
1238 const MemberOffset& /* offset */, bool /* is_static */) const
1239 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240 // Verify that the reference is live.
1241 if (ref != NULL && !IsLive(ref)) {
1242 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001243 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1244 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001245
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001246 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001247 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1248 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1249 << "Obj type " << PrettyTypeOf(obj) << "\n"
1250 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001251 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001252 void* cover_begin = card_table->AddrFromCard(card_addr);
1253 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001254 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001255 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001256 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001257 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1258
1259 // Print out how the object is live.
1260 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001261 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1262 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001263 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1264 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1265 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001266 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1267 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001268 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001269 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001270 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001271 }
1272
1273 // Attempt to see if the card table missed the reference.
1274 ScanVisitor scan_visitor;
1275 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001276 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001277 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001278
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001279 // Search to see if any of the roots reference our object.
1280 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1281 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1282 *failed_ = true;
1283 }
1284 }
1285
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001286 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001287 if (heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001288 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001289 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001290 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001291 // 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 -08001292 // If the object is not either in the live bitmap or allocation stack, so the object must be
1293 // dead.
1294 return std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001295 }
1296
1297 private:
1298 Heap* heap_;
1299 bool* failed_;
1300};
1301
1302class VerifyObjectVisitor {
1303 public:
1304 VerifyObjectVisitor(Heap* heap)
1305 : heap_(heap),
1306 failed_(false) {
1307
1308 }
1309
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001310 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001311 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001312 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1313 MarkSweep::VisitObjectReferences(obj, visitor);
1314 }
1315
1316 bool Failed() const {
1317 return failed_;
1318 }
1319
1320 private:
1321 Heap* heap_;
1322 bool failed_;
1323};
1324
1325// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001326bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001327 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001328 // Lets sort our allocation stacks so that we can efficiently binary search them.
1329 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1330 std::sort(live_stack_->Begin(), live_stack_->End());
1331 // Perform the verification.
1332 VerifyObjectVisitor visitor(this);
1333 GetLiveBitmap()->Visit(visitor);
1334 // We don't want to verify the objects in the allocation stack since they themselves may be
1335 // pointing to dead objects if they are not reachable.
1336 if (visitor.Failed()) {
1337 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001338 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001339 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001340 return true;
1341}
1342
1343class VerifyReferenceCardVisitor {
1344 public:
1345 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1346 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1347 Locks::heap_bitmap_lock_)
1348 : heap_(heap),
1349 failed_(failed) {
1350 }
1351
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001352 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1353 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001354 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1355 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001356 // Filter out class references since changing an object's class does not mark the card as dirty.
1357 // Also handles large objects, since the only reference they hold is a class reference.
1358 if (ref != NULL && !ref->IsClass()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001359 CardTable* card_table = heap_->GetCardTable();
1360 // If the object is not dirty and it is referencing something in the live stack other than
1361 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001362 if (!card_table->AddrIsInCardTable(obj)) {
1363 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1364 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001365 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001366 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1367 // kCardDirty - 1 if it didnt get touched since we aged it.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001368 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001369 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001370 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1371 LOG(ERROR) << "Object " << obj << " found in live stack";
1372 }
1373 if (heap_->GetLiveBitmap()->Test(obj)) {
1374 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1375 }
1376 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1377 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1378
1379 // Print which field of the object is dead.
1380 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001381 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001382 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001383 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1384 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001385 CHECK(fields != NULL);
1386 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001387 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001388 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1389 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1390 << PrettyField(cur);
1391 break;
1392 }
1393 }
1394 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001395 const mirror::ObjectArray<mirror::Object>* object_array =
1396 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001397 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1398 if (object_array->Get(i) == ref) {
1399 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1400 }
1401 }
1402 }
1403
1404 *failed_ = true;
1405 }
1406 }
1407 }
1408 }
1409
1410 private:
1411 Heap* heap_;
1412 bool* failed_;
1413};
1414
1415class VerifyLiveStackReferences {
1416 public:
1417 VerifyLiveStackReferences(Heap* heap)
1418 : heap_(heap),
1419 failed_(false) {
1420
1421 }
1422
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001423 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001424 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1425 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1426 MarkSweep::VisitObjectReferences(obj, visitor);
1427 }
1428
1429 bool Failed() const {
1430 return failed_;
1431 }
1432
1433 private:
1434 Heap* heap_;
1435 bool failed_;
1436};
1437
1438bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001439 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001440
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001441 // We need to sort the live stack since we binary search it.
1442 std::sort(live_stack_->Begin(), live_stack_->End());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001443 VerifyLiveStackReferences visitor(this);
1444 GetLiveBitmap()->Visit(visitor);
1445
1446 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001447 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001448 visitor(*it);
1449 }
1450
1451 if (visitor.Failed()) {
1452 DumpSpaces();
1453 return false;
1454 }
1455 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001456}
1457
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001458void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001459 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001460
1461 // Sort the live stack so that we can quickly binary search it later.
1462 if (VERIFY_OBJECT_ENABLED) {
1463 std::sort(live_stack_->Begin(), live_stack_->End());
1464 }
1465}
1466
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001467void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001468 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1469 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1470 ContinuousSpace* space = *it;
1471 if (space->IsImageSpace()) {
1472 mod_union_table_->ClearCards(*it);
1473 timings.AddSplit("ModUnionClearCards");
1474 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1475 zygote_mod_union_table_->ClearCards(space);
1476 timings.AddSplit("ZygoteModUnionClearCards");
1477 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001478 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1479 // were dirty before the GC started.
1480 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1481 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001482 }
1483 }
1484}
1485
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001486void Heap::PreGcVerification(GarbageCollector* gc) {
1487 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1488 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001489
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001490 if (verify_pre_gc_heap_) {
1491 thread_list->SuspendAll();
1492 {
1493 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1494 if (!VerifyHeapReferences()) {
1495 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1496 }
1497 }
1498 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001499 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001500
1501 // Check that all objects which reference things in the live stack are on dirty cards.
1502 if (verify_missing_card_marks_) {
1503 thread_list->SuspendAll();
1504 {
1505 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1506 SwapStacks();
1507 // Sort the live stack so that we can quickly binary search it later.
1508 if (!VerifyMissingCardMarks()) {
1509 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1510 }
1511 SwapStacks();
1512 }
1513 thread_list->ResumeAll();
1514 }
1515
1516 if (verify_mod_union_table_) {
1517 thread_list->SuspendAll();
1518 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1519 zygote_mod_union_table_->Update();
1520 zygote_mod_union_table_->Verify();
1521 mod_union_table_->Update();
1522 mod_union_table_->Verify();
1523 thread_list->ResumeAll();
1524 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001525}
1526
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001527void Heap::PreSweepingGcVerification(GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001528 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001529 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001530
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001531 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1532 // reachable objects.
1533 if (verify_post_gc_heap_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001534 thread_list->SuspendAll();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001535 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1536 // Swapping bound bitmaps does nothing.
1537 live_bitmap_.swap(mark_bitmap_);
1538 if (!VerifyHeapReferences()) {
1539 LOG(FATAL) << "Post " << gc->GetName() << "Gc verification failed";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001541 live_bitmap_.swap(mark_bitmap_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001542 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001543 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001544}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001545
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001546void Heap::PostGcVerification(GarbageCollector* gc) {
1547 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001548
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001549 if (verify_system_weaks_) {
1550 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1551 MarkSweep* mark_sweep = down_cast<MarkSweep*>(gc);
1552 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001553 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001554}
1555
Ian Rogers81d425b2012-09-27 16:03:43 -07001556GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001557 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001558 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001559 bool do_wait;
1560 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001561 {
1562 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001563 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001564 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001565 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001566 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001567 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001568 // We must wait, change thread state then sleep on gc_complete_cond_;
1569 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1570 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001571 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001572 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001573 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001574 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001575 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001576 wait_time = NanoTime() - wait_start;;
1577 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001578 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001579 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001580 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1581 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001582 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001583 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001584 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001585}
1586
Elliott Hughesc967f782012-04-16 10:23:15 -07001587void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001588 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1589 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001590 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001591}
1592
1593size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001594 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001595}
1596
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001597void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001598 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001599 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001600 << PrettySize(GetMaxMemory());
1601 max_allowed_footprint = GetMaxMemory();
1602 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001603 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001604}
1605
Mathieu Chartier65db8802012-11-20 12:36:46 -08001606void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001607 // We know what our utilization is at this moment.
1608 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001609 const size_t bytes_allocated = GetBytesAllocated();
1610 last_gc_size_ = bytes_allocated;
1611 last_gc_time_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001612
Mathieu Chartier65db8802012-11-20 12:36:46 -08001613 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1614 if (target_size > bytes_allocated + max_free_) {
1615 target_size = bytes_allocated + max_free_;
1616 } else if (target_size < bytes_allocated + min_free_) {
1617 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001618 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001619
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001620 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001621
1622 // Calculate when to perform the next ConcurrentGC if we have enough free memory.
1623 if (concurrent_gc_ && GetFreeMemory() >= concurrent_min_free_) {
1624 // Calculate the estimated GC duration.
1625 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1626 // Estimate how many remaining bytes we will have when we need to start the next GC.
1627 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1628 if (remaining_bytes < max_allowed_footprint_) {
1629 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1630 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1631 // right away.
1632 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1633 } else {
1634 // The estimated rate is so high that we should request another GC straight away.
1635 concurrent_start_bytes_ = bytes_allocated;
1636 }
1637 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1638 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1639 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001640}
1641
jeffhaoc1160702011-10-27 15:48:45 -07001642void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001643 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001644 alloc_space_->ClearGrowthLimit();
1645}
1646
Elliott Hughesadb460d2011-10-05 17:02:34 -07001647void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001648 MemberOffset reference_queue_offset,
1649 MemberOffset reference_queueNext_offset,
1650 MemberOffset reference_pendingNext_offset,
1651 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001652 reference_referent_offset_ = reference_referent_offset;
1653 reference_queue_offset_ = reference_queue_offset;
1654 reference_queueNext_offset_ = reference_queueNext_offset;
1655 reference_pendingNext_offset_ = reference_pendingNext_offset;
1656 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1657 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1658 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1659 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1660 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1661 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1662}
1663
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001664mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001665 DCHECK(reference != NULL);
1666 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001667 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001668}
1669
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001670void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001671 DCHECK(reference != NULL);
1672 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1673 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1674}
1675
1676// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001677bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001678 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001679 const mirror::Object* queue =
1680 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1681 const mirror::Object* queue_next =
1682 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001683 return (queue != NULL) && (queue_next == NULL);
1684}
1685
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001686void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001687 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001688 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1689 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001690 EnqueuePendingReference(ref, cleared_reference_list);
1691}
1692
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001693void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001694 DCHECK(ref != NULL);
1695 DCHECK(list != NULL);
1696
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001697 // TODO: Remove this lock, use atomic stacks for storing references.
1698 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001699 if (*list == NULL) {
1700 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1701 *list = ref;
1702 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001703 mirror::Object* head =
1704 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001705 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1706 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1707 }
1708}
1709
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001710mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001711 DCHECK(list != NULL);
1712 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001713 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1714 false);
1715 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001716
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001717 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1718 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001719 if (*list == head) {
1720 ref = *list;
1721 *list = NULL;
1722 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001723 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1724 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001725 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1726 ref = head;
1727 }
1728 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1729 return ref;
1730}
1731
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001732void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001733 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001734 JValue result;
1735 JValue float_result;
1736 ArgArray arg_array(NULL, 0);
1737 arg_array.Append(reinterpret_cast<uint32_t>(object));
1738 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
1739 arg_array.GetArray(), arg_array.GetNumBytes(), &result, &float_result);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001740}
1741
1742size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001743 return num_bytes_allocated_;
1744}
1745
1746size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001747 size_t total = 0;
1748 // TODO: C++0x
1749 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1750 Space* space = *it;
1751 if (space->IsAllocSpace()) {
1752 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1753 }
1754 }
1755 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001756}
1757
1758size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001759 return concurrent_start_size_;
1760}
1761
1762size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001763 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001764}
1765
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001766void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001767 DCHECK(cleared != NULL);
1768 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001769 // When a runtime isn't started there are no reference queues to care about so ignore.
1770 if (LIKELY(Runtime::Current()->IsStarted())) {
1771 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001772 JValue result;
1773 JValue float_result;
1774 ArgArray arg_array(NULL, 0);
1775 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1776 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
1777 arg_array.GetArray(), arg_array.GetNumBytes(), &result, &float_result);
Ian Rogers64b6d142012-10-29 16:34:15 -07001778 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001779 *cleared = NULL;
1780 }
1781}
1782
Ian Rogers1f539342012-10-03 21:09:42 -07001783void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001784 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001785 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001786 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001787 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001788 !runtime->IsConcurrentGcEnabled()) {
1789 return;
1790 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001791 {
1792 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1793 if (runtime->IsShuttingDown()) {
1794 return;
1795 }
1796 }
1797 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001798 return;
1799 }
1800
Ian Rogers120f1c72012-09-28 17:17:10 -07001801 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001802 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1803 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001804 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1805 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001806 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001807}
1808
Ian Rogers81d425b2012-09-27 16:03:43 -07001809void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001810 {
1811 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001812 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001813 return;
1814 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001815 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001816
Mathieu Chartier65db8802012-11-20 12:36:46 -08001817 // Wait for any GCs currently running to finish.
Ian Rogers81d425b2012-09-27 16:03:43 -07001818 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001819 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001820 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001821 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001822 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001823 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001824 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001825}
1826
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001827void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001828 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1829 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1830 // a space it will hold its lock and can become a cause of jank.
1831 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1832 // forking.
1833
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001834 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1835 // because that only marks object heads, so a large array looks like lots of empty space. We
1836 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1837 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1838 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1839 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001840 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001841 float utilization =
1842 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1843 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1844 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1845 // heap trim occurred in the last two seconds.
1846 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001847 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001848
1849 Thread* self = Thread::Current();
1850 {
1851 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1852 Runtime* runtime = Runtime::Current();
1853 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1854 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1855 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1856 // as we don't hold the lock while requesting the trim).
1857 return;
1858 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001859 }
Ian Rogers48931882013-01-22 14:35:16 -08001860
1861 SchedPolicy policy;
1862 get_sched_policy(self->GetTid(), &policy);
1863 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1864 // Don't trim the heap if we are a foreground or audio app.
1865 return;
1866 }
1867
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001868 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001869 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001870 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1871 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001872 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1873 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001874 CHECK(!env->ExceptionCheck());
1875}
1876
Ian Rogers48931882013-01-22 14:35:16 -08001877size_t Heap::Trim() {
1878 // Handle a requested heap trim on a thread outside of the main GC thread.
1879 return alloc_space_->Trim();
1880}
1881
Carl Shapiro69759ea2011-07-21 18:13:35 -07001882} // namespace art