blob: 2c52ff2f3f44afbbb70b6c3b0e39284c881ddf25 [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"
31#include "gc/mod_union_table.h"
32#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070033#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080035#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080036#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070037#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070038#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070039#include "sirt_ref.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070040#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070041#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070042#include "timing_logger.h"
43#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070044#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070045
46namespace art {
47
Mathieu Chartier02b6a782012-10-26 13:51:26 -070048static const bool kDumpGcPerformanceOnShutdown = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070049const double Heap::kDefaultTargetUtilization = 0.5;
50
Elliott Hughesae80b492012-04-24 10:43:17 -070051static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080052 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080053 std::vector<std::string> boot_class_path;
54 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070055 if (boot_class_path.empty()) {
56 LOG(FATAL) << "Failed to generate image because no boot class path specified";
57 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080058
59 std::vector<char*> arg_vector;
60
61 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070062 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080063 const char* dex2oat = dex2oat_string.c_str();
64 arg_vector.push_back(strdup(dex2oat));
65
66 std::string image_option_string("--image=");
67 image_option_string += image_file_name;
68 const char* image_option = image_option_string.c_str();
69 arg_vector.push_back(strdup(image_option));
70
71 arg_vector.push_back(strdup("--runtime-arg"));
72 arg_vector.push_back(strdup("-Xms64m"));
73
74 arg_vector.push_back(strdup("--runtime-arg"));
75 arg_vector.push_back(strdup("-Xmx64m"));
76
77 for (size_t i = 0; i < boot_class_path.size(); i++) {
78 std::string dex_file_option_string("--dex-file=");
79 dex_file_option_string += boot_class_path[i];
80 const char* dex_file_option = dex_file_option_string.c_str();
81 arg_vector.push_back(strdup(dex_file_option));
82 }
83
84 std::string oat_file_option_string("--oat-file=");
85 oat_file_option_string += image_file_name;
86 oat_file_option_string.erase(oat_file_option_string.size() - 3);
87 oat_file_option_string += "oat";
88 const char* oat_file_option = oat_file_option_string.c_str();
89 arg_vector.push_back(strdup(oat_file_option));
90
jeffhao8161c032012-10-31 15:50:00 -070091 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
92 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -080093
Elliott Hughes48436bb2012-02-07 15:23:28 -080094 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080095 LOG(INFO) << command_line;
96
Elliott Hughes48436bb2012-02-07 15:23:28 -080097 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -080098 char** argv = &arg_vector[0];
99
100 // fork and exec dex2oat
101 pid_t pid = fork();
102 if (pid == 0) {
103 // no allocation allowed between fork and exec
104
105 // change process groups, so we don't get reaped by ProcessManager
106 setpgid(0, 0);
107
108 execv(dex2oat, argv);
109
110 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
111 return false;
112 } else {
113 STLDeleteElements(&arg_vector);
114
115 // wait for dex2oat to finish
116 int status;
117 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
118 if (got_pid != pid) {
119 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
120 return false;
121 }
122 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
123 LOG(ERROR) << dex2oat << " failed: " << command_line;
124 return false;
125 }
126 }
127 return true;
128}
129
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700130void Heap::UnReserveOatFileAddressRange() {
131 oat_file_map_.reset(NULL);
132}
133
Mathieu Chartier0051be62012-10-12 17:47:11 -0700134Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
135 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700136 const std::string& original_image_file_name, bool concurrent_gc)
137 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800138 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700139 concurrent_gc_(concurrent_gc),
140 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800141 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700142 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700143 enforce_heap_growth_rate_(false),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700144 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700145 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700146 concurrent_start_size_(128 * KB),
147 concurrent_min_free_(256 * KB),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700148 concurrent_start_bytes_(initial_size - concurrent_start_size_),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700149 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700150 total_bytes_freed_(0),
151 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700152 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800153 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700154 verify_missing_card_marks_(false),
155 verify_system_weaks_(false),
156 verify_pre_gc_heap_(false),
157 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700158 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700159 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700160 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700161 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700162 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700163 requesting_gc_(false),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700164 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800165 reference_referent_offset_(0),
166 reference_queue_offset_(0),
167 reference_queueNext_offset_(0),
168 reference_pendingNext_offset_(0),
169 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700170 min_free_(min_free),
171 max_free_(max_free),
172 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700173 total_paused_time_(0),
174 total_wait_time_(0),
175 measure_allocation_time_(false),
176 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700177 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800178 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800179 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700180 }
181
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700182 live_bitmap_.reset(new HeapBitmap(this));
183 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700184
Ian Rogers30fab402012-01-23 15:43:46 -0800185 // Requested begin for the alloc space, to follow the mapped image and oat files
186 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800187 std::string image_file_name(original_image_file_name);
188 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700189 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700190
Brian Carlstrom5643b782012-02-05 12:32:53 -0800191 if (OS::FileExists(image_file_name.c_str())) {
192 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700193 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800194 } else {
195 // If the /system file didn't exist, we need to use one from the art-cache.
196 // If the cache file exists, try to open, but if it fails, regenerate.
197 // If it does not exist, generate.
198 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
199 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700200 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800201 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700202 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700203 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700204 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800205 }
206 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700207
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700208 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700209 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800210 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
211 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700212 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
213 CHECK_GT(oat_end_addr, image_space->End());
214
215 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
216 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
217 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
218 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
219 reinterpret_cast<byte*>(reserve_begin),
220 reserve_end - reserve_begin, PROT_READ));
221
Ian Rogers30fab402012-01-23 15:43:46 -0800222 if (oat_end_addr > requested_begin) {
223 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700224 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700225 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700226 }
227
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700228 // Allocate the large object space.
229 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700230 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
231 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
232
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700233 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
234 growth_limit, capacity,
235 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700236 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700237 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700238 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700239 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700240
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700241 // Spaces are sorted in order of Begin().
242 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700243 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
244 if (spaces_.back()->IsAllocSpace()) {
245 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
246 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700247
Ian Rogers30fab402012-01-23 15:43:46 -0800248 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700249 // TODO: C++0x
250 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
251 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800252 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700253 ImageSpace* image_space = space->AsImageSpace();
254 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800255 }
256 }
257
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800258 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700259 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
260 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700261
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700262 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
263 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700264
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700265 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
266 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700267
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700268 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700269 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800271 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700272 static const size_t default_mark_stack_size = 64 * KB;
273 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
274 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700275 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700276 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
277 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700278
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800279 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700280 // but we can create the heap lock now. We don't create it earlier to
281 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700282 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700283 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
284 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700285
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700286 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
287 reference_queue_lock_.reset(new Mutex("reference queue lock"));
288
289 CHECK(max_allowed_footprint_ != 0);
290
Mathieu Chartier0325e622012-09-05 14:22:51 -0700291 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700292 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
293 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700294 std::ostringstream name;
295 name << static_cast<GcType>(i);
296 cumulative_timings_.Put(static_cast<GcType>(i),
297 new CumulativeLogger(name.str().c_str(), true));
298 }
299
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;
359 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
360 it != cumulative_timings_.end(); ++it) {
361 CumulativeLogger* logger = it->second;
362 if (logger->GetTotalNs() != 0) {
363 logger->Dump();
364 total_duration += logger->GetTotalNs();
365 }
366 }
367 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
368 size_t total_objects_allocated = GetTotalObjectsAllocated();
369 size_t total_bytes_allocated = GetTotalBytesAllocated();
370 if (total_duration != 0) {
371 const double total_seconds = double(total_duration / 1000) / 1000000.0;
372 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
373 LOG(INFO) << "Mean GC size throughput: "
374 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
375 LOG(INFO) << "Mean GC object throughput: " << GetTotalObjectsFreed() / total_seconds << "/s";
376 }
377 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
378 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
379 if (measure_allocation_time_) {
380 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
381 LOG(INFO) << "Mean allocation time: "
382 << PrettyDuration(allocation_time / total_objects_allocated);
383 }
384 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time_);
385 LOG(INFO) << "Total waiting for Gc to complete time: " << PrettyDuration(total_wait_time_);
386}
387
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800388Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700389 if (kDumpGcPerformanceOnShutdown) {
390 DumpGcPerformanceInfo();
391 }
392
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700393 // If we don't reset then the mark stack complains in it's destructor.
394 allocation_stack_->Reset();
395 live_stack_->Reset();
396
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800397 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800398 // We can't take the heap lock here because there might be a daemon thread suspended with the
399 // heap lock held. We know though that no non-daemon threads are executing, and we know that
400 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
401 // 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 -0700402 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700403 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700404 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700405}
406
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700407ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700408 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700409 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
410 if ((*it)->Contains(obj)) {
411 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700412 }
413 }
414 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
415 return NULL;
416}
417
418ImageSpace* Heap::GetImageSpace() {
419 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700420 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
421 if ((*it)->IsImageSpace()) {
422 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700423 }
424 }
425 return NULL;
426}
427
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700428DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700429 return alloc_space_;
430}
431
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700432static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700433 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700434 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700435 size_t chunk_free_bytes = chunk_size - used_bytes;
436 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
437 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700438 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700439}
440
Ian Rogers50b35e22012-10-04 10:09:15 -0700441Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700442 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
443 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
444 strlen(ClassHelper(c).GetDescriptor()) == 0);
445 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700446
447 Object* obj = NULL;
448 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700449 uint64_t allocation_start = 0;
450 if (measure_allocation_time_) {
451 allocation_start = NanoTime();
452 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700453
454 // We need to have a zygote space or else our newly allocated large object can end up in the
455 // Zygote resulting in it being prematurely freed.
456 // We can only do this for primive objects since large objects will not be within the card table
457 // range. This also means that we rely on SetClass not dirtying the object's card.
458 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700459 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700460 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700461 // Make sure that our large object didn't get placed anywhere within the space interval or else
462 // it breaks the immune range.
463 DCHECK(obj == NULL ||
464 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
465 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700466 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700467 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700468
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700469 // Ensure that we did not allocate into a zygote space.
470 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
471 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700472 }
473
Mathieu Chartier037813d2012-08-23 16:44:59 -0700474 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700475 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700476
477 // Record allocation after since we want to use the atomic add for the atomic fence to guard
478 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700479 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700480
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 if (Dbg::IsAllocTrackingEnabled()) {
482 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700483 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700484 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700485 // We already have a request pending, no reason to start more until we update
486 // concurrent_start_bytes_.
487 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700489 SirtRef<Object> ref(self, obj);
490 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700491 }
492 VerifyObject(obj);
493
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700494 if (measure_allocation_time_) {
495 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
496 }
497
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498 return obj;
499 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700500 int64_t total_bytes_free = GetFreeMemory();
501 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700502 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700503 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
504 if ((*it)->IsAllocSpace()) {
505 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700506 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700507 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700508
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700509 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 -0700510 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700511 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700512 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700513}
514
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700515bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700516 // Note: we deliberately don't take the lock here, and mustn't test anything that would
517 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700518 if (obj == NULL) {
519 return true;
520 }
521 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700522 return false;
523 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800524 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800525 if (spaces_[i]->Contains(obj)) {
526 return true;
527 }
528 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700529 // Note: Doing this only works for the free list version of the large object space since the
530 // multiple memory map version uses a lock to do the contains check.
531 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700532}
533
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700534bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700535 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700536 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700537}
538
Elliott Hughes3e465b12011-09-02 18:26:12 -0700539#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700540void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700541 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700542 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700543 return;
544 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700545 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700546}
547#endif
548
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700549void Heap::DumpSpaces() {
550 // TODO: C++0x auto
551 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700552 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700553 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
554 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
555 LOG(INFO) << space << " " << *space << "\n"
556 << live_bitmap << " " << *live_bitmap << "\n"
557 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700558 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700559 if (large_object_space_.get() != NULL) {
560 large_object_space_->Dump(LOG(INFO));
561 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700562}
563
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700564void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700565 if (!IsAligned<kObjectAlignment>(obj)) {
566 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700567 }
568
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700569 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
570 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700571 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700572 // Check the allocation stack / live stack.
573 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
574 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
575 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700576 if (large_object_space_->GetLiveObjects()->Test(obj)) {
577 DumpSpaces();
578 LOG(FATAL) << "Object is dead: " << obj;
579 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700580 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700581 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700582
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700583 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700584 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700585 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
586 Object::ClassOffset().Int32Value();
587 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
588 if (c == NULL) {
589 LOG(FATAL) << "Null class in object: " << obj;
590 } else if (!IsAligned<kObjectAlignment>(c)) {
591 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
592 } else if (!GetLiveBitmap()->Test(c)) {
593 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
594 }
595 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
596 // Note: we don't use the accessors here as they have internal sanity checks
597 // that we don't want to run
598 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
599 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
600 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
601 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
602 CHECK_EQ(c_c, c_c_c);
603 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700604}
605
Brian Carlstrom78128a62011-09-15 17:21:19 -0700606void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700607 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700608 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700609}
610
611void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700612 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700613 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700614}
615
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700616void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700617 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700618 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700619 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700620
621 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700622 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700623 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700624 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700625
626 // TODO: Update these atomically.
627 RuntimeStats* global_stats = Runtime::Current()->GetStats();
628 ++global_stats->allocated_objects;
629 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700630 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700631
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700632 // This is safe to do since the GC will never free objects which are neither in the allocation
633 // stack or the live bitmap.
634 while (!allocation_stack_->AtomicPushBack(obj)) {
635 Thread* self = Thread::Current();
636 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
637 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
638 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
639 self->TransitionFromSuspendedToRunnable();
640 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700641}
642
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700643void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700644 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
645 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700646
647 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700648 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700649 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700650 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700651
652 // TODO: Do this concurrently.
653 RuntimeStats* global_stats = Runtime::Current()->GetStats();
654 global_stats->freed_objects += freed_objects;
655 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700656 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700657}
658
Ian Rogers50b35e22012-10-04 10:09:15 -0700659Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700660 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700661 if (enforce_heap_growth_rate_ && num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
662 if (grow) {
663 // Grow the heap by alloc_size extra bytes.
664 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
665 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
666 << " for a " << PrettySize(alloc_size) << " allocation";
667 } else {
668 return NULL;
669 }
670 }
671
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700672 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700673 // Completely out of memory.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700674 return NULL;
675 }
676
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700677 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700678}
679
Ian Rogers50b35e22012-10-04 10:09:15 -0700680Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700681 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
682 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700683 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700684 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700685
Ian Rogers50b35e22012-10-04 10:09:15 -0700686 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700687 if (ptr != NULL) {
688 return ptr;
689 }
690
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700691 // The allocation failed. If the GC is running, block until it completes, and then retry the
692 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700693 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700694 if (last_gc != kGcTypeNone) {
695 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700696 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700697 if (ptr != NULL) {
698 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700699 }
700 }
701
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700702 // Loop through our different Gc types and try to Gc until we get enough free memory.
703 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
704 bool run_gc = false;
705 GcType gc_type = static_cast<GcType>(i);
706 switch (gc_type) {
707 case kGcTypeSticky: {
708 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700709 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
710 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700711 break;
712 }
713 case kGcTypePartial:
714 run_gc = have_zygote_space_;
715 break;
716 case kGcTypeFull:
717 run_gc = true;
718 break;
719 default:
720 break;
721 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700722
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700723 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700724 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
725
726 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700727 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700728 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
729 i = static_cast<size_t>(gc_type_ran);
730 self->TransitionFromSuspendedToRunnable();
731
732 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700733 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700734 if (ptr != NULL) {
735 return ptr;
736 }
737 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700738 }
739
740 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700741 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700742 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700743 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700744 return ptr;
745 }
746
Elliott Hughes81ff3182012-03-23 20:35:56 -0700747 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
748 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
749 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700750
Elliott Hughes418dfe72011-10-06 18:56:27 -0700751 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700752 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
753 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700754
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700755 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700756 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700757 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700758 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700759 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700760}
761
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700762void Heap::SetTargetHeapUtilization(float target) {
763 DCHECK_GT(target, 0.0f); // asserted in Java code
764 DCHECK_LT(target, 1.0f);
765 target_utilization_ = target;
766}
767
768int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700769 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700770}
771
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700772int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700773 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700774}
775
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700776int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700777 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700778}
779
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700780size_t Heap::GetTotalBytesFreed() const {
781 return total_bytes_freed_;
782}
783
784size_t Heap::GetTotalObjectsFreed() const {
785 return total_objects_freed_;
786}
787
788size_t Heap::GetTotalObjectsAllocated() const {
789 size_t total = large_object_space_->GetTotalObjectsAllocated();
790 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
791 Space* space = *it;
792 if (space->IsAllocSpace()) {
793 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
794 }
795 }
796 return total;
797}
798
799size_t Heap::GetTotalBytesAllocated() const {
800 size_t total = large_object_space_->GetTotalBytesAllocated();
801 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
802 Space* space = *it;
803 if (space->IsAllocSpace()) {
804 total += space->AsAllocSpace()->GetTotalBytesAllocated();
805 }
806 }
807 return total;
808}
809
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700810class InstanceCounter {
811 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700812 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700813 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700814 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700815
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700816 }
817
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700818 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
819 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700820 if (count_assignable_) {
821 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700822 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700823 }
824 } else {
825 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700826 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700827 }
828 }
829 }
830
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700831 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700832 Class* class_;
833 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700834 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700835};
836
837int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700838 size_t count = 0;
839 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700840 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700841 GetLiveBitmap()->Visit(counter);
842 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700843}
844
Ian Rogers30fab402012-01-23 15:43:46 -0800845void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700846 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
847 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700848 Thread* self = Thread::Current();
849 WaitForConcurrentGcToComplete(self);
850 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700851 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
852 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700853}
854
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700855void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700856 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800857 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
858 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700859 Thread* self = Thread::Current();
860 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700861
862 // Try to see if we have any Zygote spaces.
863 if (have_zygote_space_) {
864 return;
865 }
866
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700867 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
868
869 {
870 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700871 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700872 FlushAllocStack();
873 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700874
875 // Replace the first alloc space we find with a zygote space.
876 // TODO: C++0x auto
877 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
878 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700879 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700880
881 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
882 // of the remaining available heap memory.
883 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700884 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700885
886 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700887 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700888 AddSpace(alloc_space_);
889 have_zygote_space_ = true;
890 break;
891 }
892 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700893
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700894 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700895 // TODO: C++0x
896 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
897 it != cumulative_timings_.end(); ++it) {
898 it->second->Reset();
899 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700900}
901
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700902void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700903 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
904 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700905 allocation_stack_->Reset();
906}
907
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700908size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700909 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700910}
911
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700912void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
913 Object** limit = stack->End();
914 for (Object** it = stack->Begin(); it != limit; ++it) {
915 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700916 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700917 if (LIKELY(bitmap->HasAddress(obj))) {
918 bitmap->Set(obj);
919 } else {
920 large_objects->Set(obj);
921 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700922 }
923}
924
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700925void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
926 Object** limit = stack->End();
927 for (Object** it = stack->Begin(); it != limit; ++it) {
928 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700929 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700930 if (LIKELY(bitmap->HasAddress(obj))) {
931 bitmap->Clear(obj);
932 } else {
933 large_objects->Clear(obj);
934 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700935 }
936}
937
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700938GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700939 Thread* self = Thread::Current();
940 Locks::mutator_lock_->AssertNotHeld(self);
941 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700942
Ian Rogers120f1c72012-09-28 17:17:10 -0700943 if (self->IsHandlingStackOverflow()) {
944 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
945 }
946
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700947 // Ensure there is only one GC at a time.
948 bool start_collect = false;
949 while (!start_collect) {
950 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700951 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700952 if (!is_gc_running_) {
953 is_gc_running_ = true;
954 start_collect = true;
955 }
956 }
957 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700958 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700959 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
960 // Not doing at the moment to ensure soft references are cleared.
961 }
962 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700963 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700964
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700965 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
966 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
967 ++Thread::Current()->GetStats()->gc_for_alloc_count;
968 }
969
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700970 // We need to do partial GCs every now and then to avoid the heap growing too much and
971 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700972 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700973 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700974 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700975 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700976 sticky_gc_count_ = 0;
977 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800978
Mathieu Chartier637e3482012-08-17 10:41:32 -0700979 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700980 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700981 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700982 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700983 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700984 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700985
Ian Rogers15bf2d32012-08-28 17:33:04 -0700986 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700987 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700988 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700989 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700990 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -0700991 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700992 }
993 // Inform DDMS that a GC completed.
994 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700995 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700996}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700997
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700998void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
999 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -07001001
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001002 std::stringstream gc_type_str;
1003 gc_type_str << gc_type << " ";
1004
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001005 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001006 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -07001007 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1008 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001009 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001010 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001011
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001012 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001013 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -07001014 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001015 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -07001016 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001017 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -07001018
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001019 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001020 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001021 if (!VerifyHeapReferences()) {
1022 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1023 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001024 timings.AddSplit("VerifyHeapReferencesPreGC");
1025 }
1026
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001027 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001028 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001029
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001030 // Process dirty cards and add dirty cards to mod union tables.
1031 ProcessCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001032
Ian Rogers120f1c72012-09-28 17:17:10 -07001033 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001034 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001035 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1036 // accidentally un-mark roots.
1037 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001038 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001039 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1040 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001041 }
1042 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001043 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001044
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001045 // We can assume that everything from the start of the first space to the alloc space is marked.
1046 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1047 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001048 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001049 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001050 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1051 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001052 }
1053 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001054 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001055 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001056 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001057 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1058 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001059 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001060 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001061
Carl Shapiro58551df2011-07-24 03:09:51 -07001062 mark_sweep.MarkRoots();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001063 mark_sweep.MarkConcurrentRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001064 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001065
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001066 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1067
1068 if (gc_type != kGcTypeSticky) {
1069 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1070 live_stack_.get());
1071 timings.AddSplit("MarkStackAsLive");
1072 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001073
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001074 if (verify_mod_union_table_) {
1075 zygote_mod_union_table_->Update();
1076 zygote_mod_union_table_->Verify();
1077 mod_union_table_->Update();
1078 mod_union_table_->Verify();
1079 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001080
1081 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001082 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001083 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001084 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001085 // Use -1 since we want to scan all of the cards which we aged earlier when we did
1086 // ClearCards. These are the cards which were dirty before the GC started.
1087 mark_sweep.RecursiveMarkDirtyObjects(CardTable::kCardDirty - 1);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001088 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001089 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001090
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001091 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001092 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001093 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001094
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001095 if (kIsDebugBuild) {
1096 // Verify that we only reach marked objects from the image space
1097 mark_sweep.VerifyImageRoots();
1098 timings.AddSplit("VerifyImageRoots");
1099 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001100
Mathieu Chartier0325e622012-09-05 14:22:51 -07001101 if (gc_type != kGcTypeSticky) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001102 mark_sweep.Sweep(timings, gc_type == kGcTypePartial, false);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001103 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001104 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001105 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001106 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001107 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001108 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001109 live_stack_->Reset();
1110
1111 // Unbind the live and mark bitmaps.
1112 mark_sweep.UnBindBitmaps();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001113 if (gc_type == kGcTypeSticky) {
1114 SwapLargeObjects();
1115 } else {
1116 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001117 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001118 timings.AddSplit("SwapBitmaps");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001119
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001120 if (verify_system_weaks_) {
1121 mark_sweep.VerifySystemWeaks();
1122 timings.AddSplit("VerifySystemWeaks");
1123 }
1124
Elliott Hughesadb460d2011-10-05 17:02:34 -07001125 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001126 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001127 total_bytes_freed_ += bytes_freed;
1128 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001129 }
1130
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001131 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001132 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001133 if (!VerifyHeapReferences()) {
1134 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1135 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001136 timings.AddSplit("VerifyHeapReferencesPostGC");
1137 }
1138
Carl Shapiro58551df2011-07-24 03:09:51 -07001139 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001140 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001141
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001142 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001143 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001144
1145 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001146 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001147 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001148
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001149 // If the GC was slow, then print timings in the log.
1150 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001151 total_paused_time_ += duration;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001152 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001153 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001154 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001155 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001156 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001157 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001158 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001159 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001160 if (VLOG_IS_ON(heap)) {
1161 timings.Dump();
1162 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001163 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001164
Mathieu Chartier0325e622012-09-05 14:22:51 -07001165 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1166 logger->Start();
1167 logger->AddLogger(timings);
1168 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001169}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001170
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001171void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001172 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001173 // 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 -07001174 // cards.
1175 return;
1176 }
1177
1178 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001179 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001180 zygote_mod_union_table_->Update();
1181 timings.AddSplit("UpdateZygoteModUnionTable");
1182
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001183 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001184 timings.AddSplit("ZygoteMarkReferences");
1185 }
1186
1187 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1188 mod_union_table_->Update();
1189 timings.AddSplit("UpdateModUnionTable");
1190
1191 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001192 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001193 timings.AddSplit("MarkImageToAllocSpaceReferences");
1194}
1195
1196void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1197 Object* obj = reinterpret_cast<Object*>(arg);
1198 if (root == obj) {
1199 LOG(INFO) << "Object " << obj << " is a root";
1200 }
1201}
1202
1203class ScanVisitor {
1204 public:
1205 void operator ()(const Object* obj) const {
1206 LOG(INFO) << "Would have rescanned object " << obj;
1207 }
1208};
1209
1210class VerifyReferenceVisitor {
1211 public:
1212 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001213 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1214 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001215 : heap_(heap),
1216 failed_(failed) {
1217 }
1218
1219 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1220 // analysis.
1221 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1222 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1223 // Verify that the reference is live.
1224 if (ref != NULL && !IsLive(ref)) {
1225 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001226 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1227 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001228
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001229 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001230 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1231 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1232 << "Obj type " << PrettyTypeOf(obj) << "\n"
1233 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001234 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001235 void* cover_begin = card_table->AddrFromCard(card_addr);
1236 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001237 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001238 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001239 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1241
1242 // Print out how the object is live.
1243 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001244 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1245 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001246 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1247 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1248 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001249 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1250 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001251 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001252 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001253 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001254 }
1255
1256 // Attempt to see if the card table missed the reference.
1257 ScanVisitor scan_visitor;
1258 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001259 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001260 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001261
1262 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001263 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001264 MarkSweep ms(mark_stack);
1265 ms.Init();
1266 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001267 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001268
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001269 // All the references should end up in the mark stack.
1270 ms.ScanRoot(obj);
1271 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001272 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001273 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001274 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001275 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001276 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001277 }
1278 }
1279 mark_stack->Reset();
1280
1281 // Search to see if any of the roots reference our object.
1282 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1283 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1284 *failed_ = true;
1285 }
1286 }
1287
1288 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1289 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1290 if (bitmap != NULL) {
1291 if (bitmap->Test(obj)) {
1292 return true;
1293 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001294 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001295 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001296 } else {
1297 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001298 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001299 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001300 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001301 // At this point we need to search the allocation since things in the live stack may get swept.
1302 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1303 return true;
1304 }
1305 // Not either in the live bitmap or allocation stack, so the object must be dead.
1306 return false;
1307 }
1308
1309 private:
1310 Heap* heap_;
1311 bool* failed_;
1312};
1313
1314class VerifyObjectVisitor {
1315 public:
1316 VerifyObjectVisitor(Heap* heap)
1317 : heap_(heap),
1318 failed_(false) {
1319
1320 }
1321
1322 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001323 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001324 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1325 MarkSweep::VisitObjectReferences(obj, visitor);
1326 }
1327
1328 bool Failed() const {
1329 return failed_;
1330 }
1331
1332 private:
1333 Heap* heap_;
1334 bool failed_;
1335};
1336
1337// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001338bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001339 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001340 // Lets sort our allocation stacks so that we can efficiently binary search them.
1341 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1342 std::sort(live_stack_->Begin(), live_stack_->End());
1343 // Perform the verification.
1344 VerifyObjectVisitor visitor(this);
1345 GetLiveBitmap()->Visit(visitor);
1346 // We don't want to verify the objects in the allocation stack since they themselves may be
1347 // pointing to dead objects if they are not reachable.
1348 if (visitor.Failed()) {
1349 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001350 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001351 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001352 return true;
1353}
1354
1355class VerifyReferenceCardVisitor {
1356 public:
1357 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1358 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1359 Locks::heap_bitmap_lock_)
1360 : heap_(heap),
1361 failed_(failed) {
1362 }
1363
1364 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1365 // analysis.
1366 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1367 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001368 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001369 CardTable* card_table = heap_->GetCardTable();
1370 // If the object is not dirty and it is referencing something in the live stack other than
1371 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001372 if (!card_table->AddrIsInCardTable(obj)) {
1373 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1374 *failed_ = true;
1375 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001376 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001377 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1378 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1379 LOG(ERROR) << "Object " << obj << " found in live stack";
1380 }
1381 if (heap_->GetLiveBitmap()->Test(obj)) {
1382 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1383 }
1384 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1385 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1386
1387 // Print which field of the object is dead.
1388 if (!obj->IsObjectArray()) {
1389 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1390 CHECK(klass != NULL);
1391 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1392 CHECK(fields != NULL);
1393 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1394 const Field* cur = fields->Get(i);
1395 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1396 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1397 << PrettyField(cur);
1398 break;
1399 }
1400 }
1401 } else {
1402 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1403 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1404 if (object_array->Get(i) == ref) {
1405 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1406 }
1407 }
1408 }
1409
1410 *failed_ = true;
1411 }
1412 }
1413 }
1414 }
1415
1416 private:
1417 Heap* heap_;
1418 bool* failed_;
1419};
1420
1421class VerifyLiveStackReferences {
1422 public:
1423 VerifyLiveStackReferences(Heap* heap)
1424 : heap_(heap),
1425 failed_(false) {
1426
1427 }
1428
1429 void operator ()(const Object* obj) const
1430 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1431 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1432 MarkSweep::VisitObjectReferences(obj, visitor);
1433 }
1434
1435 bool Failed() const {
1436 return failed_;
1437 }
1438
1439 private:
1440 Heap* heap_;
1441 bool failed_;
1442};
1443
1444bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001445 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001446
1447 VerifyLiveStackReferences visitor(this);
1448 GetLiveBitmap()->Visit(visitor);
1449
1450 // We can verify objects in the live stack since none of these should reference dead objects.
1451 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1452 visitor(*it);
1453 }
1454
1455 if (visitor.Failed()) {
1456 DumpSpaces();
1457 return false;
1458 }
1459 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001460}
1461
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001462void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001463 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001464 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1465 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001466 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1467 ContinuousSpace* space = *it;
1468 // We never allocate into zygote spaces.
1469 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1470 (gc_type == kGcTypeFull &&
1471 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001472 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1473 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1474 if (live_bitmap != mark_bitmap) {
1475 live_bitmap_->ReplaceBitmap(live_bitmap, mark_bitmap);
1476 mark_bitmap_->ReplaceBitmap(mark_bitmap, live_bitmap);
1477 space->AsAllocSpace()->SwapBitmaps();
1478 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001479 }
1480 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001481 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001482}
1483
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001484void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001485 large_object_space_->SwapBitmaps();
1486 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1487 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001488}
1489
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001490void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001491 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001492
1493 // Sort the live stack so that we can quickly binary search it later.
1494 if (VERIFY_OBJECT_ENABLED) {
1495 std::sort(live_stack_->Begin(), live_stack_->End());
1496 }
1497}
1498
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001499void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001500 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1501 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1502 ContinuousSpace* space = *it;
1503 if (space->IsImageSpace()) {
1504 mod_union_table_->ClearCards(*it);
1505 timings.AddSplit("ModUnionClearCards");
1506 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1507 zygote_mod_union_table_->ClearCards(space);
1508 timings.AddSplit("ZygoteModUnionClearCards");
1509 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001510 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1511 // were dirty before the GC started.
1512 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1513 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001514 }
1515 }
1516}
1517
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001518void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1519 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001520 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001521 uint64_t gc_begin = NanoTime(), dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001522 std::stringstream gc_type_str;
1523 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001524
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001525 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001526 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001527 Object* cleared_references = NULL;
1528 {
1529 MarkSweep mark_sweep(mark_stack_.get());
1530 timings.AddSplit("ctor");
1531
1532 mark_sweep.Init();
1533 timings.AddSplit("Init");
1534
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001535 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001536 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001537
Mathieu Chartier0325e622012-09-05 14:22:51 -07001538 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001539 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1540 // accidentally un-mark roots.
1541 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001542 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001543 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1544 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001545 }
1546 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001547 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001548 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1549 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001550 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001551 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001552 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1553 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001554 }
1555 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001556 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001557 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001558 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001559 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1560 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001561 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001562 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001563 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001564
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001565 if (verify_pre_gc_heap_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001566 thread_list->SuspendAll();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001567 {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001568 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1569 if (!VerifyHeapReferences()) {
1570 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1571 }
1572 timings.AddSplit("VerifyHeapReferencesPreGC");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001573 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001574 thread_list->ResumeAll();
1575 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001576
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001577 // Process dirty cards and add dirty cards to mod union tables.
1578 ProcessCards(timings);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001579
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001580 // Need to do this before the checkpoint since we don't want any threads to add references to
1581 // the live stack during the recursive mark.
1582 SwapStacks();
1583 timings.AddSplit("SwapStacks");
1584
1585 // Tell the running threads to suspend and mark their roots.
1586 mark_sweep.MarkRootsCheckpoint();
1587 timings.AddSplit("MarkRootsCheckpoint");
1588
1589 // Check that all objects which reference things in the live stack are on dirty cards.
1590 if (verify_missing_card_marks_) {
1591 thread_list->SuspendAll();
1592 {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001593 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1594 // Sort the live stack so that we can quickly binary search it later.
1595 std::sort(live_stack_->Begin(), live_stack_->End());
1596 if (!VerifyMissingCardMarks()) {
1597 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1598 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001599 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001600 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001601 }
1602
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001603 if (verify_mod_union_table_) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001604 thread_list->SuspendAll();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001605 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1606 zygote_mod_union_table_->Update();
1607 zygote_mod_union_table_->Verify();
1608 mod_union_table_->Update();
1609 mod_union_table_->Verify();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001610 thread_list->ResumeAll();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001611 }
1612
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001613 {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001614 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
Ian Rogers81d425b2012-09-27 16:03:43 -07001615 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001616
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001617 // Mark the roots which we can do concurrently.
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001618 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001619 mark_sweep.MarkConcurrentRoots();
1620 timings.AddSplit("MarkConcurrentRoots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001621 mark_sweep.MarkNonThreadRoots();
1622 timings.AddSplit("MarkNonThreadRoots");
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001623
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001624 if (gc_type != kGcTypeSticky) {
1625 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1626 // knowing that new allocations won't be marked as live.
1627 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1628 live_stack_.get());
1629 timings.AddSplit("MarkStackAsLive");
1630 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001631
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001632 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1633
Mathieu Chartier0325e622012-09-05 14:22:51 -07001634 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001635 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001636 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001637 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001638 mark_sweep.RecursiveMarkDirtyObjects(CardTable::kCardDirty - 1);
1639 timings.AddSplit("RecursiveMarkCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001640 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001641 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001642 }
1643 // Release share on mutator_lock_ and then get exclusive access.
1644 dirty_begin = NanoTime();
1645 thread_list->SuspendAll();
1646 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001647 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648
1649 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001650 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001651
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001652 // Re-mark root set.
1653 mark_sweep.ReMarkRoots();
1654 timings.AddSplit("ReMarkRoots");
1655
1656 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001657 mark_sweep.RecursiveMarkDirtyObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001658 timings.AddSplit("RecursiveMarkDirtyObjects");
1659 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001660
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001661 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001662 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001663
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664 mark_sweep.ProcessReferences(clear_soft_references);
1665 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001666 }
1667
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001668 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1669 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001670 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001671 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001672 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001673 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001674 // We only sweep over the live stack, and the live stack should not intersect with the
1675 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001676 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1677 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001678 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001679#ifndef NDEBUG
1680 if (gc_type == kGcTypeSticky) {
1681 // Make sure everything in the live stack isn't something we unmarked.
1682 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1683 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001684 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1685 << "Unmarked object " << *it << " in the live stack";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001686 }
1687 } else {
1688 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001689 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001690 }
1691 }
1692#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001693 }
1694
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001695 if (kIsDebugBuild) {
1696 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001697 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001698 mark_sweep.VerifyImageRoots();
1699 timings.AddSplit("VerifyImageRoots");
1700 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001701
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001702 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001703 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001704 // Swapping bound bitmaps does nothing.
1705 SwapBitmaps(kGcTypeFull);
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001706 if (!VerifyHeapReferences()) {
1707 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001708 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001709 SwapBitmaps(kGcTypeFull);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001710 timings.AddSplit("VerifyHeapReferencesPostGC");
1711 }
1712
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001713 thread_list->ResumeAll();
1714 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001715 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001716
1717 {
1718 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001719 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001720 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001721 mark_sweep.Sweep(timings, gc_type == kGcTypePartial, false);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001722 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001723 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001724 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001725 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001726 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001727 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001728 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001729 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001730 }
1731
1732 {
1733 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1734 // Unbind the live and mark bitmaps.
1735 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001736
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001737 // Swap the live and mark bitmaps for each space which we modified space. This is an
1738 // optimization that enables us to not clear live bits inside of the sweep.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001739 if (gc_type == kGcTypeSticky) {
1740 SwapLargeObjects();
1741 } else {
1742 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001743 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001744 timings.AddSplit("SwapBitmaps");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001745 }
1746
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001747 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001748 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001749 mark_sweep.VerifySystemWeaks();
1750 timings.AddSplit("VerifySystemWeaks");
1751 }
1752
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001753 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001754 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001755 total_bytes_freed_ += bytes_freed;
1756 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001757 }
1758
1759 GrowForUtilization();
1760 timings.AddSplit("GrowForUtilization");
1761
1762 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001763 timings.AddSplit("EnqueueClearedReferences");
1764
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001765 RequestHeapTrim();
1766 timings.AddSplit("Finish");
1767
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001768 // If the GC was slow, then print timings in the log.
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001769 uint64_t pause_time = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001770 uint64_t duration = (NanoTime() - gc_begin) / 1000 * 1000;
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001771 total_paused_time_ += pause_time;
1772 if (pause_time > MsToNs(5) || (gc_cause == kGcCauseForAlloc && duration > MsToNs(20))) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001773 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001774 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001775 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001776 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001777 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001778 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001779 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_time)
1780 << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001781 if (VLOG_IS_ON(heap)) {
1782 timings.Dump();
1783 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001784 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001785
Mathieu Chartier0325e622012-09-05 14:22:51 -07001786 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1787 logger->Start();
1788 logger->AddLogger(timings);
1789 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001790}
1791
Ian Rogers81d425b2012-09-27 16:03:43 -07001792GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001793 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001794 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001795 bool do_wait;
1796 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001797 {
1798 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001799 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001800 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001801 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001802 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001803 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001804 // We must wait, change thread state then sleep on gc_complete_cond_;
1805 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1806 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001807 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001809 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001810 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001811 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001812 wait_time = NanoTime() - wait_start;;
1813 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001814 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001815 if (wait_time > MsToNs(5)) {
1816 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1817 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001818 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001819 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001820 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001821}
1822
Elliott Hughesc967f782012-04-16 10:23:15 -07001823void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001824 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1825 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001826 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001827}
1828
1829size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001830 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001831}
1832
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001833void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001834 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001835 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001836 << PrettySize(GetMaxMemory());
1837 max_allowed_footprint = GetMaxMemory();
1838 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001839 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001840}
1841
Carl Shapiro69759ea2011-07-21 18:13:35 -07001842void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001843 // We know what our utilization is at this moment.
1844 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001845 size_t target_size = num_bytes_allocated_ / GetTargetHeapUtilization();
Mathieu Chartier0051be62012-10-12 17:47:11 -07001846 if (target_size > num_bytes_allocated_ + max_free_) {
1847 target_size = num_bytes_allocated_ + max_free_;
1848 } else if (target_size < num_bytes_allocated_ + min_free_) {
1849 target_size = num_bytes_allocated_ + min_free_;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001850 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001851
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001852 // Calculate when to perform the next ConcurrentGC.
1853 if (GetFreeMemory() < concurrent_min_free_) {
1854 // Not enough free memory to perform concurrent GC.
1855 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1856 } else {
1857 // Start a concurrent Gc when we get close to the target size.
1858 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001859 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001860
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001861 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001862}
1863
jeffhaoc1160702011-10-27 15:48:45 -07001864void Heap::ClearGrowthLimit() {
jeffhaoc1160702011-10-27 15:48:45 -07001865 alloc_space_->ClearGrowthLimit();
1866}
1867
Elliott Hughesadb460d2011-10-05 17:02:34 -07001868void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001869 MemberOffset reference_queue_offset,
1870 MemberOffset reference_queueNext_offset,
1871 MemberOffset reference_pendingNext_offset,
1872 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001873 reference_referent_offset_ = reference_referent_offset;
1874 reference_queue_offset_ = reference_queue_offset;
1875 reference_queueNext_offset_ = reference_queueNext_offset;
1876 reference_pendingNext_offset_ = reference_pendingNext_offset;
1877 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1878 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1879 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1880 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1881 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1882 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1883}
1884
1885Object* Heap::GetReferenceReferent(Object* reference) {
1886 DCHECK(reference != NULL);
1887 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1888 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1889}
1890
1891void Heap::ClearReferenceReferent(Object* reference) {
1892 DCHECK(reference != NULL);
1893 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1894 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1895}
1896
1897// Returns true if the reference object has not yet been enqueued.
1898bool Heap::IsEnqueuable(const Object* ref) {
1899 DCHECK(ref != NULL);
1900 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1901 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1902 return (queue != NULL) && (queue_next == NULL);
1903}
1904
1905void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1906 DCHECK(ref != NULL);
1907 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1908 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1909 EnqueuePendingReference(ref, cleared_reference_list);
1910}
1911
1912void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1913 DCHECK(ref != NULL);
1914 DCHECK(list != NULL);
1915
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001916 // TODO: Remove this lock, use atomic stacks for storing references.
1917 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001918 if (*list == NULL) {
1919 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1920 *list = ref;
1921 } else {
1922 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1923 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1924 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1925 }
1926}
1927
1928Object* Heap::DequeuePendingReference(Object** list) {
1929 DCHECK(list != NULL);
1930 DCHECK(*list != NULL);
1931 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1932 Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001933
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001934 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1935 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001936 if (*list == head) {
1937 ref = *list;
1938 *list = NULL;
1939 } else {
1940 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1941 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1942 ref = head;
1943 }
1944 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1945 return ref;
1946}
1947
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001948void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001949 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001950 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001951 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001952 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1953 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001954}
1955
1956size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001957 return num_bytes_allocated_;
1958}
1959
1960size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001961 size_t total = 0;
1962 // TODO: C++0x
1963 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1964 Space* space = *it;
1965 if (space->IsAllocSpace()) {
1966 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1967 }
1968 }
1969 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001970}
1971
1972size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001973 return concurrent_start_size_;
1974}
1975
1976size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001977 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001978}
1979
1980void Heap::EnqueueClearedReferences(Object** cleared) {
1981 DCHECK(cleared != NULL);
1982 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001983 // When a runtime isn't started there are no reference queues to care about so ignore.
1984 if (LIKELY(Runtime::Current()->IsStarted())) {
1985 ScopedObjectAccess soa(Thread::Current());
1986 JValue args[1];
1987 args[0].SetL(*cleared);
1988 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1989 args, NULL);
1990 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001991 *cleared = NULL;
1992 }
1993}
1994
Ian Rogers1f539342012-10-03 21:09:42 -07001995void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001996 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001997 Runtime* runtime = Runtime::Current();
1998 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1999 !runtime->IsConcurrentGcEnabled()) {
2000 return;
2001 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002002 {
2003 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2004 if (runtime->IsShuttingDown()) {
2005 return;
2006 }
2007 }
2008 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002009 return;
2010 }
2011
2012 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07002013 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002014 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2015 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002016 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2017 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002018 CHECK(!env->ExceptionCheck());
2019 requesting_gc_ = false;
2020}
2021
Ian Rogers81d425b2012-09-27 16:03:43 -07002022void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002023 {
2024 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2025 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2026 return;
2027 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002028 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002029
Ian Rogers81d425b2012-09-27 16:03:43 -07002030 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002031 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002032 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002033 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002034 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002035 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002036 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002037 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002038 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002039}
2040
Mathieu Chartier3056d0c2012-10-19 10:49:56 -07002041void Heap::Trim() {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002042 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002043}
2044
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002045void Heap::RequestHeapTrim() {
2046 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2047 // because that only marks object heads, so a large array looks like lots of empty space. We
2048 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2049 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2050 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2051 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002052 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002053 float utilization =
2054 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2055 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2056 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2057 // heap trim occurred in the last two seconds.
2058 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002059 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002060
2061 Thread* self = Thread::Current();
2062 {
2063 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2064 Runtime* runtime = Runtime::Current();
2065 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2066 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2067 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2068 // as we don't hold the lock while requesting the trim).
2069 return;
2070 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002071 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002072 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002073 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002074 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2075 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002076 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2077 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002078 CHECK(!env->ExceptionCheck());
2079}
2080
Carl Shapiro69759ea2011-07-21 18:13:35 -07002081} // namespace art