blob: 645d4021e848b729ea593e15d958726179bd26e3 [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 Hughes767a1472011-10-26 18:49:02 -070025#include "debugger.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070026#include "gc/atomic_stack.h"
27#include "gc/card_table.h"
28#include "gc/heap_bitmap.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070029#include "gc/large_object_space.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070030#include "gc/mark_sweep.h"
Mathieu Chartier2b82db42012-11-14 17:29:05 -080031#include "gc/partial_mark_sweep.h"
32#include "gc/sticky_mark_sweep.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070033#include "gc/mod_union_table.h"
34#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070035#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070036#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080037#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080038#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070039#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070040#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070041#include "sirt_ref.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070042#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070043#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070044#include "timing_logger.h"
45#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070046#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070047
48namespace art {
49
Mathieu Chartier2b82db42012-11-14 17:29:05 -080050static const uint64_t kSlowGcThreshold = MsToNs(100);
51static const uint64_t kLongGcPauseThreshold = MsToNs(5);
52static const bool kDumpGcPerformanceOnShutdown = true;
Mathieu Chartier0051be62012-10-12 17:47:11 -070053const double Heap::kDefaultTargetUtilization = 0.5;
54
Elliott Hughesae80b492012-04-24 10:43:17 -070055static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080056 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080057 std::vector<std::string> boot_class_path;
58 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070059 if (boot_class_path.empty()) {
60 LOG(FATAL) << "Failed to generate image because no boot class path specified";
61 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080062
63 std::vector<char*> arg_vector;
64
65 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070066 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080067 const char* dex2oat = dex2oat_string.c_str();
68 arg_vector.push_back(strdup(dex2oat));
69
70 std::string image_option_string("--image=");
71 image_option_string += image_file_name;
72 const char* image_option = image_option_string.c_str();
73 arg_vector.push_back(strdup(image_option));
74
75 arg_vector.push_back(strdup("--runtime-arg"));
76 arg_vector.push_back(strdup("-Xms64m"));
77
78 arg_vector.push_back(strdup("--runtime-arg"));
79 arg_vector.push_back(strdup("-Xmx64m"));
80
81 for (size_t i = 0; i < boot_class_path.size(); i++) {
82 std::string dex_file_option_string("--dex-file=");
83 dex_file_option_string += boot_class_path[i];
84 const char* dex_file_option = dex_file_option_string.c_str();
85 arg_vector.push_back(strdup(dex_file_option));
86 }
87
88 std::string oat_file_option_string("--oat-file=");
89 oat_file_option_string += image_file_name;
90 oat_file_option_string.erase(oat_file_option_string.size() - 3);
91 oat_file_option_string += "oat";
92 const char* oat_file_option = oat_file_option_string.c_str();
93 arg_vector.push_back(strdup(oat_file_option));
94
jeffhao8161c032012-10-31 15:50:00 -070095 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
96 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -080097
Elliott Hughes48436bb2012-02-07 15:23:28 -080098 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080099 LOG(INFO) << command_line;
100
Elliott Hughes48436bb2012-02-07 15:23:28 -0800101 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800102 char** argv = &arg_vector[0];
103
104 // fork and exec dex2oat
105 pid_t pid = fork();
106 if (pid == 0) {
107 // no allocation allowed between fork and exec
108
109 // change process groups, so we don't get reaped by ProcessManager
110 setpgid(0, 0);
111
112 execv(dex2oat, argv);
113
114 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
115 return false;
116 } else {
117 STLDeleteElements(&arg_vector);
118
119 // wait for dex2oat to finish
120 int status;
121 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
122 if (got_pid != pid) {
123 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
124 return false;
125 }
126 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
127 LOG(ERROR) << dex2oat << " failed: " << command_line;
128 return false;
129 }
130 }
131 return true;
132}
133
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700134void Heap::UnReserveOatFileAddressRange() {
135 oat_file_map_.reset(NULL);
136}
137
Mathieu Chartier0051be62012-10-12 17:47:11 -0700138Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
139 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700140 const std::string& original_image_file_name, bool concurrent_gc)
141 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800142 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700143 concurrent_gc_(concurrent_gc),
144 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800145 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700146 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700147 enforce_heap_growth_rate_(false),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700148 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700149 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700150 concurrent_start_size_(128 * KB),
151 concurrent_min_free_(256 * KB),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700152 concurrent_start_bytes_(initial_size - concurrent_start_size_),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700153 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700154 total_bytes_freed_(0),
155 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700156 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800157 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700158 verify_missing_card_marks_(false),
159 verify_system_weaks_(false),
160 verify_pre_gc_heap_(false),
161 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700162 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700163 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700164 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700165 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700166 last_trim_time_(0),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700167 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800168 reference_referent_offset_(0),
169 reference_queue_offset_(0),
170 reference_queueNext_offset_(0),
171 reference_pendingNext_offset_(0),
172 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700173 min_free_(min_free),
174 max_free_(max_free),
175 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700176 total_wait_time_(0),
177 measure_allocation_time_(false),
178 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700179 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800180 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800181 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700182 }
183
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700184 live_bitmap_.reset(new HeapBitmap(this));
185 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700186
Ian Rogers30fab402012-01-23 15:43:46 -0800187 // Requested begin for the alloc space, to follow the mapped image and oat files
188 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800189 std::string image_file_name(original_image_file_name);
190 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700191 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700192
Brian Carlstrom5643b782012-02-05 12:32:53 -0800193 if (OS::FileExists(image_file_name.c_str())) {
194 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700195 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800196 } else {
197 // If the /system file didn't exist, we need to use one from the art-cache.
198 // If the cache file exists, try to open, but if it fails, regenerate.
199 // If it does not exist, generate.
200 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
201 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700202 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800203 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700204 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700205 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700206 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800207 }
208 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700209
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700210 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700211 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800212 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
213 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700214 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
215 CHECK_GT(oat_end_addr, image_space->End());
216
217 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
218 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
219 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
220 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
221 reinterpret_cast<byte*>(reserve_begin),
222 reserve_end - reserve_begin, PROT_READ));
223
Ian Rogers30fab402012-01-23 15:43:46 -0800224 if (oat_end_addr > requested_begin) {
225 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700226 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700227 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700228 }
229
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700230 // Allocate the large object space.
231 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700232 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
233 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
234
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700235 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
236 growth_limit, capacity,
237 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700238 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700239 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700240 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700241 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700242
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700243 // Spaces are sorted in order of Begin().
244 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700245 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
246 if (spaces_.back()->IsAllocSpace()) {
247 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
248 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700249
Ian Rogers30fab402012-01-23 15:43:46 -0800250 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700251 // TODO: C++0x
252 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
253 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800254 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700255 ImageSpace* image_space = space->AsImageSpace();
256 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800257 }
258 }
259
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800260 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700261 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
262 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700263
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700264 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
265 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700266
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700267 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
268 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700269
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700270 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700271 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700272
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800273 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700274 static const size_t default_mark_stack_size = 64 * KB;
275 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
276 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700277 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700278 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
279 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700280
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800281 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700282 // but we can create the heap lock now. We don't create it earlier to
283 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700284 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700285 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
286 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700287
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700288 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
289 reference_queue_lock_.reset(new Mutex("reference queue lock"));
290
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800291 // Create our garbage collectors.
292 for (size_t i = 0; i < 2; ++i) {
293 const bool concurrent = i != 0;
294 mark_sweep_collectors_.push_back(new MarkSweep(this, concurrent));
295 mark_sweep_collectors_.push_back(new PartialMarkSweep(this, concurrent));
296 mark_sweep_collectors_.push_back(new StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700297 }
298
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800299 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800300 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800301 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700302 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700303}
304
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700305void Heap::CreateThreadPool() {
306 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
307 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
308 // workers to complete.
309 thread_pool_.reset(new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
310}
311
312void Heap::DeleteThreadPool() {
313 thread_pool_.reset(NULL);
314}
315
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700316// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700317struct SpaceSorter {
318 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700319 return a->Begin() < b->Begin();
320 }
321};
322
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700323void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700324 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700325 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700326 DCHECK(space->GetLiveBitmap() != NULL);
327 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700328 DCHECK(space->GetMarkBitmap() != NULL);
329 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800330 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700331 if (space->IsAllocSpace()) {
332 alloc_space_ = space->AsAllocSpace();
333 }
334
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700335 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
336 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700337
338 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
339 // avoid redundant marking.
340 bool seen_zygote = false, seen_alloc = false;
341 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
342 Space* space = *it;
343 if (space->IsImageSpace()) {
344 DCHECK(!seen_zygote);
345 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700346 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700347 DCHECK(!seen_alloc);
348 seen_zygote = true;
349 } else if (space->IsAllocSpace()) {
350 seen_alloc = true;
351 }
352 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800353}
354
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700355void Heap::DumpGcPerformanceInfo() {
356 // Dump cumulative timings.
357 LOG(INFO) << "Dumping cumulative Gc timings";
358 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800359
360 // Dump cumulative loggers for each GC type.
361 // TODO: C++0x
362 uint64_t total_paused_time = 0;
363 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
364 it != mark_sweep_collectors_.end(); ++it) {
365 MarkSweep* collector = *it;
366 const CumulativeLogger& logger = collector->GetCumulativeTimings();
367 if (logger.GetTotalNs() != 0) {
368 logger.Dump();
369 const uint64_t total_ns = logger.GetTotalNs();
370 const uint64_t total_pause_ns = (*it)->GetTotalPausedTime();
371 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
372 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
373 const uint64_t freed_objects = collector->GetTotalFreedObjects();
374 LOG(INFO)
375 << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
376 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
377 << collector->GetName() << " freed: " << freed_objects
378 << " objects with total size " << PrettySize(freed_bytes) << "\n"
379 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
380 << PrettySize(freed_bytes / seconds) << "/s\n";
381 total_duration += total_ns;
382 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700383 }
384 }
385 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
386 size_t total_objects_allocated = GetTotalObjectsAllocated();
387 size_t total_bytes_allocated = GetTotalBytesAllocated();
388 if (total_duration != 0) {
389 const double total_seconds = double(total_duration / 1000) / 1000000.0;
390 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
391 LOG(INFO) << "Mean GC size throughput: "
392 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
393 LOG(INFO) << "Mean GC object throughput: " << GetTotalObjectsFreed() / total_seconds << "/s";
394 }
395 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
396 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
397 if (measure_allocation_time_) {
398 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
399 LOG(INFO) << "Mean allocation time: "
400 << PrettyDuration(allocation_time / total_objects_allocated);
401 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800402 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time);
403 LOG(INFO) << "Total time waiting for GC to complete time: " << PrettyDuration(total_wait_time_);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700404}
405
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800406Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700407 if (kDumpGcPerformanceOnShutdown) {
408 DumpGcPerformanceInfo();
409 }
410
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800411 STLDeleteElements(&mark_sweep_collectors_);
412
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700413 // If we don't reset then the mark stack complains in it's destructor.
414 allocation_stack_->Reset();
415 live_stack_->Reset();
416
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800417 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800418 // We can't take the heap lock here because there might be a daemon thread suspended with the
419 // heap lock held. We know though that no non-daemon threads are executing, and we know that
420 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
421 // 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 -0700422 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700423 delete gc_complete_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700424}
425
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700426ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700427 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700428 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
429 if ((*it)->Contains(obj)) {
430 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700431 }
432 }
433 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
434 return NULL;
435}
436
437ImageSpace* Heap::GetImageSpace() {
438 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700439 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
440 if ((*it)->IsImageSpace()) {
441 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700442 }
443 }
444 return NULL;
445}
446
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700447DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700448 return alloc_space_;
449}
450
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700451static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700452 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700453 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700454 size_t chunk_free_bytes = chunk_size - used_bytes;
455 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
456 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700457 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700458}
459
Ian Rogers50b35e22012-10-04 10:09:15 -0700460Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
462 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
463 strlen(ClassHelper(c).GetDescriptor()) == 0);
464 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700465
466 Object* obj = NULL;
467 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700468 uint64_t allocation_start = 0;
469 if (measure_allocation_time_) {
470 allocation_start = NanoTime();
471 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700472
473 // We need to have a zygote space or else our newly allocated large object can end up in the
474 // Zygote resulting in it being prematurely freed.
475 // We can only do this for primive objects since large objects will not be within the card table
476 // range. This also means that we rely on SetClass not dirtying the object's card.
477 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700478 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700479 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700480 // Make sure that our large object didn't get placed anywhere within the space interval or else
481 // it breaks the immune range.
482 DCHECK(obj == NULL ||
483 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
484 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700485 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700486 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700487
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700488 // Ensure that we did not allocate into a zygote space.
489 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
490 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700491 }
492
Mathieu Chartier037813d2012-08-23 16:44:59 -0700493 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700494 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700495
496 // Record allocation after since we want to use the atomic add for the atomic fence to guard
497 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700498 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700499
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500 if (Dbg::IsAllocTrackingEnabled()) {
501 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700502 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700503 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700504 // We already have a request pending, no reason to start more until we update
505 // concurrent_start_bytes_.
506 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700507 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700508 SirtRef<Object> ref(self, obj);
509 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510 }
511 VerifyObject(obj);
512
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700513 if (measure_allocation_time_) {
514 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
515 }
516
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700517 return obj;
518 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700519 int64_t total_bytes_free = GetFreeMemory();
520 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700521 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700522 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
523 if ((*it)->IsAllocSpace()) {
524 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700525 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700526 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700527
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700528 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700529 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700530 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700531 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700532}
533
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700534bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700535 // Note: we deliberately don't take the lock here, and mustn't test anything that would
536 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700537 if (obj == NULL) {
538 return true;
539 }
540 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700541 return false;
542 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800543 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800544 if (spaces_[i]->Contains(obj)) {
545 return true;
546 }
547 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700548 // Note: Doing this only works for the free list version of the large object space since the
549 // multiple memory map version uses a lock to do the contains check.
550 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700551}
552
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700553bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700554 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700555 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700556}
557
Elliott Hughes3e465b12011-09-02 18:26:12 -0700558#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700560 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700561 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700562 return;
563 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700564 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700565}
566#endif
567
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700568void Heap::DumpSpaces() {
569 // TODO: C++0x auto
570 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700571 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700572 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
573 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
574 LOG(INFO) << space << " " << *space << "\n"
575 << live_bitmap << " " << *live_bitmap << "\n"
576 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700577 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700578 if (large_object_space_.get() != NULL) {
579 large_object_space_->Dump(LOG(INFO));
580 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700581}
582
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700583void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700584 if (!IsAligned<kObjectAlignment>(obj)) {
585 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700586 }
587
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700588 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
589 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700590 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700591 // Check the allocation stack / live stack.
592 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
593 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
594 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700595 if (large_object_space_->GetLiveObjects()->Test(obj)) {
596 DumpSpaces();
597 LOG(FATAL) << "Object is dead: " << obj;
598 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700599 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700600 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700601
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700602 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700603 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700604 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
605 Object::ClassOffset().Int32Value();
606 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
607 if (c == NULL) {
608 LOG(FATAL) << "Null class in object: " << obj;
609 } else if (!IsAligned<kObjectAlignment>(c)) {
610 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
611 } else if (!GetLiveBitmap()->Test(c)) {
612 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
613 }
614 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
615 // Note: we don't use the accessors here as they have internal sanity checks
616 // that we don't want to run
617 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
618 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
619 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
620 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
621 CHECK_EQ(c_c, c_c_c);
622 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700623}
624
Brian Carlstrom78128a62011-09-15 17:21:19 -0700625void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700626 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700627 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700628}
629
630void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700631 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700632 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700633}
634
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700635void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700636 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700637 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700638 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700639
640 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700641 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700642 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700643 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700644
645 // TODO: Update these atomically.
646 RuntimeStats* global_stats = Runtime::Current()->GetStats();
647 ++global_stats->allocated_objects;
648 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700649 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700650
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700651 // This is safe to do since the GC will never free objects which are neither in the allocation
652 // stack or the live bitmap.
653 while (!allocation_stack_->AtomicPushBack(obj)) {
654 Thread* self = Thread::Current();
655 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700656 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
657 self->TransitionFromSuspendedToRunnable();
658 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700659}
660
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700661void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700662 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
663 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700664
665 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700666 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700667 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700668 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700669
670 // TODO: Do this concurrently.
671 RuntimeStats* global_stats = Runtime::Current()->GetStats();
672 global_stats->freed_objects += freed_objects;
673 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700674 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700675}
676
Ian Rogers50b35e22012-10-04 10:09:15 -0700677Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700678 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800679 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
680 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
681 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
682 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700683 return NULL;
684 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700685
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800686 if (enforce_heap_growth_rate_) {
687 if (grow) {
688 // Grow the heap by alloc_size extra bytes.
689 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
690 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
691 << " for a " << PrettySize(alloc_size) << " allocation";
692 } else {
693 return NULL;
694 }
695 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700696 }
697
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700698 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700699}
700
Ian Rogers50b35e22012-10-04 10:09:15 -0700701Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700702 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
703 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700704 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700705 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700706
Ian Rogers50b35e22012-10-04 10:09:15 -0700707 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700708 if (ptr != NULL) {
709 return ptr;
710 }
711
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700712 // The allocation failed. If the GC is running, block until it completes, and then retry the
713 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700714 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700715 if (last_gc != kGcTypeNone) {
716 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700717 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700718 if (ptr != NULL) {
719 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700720 }
721 }
722
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700723 // Loop through our different Gc types and try to Gc until we get enough free memory.
724 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
725 bool run_gc = false;
726 GcType gc_type = static_cast<GcType>(i);
727 switch (gc_type) {
728 case kGcTypeSticky: {
729 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700730 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
731 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700732 break;
733 }
734 case kGcTypePartial:
735 run_gc = have_zygote_space_;
736 break;
737 case kGcTypeFull:
738 run_gc = true;
739 break;
740 default:
741 break;
742 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700743
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700744 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700745 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
746
747 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700748 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700749 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
750 i = static_cast<size_t>(gc_type_ran);
751 self->TransitionFromSuspendedToRunnable();
752
753 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700754 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700755 if (ptr != NULL) {
756 return ptr;
757 }
758 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700759 }
760
761 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700762 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700763 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700764 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700765 return ptr;
766 }
767
Elliott Hughes81ff3182012-03-23 20:35:56 -0700768 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
769 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
770 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700771
Elliott Hughes418dfe72011-10-06 18:56:27 -0700772 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700773 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
774 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700775
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700776 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700777 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700778 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700779 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700780 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700781}
782
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700783void Heap::SetTargetHeapUtilization(float target) {
784 DCHECK_GT(target, 0.0f); // asserted in Java code
785 DCHECK_LT(target, 1.0f);
786 target_utilization_ = target;
787}
788
789int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700790 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700791}
792
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700793int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700794 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700795}
796
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700797int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700798 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700799}
800
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700801size_t Heap::GetTotalBytesFreed() const {
802 return total_bytes_freed_;
803}
804
805size_t Heap::GetTotalObjectsFreed() const {
806 return total_objects_freed_;
807}
808
809size_t Heap::GetTotalObjectsAllocated() const {
810 size_t total = large_object_space_->GetTotalObjectsAllocated();
811 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
812 Space* space = *it;
813 if (space->IsAllocSpace()) {
814 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
815 }
816 }
817 return total;
818}
819
820size_t Heap::GetTotalBytesAllocated() const {
821 size_t total = large_object_space_->GetTotalBytesAllocated();
822 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
823 Space* space = *it;
824 if (space->IsAllocSpace()) {
825 total += space->AsAllocSpace()->GetTotalBytesAllocated();
826 }
827 }
828 return total;
829}
830
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700831class InstanceCounter {
832 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700833 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700834 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700835 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700836
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700837 }
838
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700839 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
840 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700841 if (count_assignable_) {
842 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700843 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700844 }
845 } else {
846 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700847 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700848 }
849 }
850 }
851
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700852 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700853 Class* class_;
854 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700855 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700856};
857
858int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700859 size_t count = 0;
860 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700861 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700862 GetLiveBitmap()->Visit(counter);
863 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700864}
865
Ian Rogers30fab402012-01-23 15:43:46 -0800866void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700867 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
868 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700869 Thread* self = Thread::Current();
870 WaitForConcurrentGcToComplete(self);
871 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700872 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
873 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700874}
875
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700876void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700877 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800878 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
879 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700880 Thread* self = Thread::Current();
881 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700882
883 // Try to see if we have any Zygote spaces.
884 if (have_zygote_space_) {
885 return;
886 }
887
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700888 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
889
890 {
891 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700892 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700893 FlushAllocStack();
894 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700895
896 // Replace the first alloc space we find with a zygote space.
897 // TODO: C++0x auto
898 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
899 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700900 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700901
902 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
903 // of the remaining available heap memory.
904 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700905 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700906
907 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700908 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700909 AddSpace(alloc_space_);
910 have_zygote_space_ = true;
911 break;
912 }
913 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700914
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700915 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700916 // TODO: C++0x
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800917 for (Collectors::const_iterator it = mark_sweep_collectors_.begin();
918 it != mark_sweep_collectors_.end(); ++it) {
919 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -0700920 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700921}
922
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700923void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700924 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
925 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700926 allocation_stack_->Reset();
927}
928
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700929size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700930 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700931}
932
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700933void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
934 Object** limit = stack->End();
935 for (Object** it = stack->Begin(); it != limit; ++it) {
936 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700937 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700938 if (LIKELY(bitmap->HasAddress(obj))) {
939 bitmap->Set(obj);
940 } else {
941 large_objects->Set(obj);
942 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700943 }
944}
945
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700946void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
947 Object** limit = stack->End();
948 for (Object** it = stack->Begin(); it != limit; ++it) {
949 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700950 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700951 if (LIKELY(bitmap->HasAddress(obj))) {
952 bitmap->Clear(obj);
953 } else {
954 large_objects->Clear(obj);
955 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700956 }
957}
958
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700959GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700960 Thread* self = Thread::Current();
961 Locks::mutator_lock_->AssertNotHeld(self);
962 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700963
Ian Rogers120f1c72012-09-28 17:17:10 -0700964 if (self->IsHandlingStackOverflow()) {
965 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
966 }
967
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700968 // Ensure there is only one GC at a time.
969 bool start_collect = false;
970 while (!start_collect) {
971 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700972 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700973 if (!is_gc_running_) {
974 is_gc_running_ = true;
975 start_collect = true;
976 }
977 }
978 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700979 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700980 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
981 // Not doing at the moment to ensure soft references are cleared.
982 }
983 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700984 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700985
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700986 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
987 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
988 ++Thread::Current()->GetStats()->gc_for_alloc_count;
989 }
990
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700991 // We need to do partial GCs every now and then to avoid the heap growing too much and
992 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700993 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700994 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700995 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700996 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700997 sticky_gc_count_ = 0;
998 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800999
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001000 DCHECK_LT(gc_type, kGcTypeMax);
1001 DCHECK_NE(gc_type, kGcTypeNone);
1002 MarkSweep* collector = NULL;
1003 for (Collectors::iterator it = mark_sweep_collectors_.begin();
1004 it != mark_sweep_collectors_.end(); ++it) {
1005 MarkSweep* cur_collector = *it;
1006 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1007 collector = cur_collector;
1008 break;
1009 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001010 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001011 CHECK(collector != NULL)
1012 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1013 << " and type=" << gc_type;
1014 collector->clear_soft_references_ = clear_soft_references;
1015 collector->Run();
1016 total_objects_freed_ += collector->GetFreedObjects();
1017 total_bytes_freed_ += collector->GetFreedBytes();
1018 RequestHeapTrim();
1019
1020 uint64_t duration = collector->GetDuration();
1021 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1022 bool was_slow = duration > kSlowGcThreshold ||
1023 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1024 for (size_t i = 0; i < pauses.size(); ++i) {
1025 if (pauses[i] > kLongGcPauseThreshold) {
1026 was_slow = true;
1027 }
1028 }
1029
1030 if (was_slow) {
1031 const size_t percent_free = GetPercentFree();
1032 const size_t current_heap_size = GetUsedMemorySize();
1033 const size_t total_memory = GetTotalMemory();
1034 std::ostringstream pause_string;
1035 for (size_t i = 0; i < pauses.size(); ++i) {
1036 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1037 << ((i != pauses.size() - 1) ? ", " : "");
1038 }
1039 LOG(INFO) << gc_cause << " " << collector->GetName()
1040 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1041 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1042 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1043 << " total " << PrettyDuration((duration / 1000) * 1000);
1044 if (VLOG_IS_ON(heap)) {
1045 collector->GetTimings().Dump();
1046 }
1047 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001048
Ian Rogers15bf2d32012-08-28 17:33:04 -07001049 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001050 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001051 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001052 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001053 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001054 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001055 }
1056 // Inform DDMS that a GC completed.
1057 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001058 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001059}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001060
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001061void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001062 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001063 // 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 -07001064 // cards.
1065 return;
1066 }
1067
1068 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001069 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001070 zygote_mod_union_table_->Update();
1071 timings.AddSplit("UpdateZygoteModUnionTable");
1072
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001073 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001074 timings.AddSplit("ZygoteMarkReferences");
1075 }
1076
1077 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1078 mod_union_table_->Update();
1079 timings.AddSplit("UpdateModUnionTable");
1080
1081 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001082 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001083 timings.AddSplit("MarkImageToAllocSpaceReferences");
1084}
1085
1086void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1087 Object* obj = reinterpret_cast<Object*>(arg);
1088 if (root == obj) {
1089 LOG(INFO) << "Object " << obj << " is a root";
1090 }
1091}
1092
1093class ScanVisitor {
1094 public:
1095 void operator ()(const Object* obj) const {
1096 LOG(INFO) << "Would have rescanned object " << obj;
1097 }
1098};
1099
1100class VerifyReferenceVisitor {
1101 public:
1102 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001103 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1104 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001105 : heap_(heap),
1106 failed_(failed) {
1107 }
1108
1109 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1110 // analysis.
1111 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1112 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1113 // Verify that the reference is live.
1114 if (ref != NULL && !IsLive(ref)) {
1115 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001116 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1117 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001118
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001119 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001120 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1121 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1122 << "Obj type " << PrettyTypeOf(obj) << "\n"
1123 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001124 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001125 void* cover_begin = card_table->AddrFromCard(card_addr);
1126 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001127 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001128 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001129 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001130 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1131
1132 // Print out how the object is live.
1133 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001134 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1135 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001136 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1137 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1138 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001139 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1140 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001141 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001142 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001143 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001144 }
1145
1146 // Attempt to see if the card table missed the reference.
1147 ScanVisitor scan_visitor;
1148 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001149 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001150 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001151
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001152 // Search to see if any of the roots reference our object.
1153 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1154 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1155 *failed_ = true;
1156 }
1157 }
1158
1159 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001160 if (heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001161 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001162 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001163 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001164 // 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 -08001165 // If the object is not either in the live bitmap or allocation stack, so the object must be
1166 // dead.
1167 return std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001168 }
1169
1170 private:
1171 Heap* heap_;
1172 bool* failed_;
1173};
1174
1175class VerifyObjectVisitor {
1176 public:
1177 VerifyObjectVisitor(Heap* heap)
1178 : heap_(heap),
1179 failed_(false) {
1180
1181 }
1182
1183 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001184 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001185 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1186 MarkSweep::VisitObjectReferences(obj, visitor);
1187 }
1188
1189 bool Failed() const {
1190 return failed_;
1191 }
1192
1193 private:
1194 Heap* heap_;
1195 bool failed_;
1196};
1197
1198// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001199bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001200 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001201 // Lets sort our allocation stacks so that we can efficiently binary search them.
1202 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1203 std::sort(live_stack_->Begin(), live_stack_->End());
1204 // Perform the verification.
1205 VerifyObjectVisitor visitor(this);
1206 GetLiveBitmap()->Visit(visitor);
1207 // We don't want to verify the objects in the allocation stack since they themselves may be
1208 // pointing to dead objects if they are not reachable.
1209 if (visitor.Failed()) {
1210 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001211 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001212 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001213 return true;
1214}
1215
1216class VerifyReferenceCardVisitor {
1217 public:
1218 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1220 Locks::heap_bitmap_lock_)
1221 : heap_(heap),
1222 failed_(failed) {
1223 }
1224
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001225 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1226 // annotalysis on visitors.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001227 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1228 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001229 // Filter out class references since changing an object's class does not mark the card as dirty.
1230 // Also handles large objects, since the only reference they hold is a class reference.
1231 if (ref != NULL && !ref->IsClass()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001232 CardTable* card_table = heap_->GetCardTable();
1233 // If the object is not dirty and it is referencing something in the live stack other than
1234 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001235 if (!card_table->AddrIsInCardTable(obj)) {
1236 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1237 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001238 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001239 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1240 // kCardDirty - 1 if it didnt get touched since we aged it.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001241 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001242 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001243 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1244 LOG(ERROR) << "Object " << obj << " found in live stack";
1245 }
1246 if (heap_->GetLiveBitmap()->Test(obj)) {
1247 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1248 }
1249 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1250 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1251
1252 // Print which field of the object is dead.
1253 if (!obj->IsObjectArray()) {
1254 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1255 CHECK(klass != NULL);
1256 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1257 CHECK(fields != NULL);
1258 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1259 const Field* cur = fields->Get(i);
1260 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1261 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1262 << PrettyField(cur);
1263 break;
1264 }
1265 }
1266 } else {
1267 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1268 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1269 if (object_array->Get(i) == ref) {
1270 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1271 }
1272 }
1273 }
1274
1275 *failed_ = true;
1276 }
1277 }
1278 }
1279 }
1280
1281 private:
1282 Heap* heap_;
1283 bool* failed_;
1284};
1285
1286class VerifyLiveStackReferences {
1287 public:
1288 VerifyLiveStackReferences(Heap* heap)
1289 : heap_(heap),
1290 failed_(false) {
1291
1292 }
1293
1294 void operator ()(const Object* obj) const
1295 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1296 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1297 MarkSweep::VisitObjectReferences(obj, visitor);
1298 }
1299
1300 bool Failed() const {
1301 return failed_;
1302 }
1303
1304 private:
1305 Heap* heap_;
1306 bool failed_;
1307};
1308
1309bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001310 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001311
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001312 // We need to sort the live stack since we binary search it.
1313 std::sort(live_stack_->Begin(), live_stack_->End());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001314 VerifyLiveStackReferences visitor(this);
1315 GetLiveBitmap()->Visit(visitor);
1316
1317 // We can verify objects in the live stack since none of these should reference dead objects.
1318 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1319 visitor(*it);
1320 }
1321
1322 if (visitor.Failed()) {
1323 DumpSpaces();
1324 return false;
1325 }
1326 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001327}
1328
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001329void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001330 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001331
1332 // Sort the live stack so that we can quickly binary search it later.
1333 if (VERIFY_OBJECT_ENABLED) {
1334 std::sort(live_stack_->Begin(), live_stack_->End());
1335 }
1336}
1337
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001338void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001339 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1340 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1341 ContinuousSpace* space = *it;
1342 if (space->IsImageSpace()) {
1343 mod_union_table_->ClearCards(*it);
1344 timings.AddSplit("ModUnionClearCards");
1345 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1346 zygote_mod_union_table_->ClearCards(space);
1347 timings.AddSplit("ZygoteModUnionClearCards");
1348 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001349 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1350 // were dirty before the GC started.
1351 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1352 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001353 }
1354 }
1355}
1356
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001357void Heap::PreGcVerification(GarbageCollector* gc) {
1358 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1359 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001360
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001361 if (verify_pre_gc_heap_) {
1362 thread_list->SuspendAll();
1363 {
1364 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1365 if (!VerifyHeapReferences()) {
1366 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1367 }
1368 }
1369 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001370 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001371
1372 // Check that all objects which reference things in the live stack are on dirty cards.
1373 if (verify_missing_card_marks_) {
1374 thread_list->SuspendAll();
1375 {
1376 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1377 SwapStacks();
1378 // Sort the live stack so that we can quickly binary search it later.
1379 if (!VerifyMissingCardMarks()) {
1380 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1381 }
1382 SwapStacks();
1383 }
1384 thread_list->ResumeAll();
1385 }
1386
1387 if (verify_mod_union_table_) {
1388 thread_list->SuspendAll();
1389 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1390 zygote_mod_union_table_->Update();
1391 zygote_mod_union_table_->Verify();
1392 mod_union_table_->Update();
1393 mod_union_table_->Verify();
1394 thread_list->ResumeAll();
1395 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001396}
1397
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001398void Heap::PreSweepingGcVerification(GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001399 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001400 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001401
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001402 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1403 // reachable objects.
1404 if (verify_post_gc_heap_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001405 thread_list->SuspendAll();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001406 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1407 // Swapping bound bitmaps does nothing.
1408 live_bitmap_.swap(mark_bitmap_);
1409 if (!VerifyHeapReferences()) {
1410 LOG(FATAL) << "Post " << gc->GetName() << "Gc verification failed";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001411 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001412 live_bitmap_.swap(mark_bitmap_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001413 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001414 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001415}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001416
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001417void Heap::PostGcVerification(GarbageCollector* gc) {
1418 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001419
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001420 if (verify_system_weaks_) {
1421 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1422 MarkSweep* mark_sweep = down_cast<MarkSweep*>(gc);
1423 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001424 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001425}
1426
Ian Rogers81d425b2012-09-27 16:03:43 -07001427GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001428 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001429 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001430 bool do_wait;
1431 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001432 {
1433 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001434 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001435 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001436 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001437 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001438 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001439 // We must wait, change thread state then sleep on gc_complete_cond_;
1440 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1441 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001442 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001443 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001444 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001445 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001446 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001447 wait_time = NanoTime() - wait_start;;
1448 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001449 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001450 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001451 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1452 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001453 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001454 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001455 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001456}
1457
Elliott Hughesc967f782012-04-16 10:23:15 -07001458void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001459 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1460 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001461 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001462}
1463
1464size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001465 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001466}
1467
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001468void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001469 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001470 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001471 << PrettySize(GetMaxMemory());
1472 max_allowed_footprint = GetMaxMemory();
1473 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001474 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001475}
1476
Carl Shapiro69759ea2011-07-21 18:13:35 -07001477void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001478 // We know what our utilization is at this moment.
1479 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001480 size_t target_size = num_bytes_allocated_ / GetTargetHeapUtilization();
Mathieu Chartier0051be62012-10-12 17:47:11 -07001481 if (target_size > num_bytes_allocated_ + max_free_) {
1482 target_size = num_bytes_allocated_ + max_free_;
1483 } else if (target_size < num_bytes_allocated_ + min_free_) {
1484 target_size = num_bytes_allocated_ + min_free_;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001485 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001486
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001487 // Calculate when to perform the next ConcurrentGC.
1488 if (GetFreeMemory() < concurrent_min_free_) {
1489 // Not enough free memory to perform concurrent GC.
1490 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1491 } else {
1492 // Start a concurrent Gc when we get close to the target size.
1493 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001494 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001495
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001496 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001497}
1498
jeffhaoc1160702011-10-27 15:48:45 -07001499void Heap::ClearGrowthLimit() {
jeffhaoc1160702011-10-27 15:48:45 -07001500 alloc_space_->ClearGrowthLimit();
1501}
1502
Elliott Hughesadb460d2011-10-05 17:02:34 -07001503void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001504 MemberOffset reference_queue_offset,
1505 MemberOffset reference_queueNext_offset,
1506 MemberOffset reference_pendingNext_offset,
1507 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001508 reference_referent_offset_ = reference_referent_offset;
1509 reference_queue_offset_ = reference_queue_offset;
1510 reference_queueNext_offset_ = reference_queueNext_offset;
1511 reference_pendingNext_offset_ = reference_pendingNext_offset;
1512 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1513 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1514 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1515 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1516 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1517 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1518}
1519
1520Object* Heap::GetReferenceReferent(Object* reference) {
1521 DCHECK(reference != NULL);
1522 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1523 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1524}
1525
1526void Heap::ClearReferenceReferent(Object* reference) {
1527 DCHECK(reference != NULL);
1528 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1529 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1530}
1531
1532// Returns true if the reference object has not yet been enqueued.
1533bool Heap::IsEnqueuable(const Object* ref) {
1534 DCHECK(ref != NULL);
1535 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1536 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1537 return (queue != NULL) && (queue_next == NULL);
1538}
1539
1540void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1541 DCHECK(ref != NULL);
1542 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1543 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1544 EnqueuePendingReference(ref, cleared_reference_list);
1545}
1546
1547void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1548 DCHECK(ref != NULL);
1549 DCHECK(list != NULL);
1550
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001551 // TODO: Remove this lock, use atomic stacks for storing references.
1552 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001553 if (*list == NULL) {
1554 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1555 *list = ref;
1556 } else {
1557 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1558 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1559 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1560 }
1561}
1562
1563Object* Heap::DequeuePendingReference(Object** list) {
1564 DCHECK(list != NULL);
1565 DCHECK(*list != NULL);
1566 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1567 Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001568
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001569 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1570 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001571 if (*list == head) {
1572 ref = *list;
1573 *list = NULL;
1574 } else {
1575 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1576 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1577 ref = head;
1578 }
1579 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1580 return ref;
1581}
1582
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001583void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001584 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001585 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001586 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001587 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1588 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001589}
1590
1591size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001592 return num_bytes_allocated_;
1593}
1594
1595size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001596 size_t total = 0;
1597 // TODO: C++0x
1598 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1599 Space* space = *it;
1600 if (space->IsAllocSpace()) {
1601 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1602 }
1603 }
1604 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001605}
1606
1607size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001608 return concurrent_start_size_;
1609}
1610
1611size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001612 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001613}
1614
1615void Heap::EnqueueClearedReferences(Object** cleared) {
1616 DCHECK(cleared != NULL);
1617 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001618 // When a runtime isn't started there are no reference queues to care about so ignore.
1619 if (LIKELY(Runtime::Current()->IsStarted())) {
1620 ScopedObjectAccess soa(Thread::Current());
1621 JValue args[1];
1622 args[0].SetL(*cleared);
1623 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1624 args, NULL);
1625 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001626 *cleared = NULL;
1627 }
1628}
1629
Ian Rogers1f539342012-10-03 21:09:42 -07001630void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001631 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001632 Runtime* runtime = Runtime::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001633 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001634 !runtime->IsConcurrentGcEnabled()) {
1635 return;
1636 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001637 {
1638 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1639 if (runtime->IsShuttingDown()) {
1640 return;
1641 }
1642 }
1643 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001644 return;
1645 }
1646
Ian Rogers120f1c72012-09-28 17:17:10 -07001647 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001648 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1649 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001650 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1651 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001652 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001653}
1654
Ian Rogers81d425b2012-09-27 16:03:43 -07001655void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001656 {
1657 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1658 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
1659 return;
1660 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001661 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001662
Ian Rogers81d425b2012-09-27 16:03:43 -07001663 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07001665 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001666 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001667 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001668 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001669 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001670 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001671 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001672}
1673
Mathieu Chartier3056d0c2012-10-19 10:49:56 -07001674void Heap::Trim() {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001675 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001676}
1677
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001678void Heap::RequestHeapTrim() {
1679 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1680 // because that only marks object heads, so a large array looks like lots of empty space. We
1681 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1682 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1683 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1684 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001685 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001686 float utilization =
1687 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1688 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1689 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1690 // heap trim occurred in the last two seconds.
1691 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001692 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001693
1694 Thread* self = Thread::Current();
1695 {
1696 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1697 Runtime* runtime = Runtime::Current();
1698 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1699 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1700 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1701 // as we don't hold the lock while requesting the trim).
1702 return;
1703 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001704 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001705 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001706 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001707 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1708 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001709 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1710 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001711 CHECK(!env->ExceptionCheck());
1712}
1713
Carl Shapiro69759ea2011-07-21 18:13:35 -07001714} // namespace art