blob: b4cf4a9af507bb8b7dcf65d48ba35f9190d4319a [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 Chartier357e9be2012-08-01 11:00:14 -0700271 // Max 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);
Ian Rogers81d425b2012-09-27 16:03:43 -0700857 Thread* self = Thread::Current();
858 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700859
860 // Try to see if we have any Zygote spaces.
861 if (have_zygote_space_) {
862 return;
863 }
864
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700865 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
866
867 {
868 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700869 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700870 FlushAllocStack();
871 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700872
873 // Replace the first alloc space we find with a zygote space.
874 // TODO: C++0x auto
875 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
876 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700877 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700878
879 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
880 // of the remaining available heap memory.
881 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700882 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700883
884 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700885 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700886 AddSpace(alloc_space_);
887 have_zygote_space_ = true;
888 break;
889 }
890 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700891
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700892 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700893 // TODO: C++0x
894 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
895 it != cumulative_timings_.end(); ++it) {
896 it->second->Reset();
897 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700898}
899
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700900void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700901 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
902 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700903 allocation_stack_->Reset();
904}
905
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700906size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700907 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700908}
909
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700910void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
911 Object** limit = stack->End();
912 for (Object** it = stack->Begin(); it != limit; ++it) {
913 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700914 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700915 if (LIKELY(bitmap->HasAddress(obj))) {
916 bitmap->Set(obj);
917 } else {
918 large_objects->Set(obj);
919 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700920 }
921}
922
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700923void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
924 Object** limit = stack->End();
925 for (Object** it = stack->Begin(); it != limit; ++it) {
926 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700927 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700928 if (LIKELY(bitmap->HasAddress(obj))) {
929 bitmap->Clear(obj);
930 } else {
931 large_objects->Clear(obj);
932 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700933 }
934}
935
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700936GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700937 Thread* self = Thread::Current();
938 Locks::mutator_lock_->AssertNotHeld(self);
939 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700940
Ian Rogers120f1c72012-09-28 17:17:10 -0700941 if (self->IsHandlingStackOverflow()) {
942 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
943 }
944
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700945 // Ensure there is only one GC at a time.
946 bool start_collect = false;
947 while (!start_collect) {
948 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700949 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700950 if (!is_gc_running_) {
951 is_gc_running_ = true;
952 start_collect = true;
953 }
954 }
955 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700956 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700957 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
958 // Not doing at the moment to ensure soft references are cleared.
959 }
960 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700961 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700962
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700963 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
964 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
965 ++Thread::Current()->GetStats()->gc_for_alloc_count;
966 }
967
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700968 // We need to do partial GCs every now and then to avoid the heap growing too much and
969 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700970 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700971 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700972 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700973 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700974 sticky_gc_count_ = 0;
975 }
Mathieu Chartier637e3482012-08-17 10:41:32 -0700976 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700977 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700978 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700979 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700980 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700981 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700982
Ian Rogers15bf2d32012-08-28 17:33:04 -0700983 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700984 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700985 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700986 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700987 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -0700988 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700989 }
990 // Inform DDMS that a GC completed.
991 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700992 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700993}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700994
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700995void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
996 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700997 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700998
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700999 std::stringstream gc_type_str;
1000 gc_type_str << gc_type << " ";
1001
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001002 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001003 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -07001004 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1005 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001006 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001007 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001008
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001009 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001010 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -07001011 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001012 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -07001013 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001014 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -07001015
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001016 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001017 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001018 if (!VerifyHeapReferences()) {
1019 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1020 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001021 timings.AddSplit("VerifyHeapReferencesPreGC");
1022 }
1023
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001024 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001025 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001026
1027 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1028 // TODO: Investigate using a mark stack instead of a vector.
1029 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001030 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001031 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1032 card_table_->GetDirtyCards(*it, dirty_cards);
1033 }
1034 }
1035
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001036 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001037 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001038
Ian Rogers120f1c72012-09-28 17:17:10 -07001039 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001040 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001041 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1042 // accidentally un-mark roots.
1043 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001044 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001045 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1046 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001047 }
1048 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001049 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001050
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001051 // We can assume that everything from the start of the first space to the alloc space is marked.
1052 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1053 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001054 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001055 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001056 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1057 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001058 }
1059 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001060 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001061 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001062 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001063 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1064 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001065 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001066 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001067
Carl Shapiro58551df2011-07-24 03:09:51 -07001068 mark_sweep.MarkRoots();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001069 mark_sweep.MarkConcurrentRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001070 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001071
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001072 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1073
1074 if (gc_type != kGcTypeSticky) {
1075 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1076 live_stack_.get());
1077 timings.AddSplit("MarkStackAsLive");
1078 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001079
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001080 if (verify_mod_union_table_) {
1081 zygote_mod_union_table_->Update();
1082 zygote_mod_union_table_->Verify();
1083 mod_union_table_->Update();
1084 mod_union_table_->Verify();
1085 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001086
1087 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001088 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001089 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001090 } else {
1091 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1092 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001093 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001094
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001095 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001096 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001097 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001098
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001099 if (kIsDebugBuild) {
1100 // Verify that we only reach marked objects from the image space
1101 mark_sweep.VerifyImageRoots();
1102 timings.AddSplit("VerifyImageRoots");
1103 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001104
Mathieu Chartier0325e622012-09-05 14:22:51 -07001105 if (gc_type != kGcTypeSticky) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001106 mark_sweep.Sweep(timings, gc_type == kGcTypePartial, false);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001107 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001108 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001109 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001110 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001111 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001112 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001113 live_stack_->Reset();
1114
1115 // Unbind the live and mark bitmaps.
1116 mark_sweep.UnBindBitmaps();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001117 if (gc_type == kGcTypeSticky) {
1118 SwapLargeObjects();
1119 } else {
1120 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001121 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001122 timings.AddSplit("SwapBitmaps");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001123
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001124 if (verify_system_weaks_) {
1125 mark_sweep.VerifySystemWeaks();
1126 timings.AddSplit("VerifySystemWeaks");
1127 }
1128
Elliott Hughesadb460d2011-10-05 17:02:34 -07001129 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001130 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001131 total_bytes_freed_ += bytes_freed;
1132 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001133 }
1134
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001135 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001136 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001137 if (!VerifyHeapReferences()) {
1138 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1139 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001140 timings.AddSplit("VerifyHeapReferencesPostGC");
1141 }
1142
Carl Shapiro58551df2011-07-24 03:09:51 -07001143 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001144 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001145
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001146 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001147 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001148
1149 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001150 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001151 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001152
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001153 // If the GC was slow, then print timings in the log.
1154 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001155 total_paused_time_ += duration;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001156 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001157 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001158 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001159 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001160 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001161 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001162 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001163 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001164 if (VLOG_IS_ON(heap)) {
1165 timings.Dump();
1166 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001167 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001168
Mathieu Chartier0325e622012-09-05 14:22:51 -07001169 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1170 logger->Start();
1171 logger->AddLogger(timings);
1172 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001173}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001174
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001175void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001176 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001177 // 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 -07001178 // cards.
1179 return;
1180 }
1181
1182 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001183 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001184 zygote_mod_union_table_->Update();
1185 timings.AddSplit("UpdateZygoteModUnionTable");
1186
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001187 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001188 timings.AddSplit("ZygoteMarkReferences");
1189 }
1190
1191 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1192 mod_union_table_->Update();
1193 timings.AddSplit("UpdateModUnionTable");
1194
1195 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001196 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001197 timings.AddSplit("MarkImageToAllocSpaceReferences");
1198}
1199
1200void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1201 Object* obj = reinterpret_cast<Object*>(arg);
1202 if (root == obj) {
1203 LOG(INFO) << "Object " << obj << " is a root";
1204 }
1205}
1206
1207class ScanVisitor {
1208 public:
1209 void operator ()(const Object* obj) const {
1210 LOG(INFO) << "Would have rescanned object " << obj;
1211 }
1212};
1213
1214class VerifyReferenceVisitor {
1215 public:
1216 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001217 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1218 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001219 : heap_(heap),
1220 failed_(failed) {
1221 }
1222
1223 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1224 // analysis.
1225 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1226 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1227 // Verify that the reference is live.
1228 if (ref != NULL && !IsLive(ref)) {
1229 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001230 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1231 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001232
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001233 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001234 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1235 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1236 << "Obj type " << PrettyTypeOf(obj) << "\n"
1237 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001238 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001239 void* cover_begin = card_table->AddrFromCard(card_addr);
1240 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001241 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001242 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001243 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001244 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1245
1246 // Print out how the object is live.
1247 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001248 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1249 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001250 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1251 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1252 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001253 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1254 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001255 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001256 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001257 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001258 }
1259
1260 // Attempt to see if the card table missed the reference.
1261 ScanVisitor scan_visitor;
1262 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001263 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1264 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001265
1266 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001267 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001268 MarkSweep ms(mark_stack);
1269 ms.Init();
1270 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001271 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001272
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001273 // All the references should end up in the mark stack.
1274 ms.ScanRoot(obj);
1275 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001276 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001277 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001278 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001279 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001280 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001281 }
1282 }
1283 mark_stack->Reset();
1284
1285 // Search to see if any of the roots reference our object.
1286 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1287 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1288 *failed_ = true;
1289 }
1290 }
1291
1292 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1293 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1294 if (bitmap != NULL) {
1295 if (bitmap->Test(obj)) {
1296 return true;
1297 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001298 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001299 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001300 } else {
1301 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001302 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001303 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001304 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001305 // At this point we need to search the allocation since things in the live stack may get swept.
1306 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1307 return true;
1308 }
1309 // Not either in the live bitmap or allocation stack, so the object must be dead.
1310 return false;
1311 }
1312
1313 private:
1314 Heap* heap_;
1315 bool* failed_;
1316};
1317
1318class VerifyObjectVisitor {
1319 public:
1320 VerifyObjectVisitor(Heap* heap)
1321 : heap_(heap),
1322 failed_(false) {
1323
1324 }
1325
1326 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001327 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001328 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1329 MarkSweep::VisitObjectReferences(obj, visitor);
1330 }
1331
1332 bool Failed() const {
1333 return failed_;
1334 }
1335
1336 private:
1337 Heap* heap_;
1338 bool failed_;
1339};
1340
1341// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001342bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001343 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001344 // Lets sort our allocation stacks so that we can efficiently binary search them.
1345 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1346 std::sort(live_stack_->Begin(), live_stack_->End());
1347 // Perform the verification.
1348 VerifyObjectVisitor visitor(this);
1349 GetLiveBitmap()->Visit(visitor);
1350 // We don't want to verify the objects in the allocation stack since they themselves may be
1351 // pointing to dead objects if they are not reachable.
1352 if (visitor.Failed()) {
1353 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001354 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001355 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001356 return true;
1357}
1358
1359class VerifyReferenceCardVisitor {
1360 public:
1361 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1362 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1363 Locks::heap_bitmap_lock_)
1364 : heap_(heap),
1365 failed_(failed) {
1366 }
1367
1368 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1369 // analysis.
1370 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1371 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001372 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001373 CardTable* card_table = heap_->GetCardTable();
1374 // If the object is not dirty and it is referencing something in the live stack other than
1375 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001376 if (!card_table->AddrIsInCardTable(obj)) {
1377 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1378 *failed_ = true;
1379 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001380 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001381 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1382 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1383 LOG(ERROR) << "Object " << obj << " found in live stack";
1384 }
1385 if (heap_->GetLiveBitmap()->Test(obj)) {
1386 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1387 }
1388 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1389 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1390
1391 // Print which field of the object is dead.
1392 if (!obj->IsObjectArray()) {
1393 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1394 CHECK(klass != NULL);
1395 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1396 CHECK(fields != NULL);
1397 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1398 const Field* cur = fields->Get(i);
1399 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1400 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1401 << PrettyField(cur);
1402 break;
1403 }
1404 }
1405 } else {
1406 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1407 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1408 if (object_array->Get(i) == ref) {
1409 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1410 }
1411 }
1412 }
1413
1414 *failed_ = true;
1415 }
1416 }
1417 }
1418 }
1419
1420 private:
1421 Heap* heap_;
1422 bool* failed_;
1423};
1424
1425class VerifyLiveStackReferences {
1426 public:
1427 VerifyLiveStackReferences(Heap* heap)
1428 : heap_(heap),
1429 failed_(false) {
1430
1431 }
1432
1433 void operator ()(const Object* obj) const
1434 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1435 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1436 MarkSweep::VisitObjectReferences(obj, visitor);
1437 }
1438
1439 bool Failed() const {
1440 return failed_;
1441 }
1442
1443 private:
1444 Heap* heap_;
1445 bool failed_;
1446};
1447
1448bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001449 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001450
1451 VerifyLiveStackReferences visitor(this);
1452 GetLiveBitmap()->Visit(visitor);
1453
1454 // We can verify objects in the live stack since none of these should reference dead objects.
1455 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1456 visitor(*it);
1457 }
1458
1459 if (visitor.Failed()) {
1460 DumpSpaces();
1461 return false;
1462 }
1463 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001464}
1465
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001466void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001467 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001468 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1469 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001470 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1471 ContinuousSpace* space = *it;
1472 // We never allocate into zygote spaces.
1473 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1474 (gc_type == kGcTypeFull &&
1475 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001476 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1477 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1478 if (live_bitmap != mark_bitmap) {
1479 live_bitmap_->ReplaceBitmap(live_bitmap, mark_bitmap);
1480 mark_bitmap_->ReplaceBitmap(mark_bitmap, live_bitmap);
1481 space->AsAllocSpace()->SwapBitmaps();
1482 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001483 }
1484 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001485 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001486}
1487
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001488void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001489 large_object_space_->SwapBitmaps();
1490 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1491 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001492}
1493
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001494void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001495 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001496 allocation_stack_.reset(live_stack_.release());
1497 live_stack_.reset(temp);
1498
1499 // Sort the live stack so that we can quickly binary search it later.
1500 if (VERIFY_OBJECT_ENABLED) {
1501 std::sort(live_stack_->Begin(), live_stack_->End());
1502 }
1503}
1504
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001505void Heap::ClearCards(TimingLogger& timings) {
1506 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1507 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1508 ContinuousSpace* space = *it;
1509 if (space->IsImageSpace()) {
1510 mod_union_table_->ClearCards(*it);
1511 timings.AddSplit("ModUnionClearCards");
1512 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1513 zygote_mod_union_table_->ClearCards(space);
1514 timings.AddSplit("ZygoteModUnionClearCards");
1515 } else {
1516 card_table_->ClearSpaceCards(space);
1517 timings.AddSplit("ClearCards");
1518 }
1519 }
1520}
1521
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001522void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1523 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001524 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001525 uint64_t gc_begin = NanoTime(), root_begin = 0, root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001526 std::stringstream gc_type_str;
1527 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001528
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001529 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001530 std::vector<byte*> dirty_cards;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001531 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001532 Object* cleared_references = NULL;
1533 {
1534 MarkSweep mark_sweep(mark_stack_.get());
1535 timings.AddSplit("ctor");
1536
1537 mark_sweep.Init();
1538 timings.AddSplit("Init");
1539
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001541 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001542
Mathieu Chartier0325e622012-09-05 14:22:51 -07001543 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001544 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1545 // accidentally un-mark roots.
1546 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001547 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001548 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1549 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001550 }
1551 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001552 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001553 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1554 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001555 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001556 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001557 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1558 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001559 }
1560 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001561 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001562 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001563 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001564 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1565 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001566 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001567 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001568 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001569
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001570 mark_sweep.MarkRootsCheckpoint();
1571 timings.AddSplit("MarkRootsCheckpoint");
1572
1573 {
1574 root_begin = NanoTime();
1575
1576 // Suspend all threads are get exclusive access to the heap.
1577 thread_list->SuspendAll();
1578 timings.AddSplit("SuspendAll");
1579 Locks::mutator_lock_->AssertExclusiveHeld(self);
1580
1581 if (verify_pre_gc_heap_) {
1582 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1583 if (!VerifyHeapReferences()) {
1584 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1585 }
1586 timings.AddSplit("VerifyHeapReferencesPreGC");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001587 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001588
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001589 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1590 SwapStacks();
1591
1592 // Check that all objects which reference things in the live stack are on dirty cards.
1593 if (verify_missing_card_marks_) {
1594 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1595 // Sort the live stack so that we can quickly binary search it later.
1596 std::sort(live_stack_->Begin(), live_stack_->End());
1597 if (!VerifyMissingCardMarks()) {
1598 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1599 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001600 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001601
1602 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1603 // TODO: Investigate using a mark stack instead of a vector.
1604 if (gc_type == kGcTypeSticky) {
1605 dirty_cards.reserve(4 * KB);
1606 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1607 card_table_->GetDirtyCards(*it, dirty_cards);
1608 }
1609 timings.AddSplit("GetDirtyCards");
1610 }
1611
1612 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1613 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001614 }
1615
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001616 if (verify_mod_union_table_) {
1617 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1618 zygote_mod_union_table_->Update();
1619 zygote_mod_union_table_->Verify();
1620 mod_union_table_->Update();
1621 mod_union_table_->Verify();
1622 }
1623
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001624 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1625 thread_list->ResumeAll();
1626 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001627 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001628 root_end = NanoTime();
1629 timings.AddSplit("RootEnd");
1630
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001631 // Mark the roots which we can do concurrently.
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001632 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001633 mark_sweep.MarkConcurrentRoots();
1634 timings.AddSplit("MarkConcurrentRoots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001635 mark_sweep.MarkNonThreadRoots();
1636 timings.AddSplit("MarkNonThreadRoots");
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001637
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001638 if (gc_type != kGcTypeSticky) {
1639 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1640 // knowing that new allocations won't be marked as live.
1641 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1642 live_stack_.get());
1643 timings.AddSplit("MarkStackAsLive");
1644 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001645
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001646 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1647
Mathieu Chartier0325e622012-09-05 14:22:51 -07001648 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001649 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001650 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001651 } else {
1652 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001653 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001654 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655 }
1656 // Release share on mutator_lock_ and then get exclusive access.
1657 dirty_begin = NanoTime();
1658 thread_list->SuspendAll();
1659 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001660 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001661
1662 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001663 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001664
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001665 // Re-mark root set.
1666 mark_sweep.ReMarkRoots();
1667 timings.AddSplit("ReMarkRoots");
1668
1669 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001670 mark_sweep.RecursiveMarkDirtyObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001671 timings.AddSplit("RecursiveMarkDirtyObjects");
1672 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001673
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001674 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001675 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001676
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001677 mark_sweep.ProcessReferences(clear_soft_references);
1678 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001679 }
1680
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001681 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1682 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001683 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001684 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001685 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001686 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001687 // We only sweep over the live stack, and the live stack should not intersect with the
1688 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001689 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1690 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001691 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001692#ifndef NDEBUG
1693 if (gc_type == kGcTypeSticky) {
1694 // Make sure everything in the live stack isn't something we unmarked.
1695 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1696 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001697 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1698 << "Unmarked object " << *it << " in the live stack";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001699 }
1700 } else {
1701 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001702 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001703 }
1704 }
1705#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001706 }
1707
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001708 if (kIsDebugBuild) {
1709 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001710 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001711 mark_sweep.VerifyImageRoots();
1712 timings.AddSplit("VerifyImageRoots");
1713 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001714
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001715 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001716 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001717 // Swapping bound bitmaps does nothing.
1718 SwapBitmaps(kGcTypeFull);
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001719 if (!VerifyHeapReferences()) {
1720 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001721 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001722 SwapBitmaps(kGcTypeFull);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001723 timings.AddSplit("VerifyHeapReferencesPostGC");
1724 }
1725
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001726 thread_list->ResumeAll();
1727 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001728 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001729
1730 {
1731 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001732 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001733 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001734 mark_sweep.Sweep(timings, gc_type == kGcTypePartial, false);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001735 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001736 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001737 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001738 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001739 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001740 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001741 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001742 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001743 }
1744
1745 {
1746 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1747 // Unbind the live and mark bitmaps.
1748 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001749
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001750 // Swap the live and mark bitmaps for each space which we modified space. This is an
1751 // optimization that enables us to not clear live bits inside of the sweep.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001752 if (gc_type == kGcTypeSticky) {
1753 SwapLargeObjects();
1754 } else {
1755 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001756 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001757 timings.AddSplit("SwapBitmaps");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001758 }
1759
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001760 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001761 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001762 mark_sweep.VerifySystemWeaks();
1763 timings.AddSplit("VerifySystemWeaks");
1764 }
1765
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001766 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001767 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001768 total_bytes_freed_ += bytes_freed;
1769 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001770 }
1771
1772 GrowForUtilization();
1773 timings.AddSplit("GrowForUtilization");
1774
1775 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001776 timings.AddSplit("EnqueueClearedReferences");
1777
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001778 RequestHeapTrim();
1779 timings.AddSplit("Finish");
1780
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001781 // If the GC was slow, then print timings in the log.
1782 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1783 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001784 uint64_t duration = (NanoTime() - gc_begin) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001785 total_paused_time_ += pause_roots + pause_dirty;
Mathieu Chartier0051be62012-10-12 17:47:11 -07001786 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5) ||
1787 (gc_cause == kGcCauseForAlloc && duration > MsToNs(20))) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001788 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001789 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001790 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001791 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001792 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001793 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001794 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1795 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001796 if (VLOG_IS_ON(heap)) {
1797 timings.Dump();
1798 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001799 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001800
Mathieu Chartier0325e622012-09-05 14:22:51 -07001801 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1802 logger->Start();
1803 logger->AddLogger(timings);
1804 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001805}
1806
Ian Rogers81d425b2012-09-27 16:03:43 -07001807GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001808 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001809 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001810 bool do_wait;
1811 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001812 {
1813 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001814 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001815 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001816 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001817 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001818 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001819 // We must wait, change thread state then sleep on gc_complete_cond_;
1820 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1821 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001822 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001823 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001824 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001825 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001826 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001827 wait_time = NanoTime() - wait_start;;
1828 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001829 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001830 if (wait_time > MsToNs(5)) {
1831 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1832 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001833 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001834 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001835 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001836}
1837
Elliott Hughesc967f782012-04-16 10:23:15 -07001838void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001839 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1840 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001841 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001842}
1843
1844size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001845 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001846}
1847
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001848void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001849 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001850 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001851 << PrettySize(GetMaxMemory());
1852 max_allowed_footprint = GetMaxMemory();
1853 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001854 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001855}
1856
Carl Shapiro69759ea2011-07-21 18:13:35 -07001857void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001858 // We know what our utilization is at this moment.
1859 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001860 size_t target_size = num_bytes_allocated_ / GetTargetHeapUtilization();
Mathieu Chartier0051be62012-10-12 17:47:11 -07001861 if (target_size > num_bytes_allocated_ + max_free_) {
1862 target_size = num_bytes_allocated_ + max_free_;
1863 } else if (target_size < num_bytes_allocated_ + min_free_) {
1864 target_size = num_bytes_allocated_ + min_free_;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001865 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001866
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001867 // Calculate when to perform the next ConcurrentGC.
1868 if (GetFreeMemory() < concurrent_min_free_) {
1869 // Not enough free memory to perform concurrent GC.
1870 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1871 } else {
1872 // Start a concurrent Gc when we get close to the target size.
1873 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001874 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001875
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001876 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001877}
1878
jeffhaoc1160702011-10-27 15:48:45 -07001879void Heap::ClearGrowthLimit() {
jeffhaoc1160702011-10-27 15:48:45 -07001880 alloc_space_->ClearGrowthLimit();
1881}
1882
Elliott Hughesadb460d2011-10-05 17:02:34 -07001883void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001884 MemberOffset reference_queue_offset,
1885 MemberOffset reference_queueNext_offset,
1886 MemberOffset reference_pendingNext_offset,
1887 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001888 reference_referent_offset_ = reference_referent_offset;
1889 reference_queue_offset_ = reference_queue_offset;
1890 reference_queueNext_offset_ = reference_queueNext_offset;
1891 reference_pendingNext_offset_ = reference_pendingNext_offset;
1892 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1893 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1894 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1895 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1896 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1897 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1898}
1899
1900Object* Heap::GetReferenceReferent(Object* reference) {
1901 DCHECK(reference != NULL);
1902 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1903 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1904}
1905
1906void Heap::ClearReferenceReferent(Object* reference) {
1907 DCHECK(reference != NULL);
1908 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1909 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1910}
1911
1912// Returns true if the reference object has not yet been enqueued.
1913bool Heap::IsEnqueuable(const Object* ref) {
1914 DCHECK(ref != NULL);
1915 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1916 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1917 return (queue != NULL) && (queue_next == NULL);
1918}
1919
1920void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1921 DCHECK(ref != NULL);
1922 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1923 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1924 EnqueuePendingReference(ref, cleared_reference_list);
1925}
1926
1927void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1928 DCHECK(ref != NULL);
1929 DCHECK(list != NULL);
1930
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001931 // TODO: Remove this lock, use atomic stacks for storing references.
1932 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001933 if (*list == NULL) {
1934 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1935 *list = ref;
1936 } else {
1937 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1938 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1939 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1940 }
1941}
1942
1943Object* Heap::DequeuePendingReference(Object** list) {
1944 DCHECK(list != NULL);
1945 DCHECK(*list != NULL);
1946 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1947 Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001948
1949 // TODO: Remove this lock, use atomic stacks for storing references.
1950 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001951 if (*list == head) {
1952 ref = *list;
1953 *list = NULL;
1954 } else {
1955 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1956 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1957 ref = head;
1958 }
1959 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1960 return ref;
1961}
1962
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001963void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001964 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001965 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001966 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001967 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1968 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001969}
1970
1971size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001972 return num_bytes_allocated_;
1973}
1974
1975size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001976 size_t total = 0;
1977 // TODO: C++0x
1978 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1979 Space* space = *it;
1980 if (space->IsAllocSpace()) {
1981 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1982 }
1983 }
1984 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001985}
1986
1987size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001988 return concurrent_start_size_;
1989}
1990
1991size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001992 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001993}
1994
1995void Heap::EnqueueClearedReferences(Object** cleared) {
1996 DCHECK(cleared != NULL);
1997 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001998 // When a runtime isn't started there are no reference queues to care about so ignore.
1999 if (LIKELY(Runtime::Current()->IsStarted())) {
2000 ScopedObjectAccess soa(Thread::Current());
2001 JValue args[1];
2002 args[0].SetL(*cleared);
2003 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
2004 args, NULL);
2005 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07002006 *cleared = NULL;
2007 }
2008}
2009
Ian Rogers1f539342012-10-03 21:09:42 -07002010void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07002011 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07002012 Runtime* runtime = Runtime::Current();
2013 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
2014 !runtime->IsConcurrentGcEnabled()) {
2015 return;
2016 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002017 {
2018 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2019 if (runtime->IsShuttingDown()) {
2020 return;
2021 }
2022 }
2023 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002024 return;
2025 }
2026
2027 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07002028 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002029 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2030 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002031 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2032 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002033 CHECK(!env->ExceptionCheck());
2034 requesting_gc_ = false;
2035}
2036
Ian Rogers81d425b2012-09-27 16:03:43 -07002037void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002038 {
2039 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2040 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2041 return;
2042 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002043 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002044
Ian Rogers81d425b2012-09-27 16:03:43 -07002045 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002046 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002047 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002048 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002049 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002050 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002051 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002052 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002053 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002054}
2055
Mathieu Chartier3056d0c2012-10-19 10:49:56 -07002056void Heap::Trim() {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002057 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002058}
2059
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002060void Heap::RequestHeapTrim() {
2061 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2062 // because that only marks object heads, so a large array looks like lots of empty space. We
2063 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2064 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2065 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2066 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002067 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002068 float utilization =
2069 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2070 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2071 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2072 // heap trim occurred in the last two seconds.
2073 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002074 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002075
2076 Thread* self = Thread::Current();
2077 {
2078 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2079 Runtime* runtime = Runtime::Current();
2080 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2081 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2082 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2083 // as we don't hold the lock while requesting the trim).
2084 return;
2085 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002086 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002087 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002088 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002089 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2090 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002091 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2092 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002093 CHECK(!env->ExceptionCheck());
2094}
2095
Carl Shapiro69759ea2011-07-21 18:13:35 -07002096} // namespace art