blob: 33f83660bb0e06376460170d795f1813bb94c6a7 [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 Chartier0051be62012-10-12 17:47:11 -070048const double Heap::kDefaultTargetUtilization = 0.5;
49
Elliott Hughesae80b492012-04-24 10:43:17 -070050static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080051 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080052 std::vector<std::string> boot_class_path;
53 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070054 if (boot_class_path.empty()) {
55 LOG(FATAL) << "Failed to generate image because no boot class path specified";
56 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080057
58 std::vector<char*> arg_vector;
59
60 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070061 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080062 const char* dex2oat = dex2oat_string.c_str();
63 arg_vector.push_back(strdup(dex2oat));
64
65 std::string image_option_string("--image=");
66 image_option_string += image_file_name;
67 const char* image_option = image_option_string.c_str();
68 arg_vector.push_back(strdup(image_option));
69
70 arg_vector.push_back(strdup("--runtime-arg"));
71 arg_vector.push_back(strdup("-Xms64m"));
72
73 arg_vector.push_back(strdup("--runtime-arg"));
74 arg_vector.push_back(strdup("-Xmx64m"));
75
76 for (size_t i = 0; i < boot_class_path.size(); i++) {
77 std::string dex_file_option_string("--dex-file=");
78 dex_file_option_string += boot_class_path[i];
79 const char* dex_file_option = dex_file_option_string.c_str();
80 arg_vector.push_back(strdup(dex_file_option));
81 }
82
83 std::string oat_file_option_string("--oat-file=");
84 oat_file_option_string += image_file_name;
85 oat_file_option_string.erase(oat_file_option_string.size() - 3);
86 oat_file_option_string += "oat";
87 const char* oat_file_option = oat_file_option_string.c_str();
88 arg_vector.push_back(strdup(oat_file_option));
89
90 arg_vector.push_back(strdup("--base=0x60000000"));
91
Elliott Hughes48436bb2012-02-07 15:23:28 -080092 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080093 LOG(INFO) << command_line;
94
Elliott Hughes48436bb2012-02-07 15:23:28 -080095 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -080096 char** argv = &arg_vector[0];
97
98 // fork and exec dex2oat
99 pid_t pid = fork();
100 if (pid == 0) {
101 // no allocation allowed between fork and exec
102
103 // change process groups, so we don't get reaped by ProcessManager
104 setpgid(0, 0);
105
106 execv(dex2oat, argv);
107
108 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
109 return false;
110 } else {
111 STLDeleteElements(&arg_vector);
112
113 // wait for dex2oat to finish
114 int status;
115 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
116 if (got_pid != pid) {
117 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
118 return false;
119 }
120 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
121 LOG(ERROR) << dex2oat << " failed: " << command_line;
122 return false;
123 }
124 }
125 return true;
126}
127
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700128void Heap::UnReserveOatFileAddressRange() {
129 oat_file_map_.reset(NULL);
130}
131
Mathieu Chartier0051be62012-10-12 17:47:11 -0700132Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
133 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700134 const std::string& original_image_file_name, bool concurrent_gc)
135 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800136 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137 concurrent_gc_(concurrent_gc),
138 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800139 card_marking_disabled_(false),
140 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700141 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700142 enforce_heap_growth_rate_(false),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700143 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700144 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700145 concurrent_start_size_(128 * KB),
146 concurrent_min_free_(256 * KB),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700147 concurrent_start_bytes_(initial_size - concurrent_start_size_),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700148 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700149 total_bytes_freed_(0),
150 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700151 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800152 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700153 verify_missing_card_marks_(false),
154 verify_system_weaks_(false),
155 verify_pre_gc_heap_(false),
156 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700157 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700158 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700159 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700160 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700161 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700162 requesting_gc_(false),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700163 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800164 reference_referent_offset_(0),
165 reference_queue_offset_(0),
166 reference_queueNext_offset_(0),
167 reference_pendingNext_offset_(0),
168 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700169 min_free_(min_free),
170 max_free_(max_free),
171 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700172 total_paused_time_(0),
173 total_wait_time_(0),
174 measure_allocation_time_(false),
175 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700176 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800177 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800178 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700179 }
180
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700181 live_bitmap_.reset(new HeapBitmap(this));
182 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700183
Ian Rogers30fab402012-01-23 15:43:46 -0800184 // Requested begin for the alloc space, to follow the mapped image and oat files
185 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800186 std::string image_file_name(original_image_file_name);
187 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700188 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700189
Brian Carlstrom5643b782012-02-05 12:32:53 -0800190 if (OS::FileExists(image_file_name.c_str())) {
191 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700192 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800193 } else {
194 // If the /system file didn't exist, we need to use one from the art-cache.
195 // If the cache file exists, try to open, but if it fails, regenerate.
196 // If it does not exist, generate.
197 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
198 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700199 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800200 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700201 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700202 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700203 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800204 }
205 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700206
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700207 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700208 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800209 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
210 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700211 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
212 CHECK_GT(oat_end_addr, image_space->End());
213
214 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
215 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
216 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
217 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
218 reinterpret_cast<byte*>(reserve_begin),
219 reserve_end - reserve_begin, PROT_READ));
220
Ian Rogers30fab402012-01-23 15:43:46 -0800221 if (oat_end_addr > requested_begin) {
222 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700223 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700224 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700225 }
226
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700227 // Allocate the large object space.
228 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700229 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
230 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
231
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700232 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
233 growth_limit, capacity,
234 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700235 alloc_space_ = alloc_space.release();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700236 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700237 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700238 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700239
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700240 // Spaces are sorted in order of Begin().
241 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700242 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
243 if (spaces_.back()->IsAllocSpace()) {
244 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
245 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700246
Ian Rogers30fab402012-01-23 15:43:46 -0800247 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700248 // TODO: C++0x
249 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
250 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800251 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700252 ImageSpace* image_space = space->AsImageSpace();
253 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800254 }
255 }
256
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800257 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700258 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
259 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700260
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700261 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
262 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700263
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700264 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
265 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700266
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700267 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700268 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700269
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700270 // Max stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700271 static const size_t default_mark_stack_size = 64 * KB;
272 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
273 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700274 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700275 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
276 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700277
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800278 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700279 // but we can create the heap lock now. We don't create it earlier to
280 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700281 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700282 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
283 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700284
Mathieu Chartier0325e622012-09-05 14:22:51 -0700285 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700286 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
287 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700288 std::ostringstream name;
289 name << static_cast<GcType>(i);
290 cumulative_timings_.Put(static_cast<GcType>(i),
291 new CumulativeLogger(name.str().c_str(), true));
292 }
293
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800294 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800295 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700296 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700297}
298
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700299// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700300struct SpaceSorter {
301 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700302 return a->Begin() < b->Begin();
303 }
304};
305
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700306void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700307 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700308 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700309 DCHECK(space->GetLiveBitmap() != NULL);
310 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700311 DCHECK(space->GetMarkBitmap() != NULL);
312 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800313 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700314 if (space->IsAllocSpace()) {
315 alloc_space_ = space->AsAllocSpace();
316 }
317
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700318 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
319 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700320
321 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
322 // avoid redundant marking.
323 bool seen_zygote = false, seen_alloc = false;
324 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
325 Space* space = *it;
326 if (space->IsImageSpace()) {
327 DCHECK(!seen_zygote);
328 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700329 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700330 DCHECK(!seen_alloc);
331 seen_zygote = true;
332 } else if (space->IsAllocSpace()) {
333 seen_alloc = true;
334 }
335 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800336}
337
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700338void Heap::DumpGcPerformanceInfo() {
339 // Dump cumulative timings.
340 LOG(INFO) << "Dumping cumulative Gc timings";
341 uint64_t total_duration = 0;
342 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
343 it != cumulative_timings_.end(); ++it) {
344 CumulativeLogger* logger = it->second;
345 if (logger->GetTotalNs() != 0) {
346 logger->Dump();
347 total_duration += logger->GetTotalNs();
348 }
349 }
350 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
351 size_t total_objects_allocated = GetTotalObjectsAllocated();
352 size_t total_bytes_allocated = GetTotalBytesAllocated();
353 if (total_duration != 0) {
354 const double total_seconds = double(total_duration / 1000) / 1000000.0;
355 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
356 LOG(INFO) << "Mean GC size throughput: "
357 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
358 LOG(INFO) << "Mean GC object throughput: " << GetTotalObjectsFreed() / total_seconds << "/s";
359 }
360 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
361 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
362 if (measure_allocation_time_) {
363 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
364 LOG(INFO) << "Mean allocation time: "
365 << PrettyDuration(allocation_time / total_objects_allocated);
366 }
367 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time_);
368 LOG(INFO) << "Total waiting for Gc to complete time: " << PrettyDuration(total_wait_time_);
369}
370
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800371Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700372 // If we don't reset then the mark stack complains in it's destructor.
373 allocation_stack_->Reset();
374 live_stack_->Reset();
375
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800376 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800377 // We can't take the heap lock here because there might be a daemon thread suspended with the
378 // heap lock held. We know though that no non-daemon threads are executing, and we know that
379 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
380 // 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 -0700381 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700382 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700383 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700384}
385
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700386ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700387 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700388 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
389 if ((*it)->Contains(obj)) {
390 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700391 }
392 }
393 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
394 return NULL;
395}
396
397ImageSpace* Heap::GetImageSpace() {
398 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700399 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
400 if ((*it)->IsImageSpace()) {
401 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700402 }
403 }
404 return NULL;
405}
406
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700407DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700408 return alloc_space_;
409}
410
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700411static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700412 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700413 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700414 size_t chunk_free_bytes = chunk_size - used_bytes;
415 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
416 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700417 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700418}
419
Ian Rogers50b35e22012-10-04 10:09:15 -0700420Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
422 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
423 strlen(ClassHelper(c).GetDescriptor()) == 0);
424 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700425
426 Object* obj = NULL;
427 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700428 uint64_t allocation_start = 0;
429 if (measure_allocation_time_) {
430 allocation_start = NanoTime();
431 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700432
433 // We need to have a zygote space or else our newly allocated large object can end up in the
434 // Zygote resulting in it being prematurely freed.
435 // We can only do this for primive objects since large objects will not be within the card table
436 // range. This also means that we rely on SetClass not dirtying the object's card.
437 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700438 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700439 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700440 // Make sure that our large object didn't get placed anywhere within the space interval or else
441 // it breaks the immune range.
442 DCHECK(obj == NULL ||
443 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
444 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700445 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700446 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700447
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700448 // Ensure that we did not allocate into a zygote space.
449 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
450 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700451 }
452
Mathieu Chartier037813d2012-08-23 16:44:59 -0700453 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700455
456 // Record allocation after since we want to use the atomic add for the atomic fence to guard
457 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700458 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700459
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460 if (Dbg::IsAllocTrackingEnabled()) {
461 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700462 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700463 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700464 // We already have a request pending, no reason to start more until we update
465 // concurrent_start_bytes_.
466 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700468 SirtRef<Object> ref(self, obj);
469 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 }
471 VerifyObject(obj);
472
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700473 if (measure_allocation_time_) {
474 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
475 }
476
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 return obj;
478 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700479 int64_t total_bytes_free = GetFreeMemory();
480 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700482 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
483 if ((*it)->IsAllocSpace()) {
484 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700485 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700486 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700487
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700488 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 -0700489 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700490 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700491 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700492}
493
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700494bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700495 // Note: we deliberately don't take the lock here, and mustn't test anything that would
496 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700497 if (obj == NULL) {
498 return true;
499 }
500 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700501 return false;
502 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800503 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800504 if (spaces_[i]->Contains(obj)) {
505 return true;
506 }
507 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700508 // Note: Doing this only works for the free list version of the large object space since the
509 // multiple memory map version uses a lock to do the contains check.
510 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700511}
512
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700513bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700514 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700515 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700516}
517
Elliott Hughes3e465b12011-09-02 18:26:12 -0700518#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700519void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700520 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700521 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700522 return;
523 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700524 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700525}
526#endif
527
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700528void Heap::DumpSpaces() {
529 // TODO: C++0x auto
530 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700531 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700532 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
533 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
534 LOG(INFO) << space << " " << *space << "\n"
535 << live_bitmap << " " << *live_bitmap << "\n"
536 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700537 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700538 if (large_object_space_.get() != NULL) {
539 large_object_space_->Dump(LOG(INFO));
540 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700541}
542
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700543void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700544 if (!IsAligned<kObjectAlignment>(obj)) {
545 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700546 }
547
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700548 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
549 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700550 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700551 // Check the allocation stack / live stack.
552 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
553 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
554 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700555 if (large_object_space_->GetLiveObjects()->Test(obj)) {
556 DumpSpaces();
557 LOG(FATAL) << "Object is dead: " << obj;
558 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700559 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700560 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700561
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700562 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700563 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700564 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
565 Object::ClassOffset().Int32Value();
566 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
567 if (c == NULL) {
568 LOG(FATAL) << "Null class in object: " << obj;
569 } else if (!IsAligned<kObjectAlignment>(c)) {
570 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
571 } else if (!GetLiveBitmap()->Test(c)) {
572 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
573 }
574 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
575 // Note: we don't use the accessors here as they have internal sanity checks
576 // that we don't want to run
577 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
578 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
579 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
580 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
581 CHECK_EQ(c_c, c_c_c);
582 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700583}
584
Brian Carlstrom78128a62011-09-15 17:21:19 -0700585void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700586 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700587 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700588}
589
590void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700591 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700592 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700593}
594
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700595void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700596 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700597 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700598 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700599
600 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700601 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700602 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700603 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700604
605 // TODO: Update these atomically.
606 RuntimeStats* global_stats = Runtime::Current()->GetStats();
607 ++global_stats->allocated_objects;
608 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700609 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700610
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700611 // This is safe to do since the GC will never free objects which are neither in the allocation
612 // stack or the live bitmap.
613 while (!allocation_stack_->AtomicPushBack(obj)) {
614 Thread* self = Thread::Current();
615 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
616 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
617 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
618 self->TransitionFromSuspendedToRunnable();
619 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700620}
621
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700622void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700623 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
624 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700625
626 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700627 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700628 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700629 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700630
631 // TODO: Do this concurrently.
632 RuntimeStats* global_stats = Runtime::Current()->GetStats();
633 global_stats->freed_objects += freed_objects;
634 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700635 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700636}
637
Ian Rogers50b35e22012-10-04 10:09:15 -0700638Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700639 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700640 if (enforce_heap_growth_rate_ && num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
641 if (grow) {
642 // Grow the heap by alloc_size extra bytes.
643 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
644 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
645 << " for a " << PrettySize(alloc_size) << " allocation";
646 } else {
647 return NULL;
648 }
649 }
650
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700651 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700652 // Completely out of memory.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700653 return NULL;
654 }
655
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700656 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700657}
658
Ian Rogers50b35e22012-10-04 10:09:15 -0700659Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700660 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
661 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700662 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700663 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700664
Ian Rogers50b35e22012-10-04 10:09:15 -0700665 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700666 if (ptr != NULL) {
667 return ptr;
668 }
669
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700670 // The allocation failed. If the GC is running, block until it completes, and then retry the
671 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700672 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700673 if (last_gc != kGcTypeNone) {
674 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700675 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700676 if (ptr != NULL) {
677 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700678 }
679 }
680
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700681 // Loop through our different Gc types and try to Gc until we get enough free memory.
682 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
683 bool run_gc = false;
684 GcType gc_type = static_cast<GcType>(i);
685 switch (gc_type) {
686 case kGcTypeSticky: {
687 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700688 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
689 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700690 break;
691 }
692 case kGcTypePartial:
693 run_gc = have_zygote_space_;
694 break;
695 case kGcTypeFull:
696 run_gc = true;
697 break;
698 default:
699 break;
700 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700701
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700702 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700703 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
704
705 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700706 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700707 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
708 i = static_cast<size_t>(gc_type_ran);
709 self->TransitionFromSuspendedToRunnable();
710
711 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700712 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700713 if (ptr != NULL) {
714 return ptr;
715 }
716 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700717 }
718
719 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700720 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700721 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700722 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700723 return ptr;
724 }
725
Elliott Hughes81ff3182012-03-23 20:35:56 -0700726 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
727 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
728 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700729
Elliott Hughes418dfe72011-10-06 18:56:27 -0700730 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700731 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
732 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700733
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700734 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700735 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700736 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700737 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700738 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700739}
740
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700741void Heap::SetTargetHeapUtilization(float target) {
742 DCHECK_GT(target, 0.0f); // asserted in Java code
743 DCHECK_LT(target, 1.0f);
744 target_utilization_ = target;
745}
746
747int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700748 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700749}
750
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700751int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700752 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700753}
754
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700755int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700756 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700757}
758
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700759size_t Heap::GetTotalBytesFreed() const {
760 return total_bytes_freed_;
761}
762
763size_t Heap::GetTotalObjectsFreed() const {
764 return total_objects_freed_;
765}
766
767size_t Heap::GetTotalObjectsAllocated() const {
768 size_t total = large_object_space_->GetTotalObjectsAllocated();
769 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
770 Space* space = *it;
771 if (space->IsAllocSpace()) {
772 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
773 }
774 }
775 return total;
776}
777
778size_t Heap::GetTotalBytesAllocated() const {
779 size_t total = large_object_space_->GetTotalBytesAllocated();
780 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
781 Space* space = *it;
782 if (space->IsAllocSpace()) {
783 total += space->AsAllocSpace()->GetTotalBytesAllocated();
784 }
785 }
786 return total;
787}
788
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700789class InstanceCounter {
790 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700791 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700792 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700793 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700794
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700795 }
796
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700797 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
798 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700799 if (count_assignable_) {
800 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700801 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700802 }
803 } else {
804 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700805 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700806 }
807 }
808 }
809
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700810 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700811 Class* class_;
812 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700813 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700814};
815
816int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700817 size_t count = 0;
818 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700819 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700820 GetLiveBitmap()->Visit(counter);
821 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700822}
823
Ian Rogers30fab402012-01-23 15:43:46 -0800824void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700825 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
826 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700827 Thread* self = Thread::Current();
828 WaitForConcurrentGcToComplete(self);
829 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700830 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
831 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700832}
833
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700834void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700835 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700836 Thread* self = Thread::Current();
837 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700838
839 // Try to see if we have any Zygote spaces.
840 if (have_zygote_space_) {
841 return;
842 }
843
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700844 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
845
846 {
847 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700848 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700849 FlushAllocStack();
850 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700851
852 // Replace the first alloc space we find with a zygote space.
853 // TODO: C++0x auto
854 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
855 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700856 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700857
858 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
859 // of the remaining available heap memory.
860 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700861 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700862
863 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700864 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700865 AddSpace(alloc_space_);
866 have_zygote_space_ = true;
867 break;
868 }
869 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700870
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700871 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700872 // TODO: C++0x
873 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
874 it != cumulative_timings_.end(); ++it) {
875 it->second->Reset();
876 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700877}
878
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700879void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700880 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
881 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700882 allocation_stack_->Reset();
883}
884
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700885size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700886 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700887}
888
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700889void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
890 Object** limit = stack->End();
891 for (Object** it = stack->Begin(); it != limit; ++it) {
892 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700893 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700894 if (LIKELY(bitmap->HasAddress(obj))) {
895 bitmap->Set(obj);
896 } else {
897 large_objects->Set(obj);
898 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700899 }
900}
901
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700902void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
903 Object** limit = stack->End();
904 for (Object** it = stack->Begin(); it != limit; ++it) {
905 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700906 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700907 if (LIKELY(bitmap->HasAddress(obj))) {
908 bitmap->Clear(obj);
909 } else {
910 large_objects->Clear(obj);
911 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700912 }
913}
914
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700915GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700916 Thread* self = Thread::Current();
917 Locks::mutator_lock_->AssertNotHeld(self);
918 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700919
Ian Rogers120f1c72012-09-28 17:17:10 -0700920 if (self->IsHandlingStackOverflow()) {
921 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
922 }
923
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700924 // Ensure there is only one GC at a time.
925 bool start_collect = false;
926 while (!start_collect) {
927 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700928 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700929 if (!is_gc_running_) {
930 is_gc_running_ = true;
931 start_collect = true;
932 }
933 }
934 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700935 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700936 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
937 // Not doing at the moment to ensure soft references are cleared.
938 }
939 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700940 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700941
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700942 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
943 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
944 ++Thread::Current()->GetStats()->gc_for_alloc_count;
945 }
946
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700947 // We need to do partial GCs every now and then to avoid the heap growing too much and
948 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700949 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700950 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700951 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700952 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700953 sticky_gc_count_ = 0;
954 }
955
Mathieu Chartier637e3482012-08-17 10:41:32 -0700956 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700957 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700958 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700959 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700960 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700961 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700962
Ian Rogers15bf2d32012-08-28 17:33:04 -0700963 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700964 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700965 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700966 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700967 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -0700968 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700969 }
970 // Inform DDMS that a GC completed.
971 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700972 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700973}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700974
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700975void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
976 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700977 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700978
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700979 std::stringstream gc_type_str;
980 gc_type_str << gc_type << " ";
981
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700982 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700983 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700984 ThreadList* thread_list = Runtime::Current()->GetThreadList();
985 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700986 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700987 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700988
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700989 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700990 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700991 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700992 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700993 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700994 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700995
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700996 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700997 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700998 if (!VerifyHeapReferences()) {
999 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1000 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001001 timings.AddSplit("VerifyHeapReferencesPreGC");
1002 }
1003
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001004 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001005 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001006
1007 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1008 // TODO: Investigate using a mark stack instead of a vector.
1009 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001010 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001011 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1012 card_table_->GetDirtyCards(*it, dirty_cards);
1013 }
1014 }
1015
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001016 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001017 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001018
Ian Rogers120f1c72012-09-28 17:17:10 -07001019 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001020 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001021 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1022 // accidentally un-mark roots.
1023 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001024 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001025 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1026 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001027 }
1028 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001029 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001030
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001031 // We can assume that everything from the start of the first space to the alloc space is marked.
1032 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1033 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001034 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001035 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001036 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1037 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001038 }
1039 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001040 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001041 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001042 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001043 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1044 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001045 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001046 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001047
Carl Shapiro58551df2011-07-24 03:09:51 -07001048 mark_sweep.MarkRoots();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001049 mark_sweep.MarkConcurrentRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001050 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001051
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001052 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001053 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -07001054
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001055 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1056
1057 if (gc_type != kGcTypeSticky) {
1058 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1059 live_stack_.get());
1060 timings.AddSplit("MarkStackAsLive");
1061 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001062
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001063 if (verify_mod_union_table_) {
1064 zygote_mod_union_table_->Update();
1065 zygote_mod_union_table_->Verify();
1066 mod_union_table_->Update();
1067 mod_union_table_->Verify();
1068 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001069
1070 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001071 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001072 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001073 } else {
1074 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1075 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001076 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001077
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001078 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001079 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001080 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001081
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001082#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001083 // Verify that we only reach marked objects from the image space
1084 mark_sweep.VerifyImageRoots();
1085 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001086#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001087
Mathieu Chartier0325e622012-09-05 14:22:51 -07001088 if (gc_type != kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001089 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1090 timings.AddSplit("Sweep");
1091 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001092 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001093 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001094 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001095 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001096 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001097 live_stack_->Reset();
1098
1099 // Unbind the live and mark bitmaps.
1100 mark_sweep.UnBindBitmaps();
1101
1102 const bool swap = true;
1103 if (swap) {
1104 if (gc_type == kGcTypeSticky) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001105 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001106 } else {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001107 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001108 }
1109 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001110
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001111 if (verify_system_weaks_) {
1112 mark_sweep.VerifySystemWeaks();
1113 timings.AddSplit("VerifySystemWeaks");
1114 }
1115
Elliott Hughesadb460d2011-10-05 17:02:34 -07001116 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001117 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001118 total_bytes_freed_ += bytes_freed;
1119 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001120 }
1121
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001122 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001123 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001124 if (!VerifyHeapReferences()) {
1125 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1126 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001127 timings.AddSplit("VerifyHeapReferencesPostGC");
1128 }
1129
Carl Shapiro58551df2011-07-24 03:09:51 -07001130 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001131 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001132
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001133 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001134 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001135
1136 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001137 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001138 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001139
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001140 // If the GC was slow, then print timings in the log.
1141 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001142 total_paused_time_ += duration;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001143 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001144 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001145 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001146 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001147 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001148 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001149 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001150 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001151 if (VLOG_IS_ON(heap)) {
1152 timings.Dump();
1153 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001154 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001155
Mathieu Chartier0325e622012-09-05 14:22:51 -07001156 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1157 logger->Start();
1158 logger->AddLogger(timings);
1159 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001160}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001161
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001162void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001163 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001164 // 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 -07001165 // cards.
1166 return;
1167 }
1168
1169 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001170 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001171 zygote_mod_union_table_->Update();
1172 timings.AddSplit("UpdateZygoteModUnionTable");
1173
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001174 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001175 timings.AddSplit("ZygoteMarkReferences");
1176 }
1177
1178 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1179 mod_union_table_->Update();
1180 timings.AddSplit("UpdateModUnionTable");
1181
1182 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001183 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001184 timings.AddSplit("MarkImageToAllocSpaceReferences");
1185}
1186
1187void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1188 Object* obj = reinterpret_cast<Object*>(arg);
1189 if (root == obj) {
1190 LOG(INFO) << "Object " << obj << " is a root";
1191 }
1192}
1193
1194class ScanVisitor {
1195 public:
1196 void operator ()(const Object* obj) const {
1197 LOG(INFO) << "Would have rescanned object " << obj;
1198 }
1199};
1200
1201class VerifyReferenceVisitor {
1202 public:
1203 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001204 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1205 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001206 : heap_(heap),
1207 failed_(failed) {
1208 }
1209
1210 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1211 // analysis.
1212 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1213 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1214 // Verify that the reference is live.
1215 if (ref != NULL && !IsLive(ref)) {
1216 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001217 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1218 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001219
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001220 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001221 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1222 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1223 << "Obj type " << PrettyTypeOf(obj) << "\n"
1224 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001225 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001226 void* cover_begin = card_table->AddrFromCard(card_addr);
1227 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001228 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001229 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001230 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001231 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1232
1233 // Print out how the object is live.
1234 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001235 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1236 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001237 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1238 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1239 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001240 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1241 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001242 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001243 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001244 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001245 }
1246
1247 // Attempt to see if the card table missed the reference.
1248 ScanVisitor scan_visitor;
1249 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001250 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1251 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001252
1253 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001254 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001255 MarkSweep ms(mark_stack);
1256 ms.Init();
1257 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001258 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001259
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001260 // All the references should end up in the mark stack.
1261 ms.ScanRoot(obj);
1262 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001263 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001264 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001265 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001266 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001267 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001268 }
1269 }
1270 mark_stack->Reset();
1271
1272 // Search to see if any of the roots reference our object.
1273 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1274 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1275 *failed_ = true;
1276 }
1277 }
1278
1279 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1280 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1281 if (bitmap != NULL) {
1282 if (bitmap->Test(obj)) {
1283 return true;
1284 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001285 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001286 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001287 } else {
1288 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001289 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001290 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001291 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001292 // At this point we need to search the allocation since things in the live stack may get swept.
1293 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1294 return true;
1295 }
1296 // Not either in the live bitmap or allocation stack, so the object must be dead.
1297 return false;
1298 }
1299
1300 private:
1301 Heap* heap_;
1302 bool* failed_;
1303};
1304
1305class VerifyObjectVisitor {
1306 public:
1307 VerifyObjectVisitor(Heap* heap)
1308 : heap_(heap),
1309 failed_(false) {
1310
1311 }
1312
1313 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001314 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001315 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1316 MarkSweep::VisitObjectReferences(obj, visitor);
1317 }
1318
1319 bool Failed() const {
1320 return failed_;
1321 }
1322
1323 private:
1324 Heap* heap_;
1325 bool failed_;
1326};
1327
1328// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001329bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001330 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001331 // Lets sort our allocation stacks so that we can efficiently binary search them.
1332 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1333 std::sort(live_stack_->Begin(), live_stack_->End());
1334 // Perform the verification.
1335 VerifyObjectVisitor visitor(this);
1336 GetLiveBitmap()->Visit(visitor);
1337 // We don't want to verify the objects in the allocation stack since they themselves may be
1338 // pointing to dead objects if they are not reachable.
1339 if (visitor.Failed()) {
1340 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001341 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001342 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001343 return true;
1344}
1345
1346class VerifyReferenceCardVisitor {
1347 public:
1348 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1349 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1350 Locks::heap_bitmap_lock_)
1351 : heap_(heap),
1352 failed_(failed) {
1353 }
1354
1355 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1356 // analysis.
1357 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1358 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001359 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001360 CardTable* card_table = heap_->GetCardTable();
1361 // If the object is not dirty and it is referencing something in the live stack other than
1362 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001363 if (!card_table->AddrIsInCardTable(obj)) {
1364 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1365 *failed_ = true;
1366 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001367 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001368 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1369 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1370 LOG(ERROR) << "Object " << obj << " found in live stack";
1371 }
1372 if (heap_->GetLiveBitmap()->Test(obj)) {
1373 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1374 }
1375 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1376 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1377
1378 // Print which field of the object is dead.
1379 if (!obj->IsObjectArray()) {
1380 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1381 CHECK(klass != NULL);
1382 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1383 CHECK(fields != NULL);
1384 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1385 const Field* cur = fields->Get(i);
1386 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1387 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1388 << PrettyField(cur);
1389 break;
1390 }
1391 }
1392 } else {
1393 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1394 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1395 if (object_array->Get(i) == ref) {
1396 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1397 }
1398 }
1399 }
1400
1401 *failed_ = true;
1402 }
1403 }
1404 }
1405 }
1406
1407 private:
1408 Heap* heap_;
1409 bool* failed_;
1410};
1411
1412class VerifyLiveStackReferences {
1413 public:
1414 VerifyLiveStackReferences(Heap* heap)
1415 : heap_(heap),
1416 failed_(false) {
1417
1418 }
1419
1420 void operator ()(const Object* obj) const
1421 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1422 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1423 MarkSweep::VisitObjectReferences(obj, visitor);
1424 }
1425
1426 bool Failed() const {
1427 return failed_;
1428 }
1429
1430 private:
1431 Heap* heap_;
1432 bool failed_;
1433};
1434
1435bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001436 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001437
1438 VerifyLiveStackReferences visitor(this);
1439 GetLiveBitmap()->Visit(visitor);
1440
1441 // We can verify objects in the live stack since none of these should reference dead objects.
1442 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1443 visitor(*it);
1444 }
1445
1446 if (visitor.Failed()) {
1447 DumpSpaces();
1448 return false;
1449 }
1450 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001451}
1452
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001453void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001454 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001455 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1456 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001457 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1458 ContinuousSpace* space = *it;
1459 // We never allocate into zygote spaces.
1460 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1461 (gc_type == kGcTypeFull &&
1462 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001463 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1464 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1465 if (live_bitmap != mark_bitmap) {
1466 live_bitmap_->ReplaceBitmap(live_bitmap, mark_bitmap);
1467 mark_bitmap_->ReplaceBitmap(mark_bitmap, live_bitmap);
1468 space->AsAllocSpace()->SwapBitmaps();
1469 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001470 }
1471 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001472 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001473}
1474
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001475void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001476 large_object_space_->SwapBitmaps();
1477 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1478 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001479}
1480
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001481void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001482 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001483 allocation_stack_.reset(live_stack_.release());
1484 live_stack_.reset(temp);
1485
1486 // Sort the live stack so that we can quickly binary search it later.
1487 if (VERIFY_OBJECT_ENABLED) {
1488 std::sort(live_stack_->Begin(), live_stack_->End());
1489 }
1490}
1491
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001492void Heap::ClearCards(TimingLogger& timings) {
1493 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1494 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1495 ContinuousSpace* space = *it;
1496 if (space->IsImageSpace()) {
1497 mod_union_table_->ClearCards(*it);
1498 timings.AddSplit("ModUnionClearCards");
1499 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1500 zygote_mod_union_table_->ClearCards(space);
1501 timings.AddSplit("ZygoteModUnionClearCards");
1502 } else {
1503 card_table_->ClearSpaceCards(space);
1504 timings.AddSplit("ClearCards");
1505 }
1506 }
1507}
1508
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001509void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1510 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001511 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001512 uint64_t gc_begin = NanoTime(), root_begin = 0, root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001513 std::stringstream gc_type_str;
1514 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001515
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001516 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001517 std::vector<byte*> dirty_cards;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001518 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001519 Object* cleared_references = NULL;
1520 {
1521 MarkSweep mark_sweep(mark_stack_.get());
1522 timings.AddSplit("ctor");
1523
1524 mark_sweep.Init();
1525 timings.AddSplit("Init");
1526
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001527 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001528 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001529
Mathieu Chartier0325e622012-09-05 14:22:51 -07001530 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001531 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1532 // accidentally un-mark roots.
1533 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001534 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001535 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1536 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001537 }
1538 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001539 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001540 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1541 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001542 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001543 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001544 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1545 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001546 }
1547 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001548 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001549 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001550 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001551 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1552 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001553 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001554 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001555 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001556
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001557 mark_sweep.MarkRootsCheckpoint();
1558 timings.AddSplit("MarkRootsCheckpoint");
1559
1560 {
1561 root_begin = NanoTime();
1562
1563 // Suspend all threads are get exclusive access to the heap.
1564 thread_list->SuspendAll();
1565 timings.AddSplit("SuspendAll");
1566 Locks::mutator_lock_->AssertExclusiveHeld(self);
1567
1568 if (verify_pre_gc_heap_) {
1569 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1570 if (!VerifyHeapReferences()) {
1571 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1572 }
1573 timings.AddSplit("VerifyHeapReferencesPreGC");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001574 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001575
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001576 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1577 SwapStacks();
1578
1579 // Check that all objects which reference things in the live stack are on dirty cards.
1580 if (verify_missing_card_marks_) {
1581 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1582 // Sort the live stack so that we can quickly binary search it later.
1583 std::sort(live_stack_->Begin(), live_stack_->End());
1584 if (!VerifyMissingCardMarks()) {
1585 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1586 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001587 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001588
1589 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1590 // TODO: Investigate using a mark stack instead of a vector.
1591 if (gc_type == kGcTypeSticky) {
1592 dirty_cards.reserve(4 * KB);
1593 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1594 card_table_->GetDirtyCards(*it, dirty_cards);
1595 }
1596 timings.AddSplit("GetDirtyCards");
1597 }
1598
1599 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1600 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001601 }
1602
1603 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001604 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001605
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001606 if (verify_mod_union_table_) {
1607 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1608 zygote_mod_union_table_->Update();
1609 zygote_mod_union_table_->Verify();
1610 mod_union_table_->Update();
1611 mod_union_table_->Verify();
1612 }
1613
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001614 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1615 thread_list->ResumeAll();
1616 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001617 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001618 root_end = NanoTime();
1619 timings.AddSplit("RootEnd");
1620
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001621 // Mark the roots which we can do concurrently.
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001622 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001623 mark_sweep.MarkConcurrentRoots();
1624 timings.AddSplit("MarkConcurrentRoots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001625 mark_sweep.MarkNonThreadRoots();
1626 timings.AddSplit("MarkNonThreadRoots");
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001627
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001628 if (gc_type != kGcTypeSticky) {
1629 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1630 // knowing that new allocations won't be marked as live.
1631 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1632 live_stack_.get());
1633 timings.AddSplit("MarkStackAsLive");
1634 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001635
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001636 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1637
Mathieu Chartier0325e622012-09-05 14:22:51 -07001638 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001639 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001640 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001641 } else {
1642 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001643 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001644 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001645 }
1646 // Release share on mutator_lock_ and then get exclusive access.
1647 dirty_begin = NanoTime();
1648 thread_list->SuspendAll();
1649 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001650 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001651
1652 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001653 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001654
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655 // Re-mark root set.
1656 mark_sweep.ReMarkRoots();
1657 timings.AddSplit("ReMarkRoots");
1658
1659 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001660 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001661 timings.AddSplit("RecursiveMarkDirtyObjects");
1662 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001663
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001665 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001666
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001667 mark_sweep.ProcessReferences(clear_soft_references);
1668 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001669 }
1670
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001671 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1672 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001673 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001674 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001675 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001676 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001677 // We only sweep over the live stack, and the live stack should not intersect with the
1678 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001679 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1680 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001681 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001682#ifndef NDEBUG
1683 if (gc_type == kGcTypeSticky) {
1684 // Make sure everything in the live stack isn't something we unmarked.
1685 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1686 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001687 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1688 << "Unmarked object " << *it << " in the live stack";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001689 }
1690 } else {
1691 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001692 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001693 }
1694 }
1695#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001696 }
1697
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001698 if (kIsDebugBuild) {
1699 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001700 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001701 mark_sweep.VerifyImageRoots();
1702 timings.AddSplit("VerifyImageRoots");
1703 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001704
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001705 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001706 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001707 // Swapping bound bitmaps does nothing.
1708 SwapBitmaps(kGcTypeFull);
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001709 if (!VerifyHeapReferences()) {
1710 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001711 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001712 SwapBitmaps(kGcTypeFull);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001713 timings.AddSplit("VerifyHeapReferencesPostGC");
1714 }
1715
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001716 thread_list->ResumeAll();
1717 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001718 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001719
1720 {
1721 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001722 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001723 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001724 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1725 timings.AddSplit("Sweep");
1726 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001727 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001728 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001729 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001730 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001731 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001732 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001733 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001734 }
1735
1736 {
1737 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1738 // Unbind the live and mark bitmaps.
1739 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001740
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001741 // Swap the live and mark bitmaps for each space which we modified space. This is an
1742 // optimization that enables us to not clear live bits inside of the sweep.
1743 const bool swap = true;
1744 if (swap) {
1745 if (gc_type == kGcTypeSticky) {
1746 SwapLargeObjects();
1747 } else {
1748 SwapBitmaps(gc_type);
1749 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001750 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001751 }
1752
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001753 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001754 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001755 mark_sweep.VerifySystemWeaks();
1756 timings.AddSplit("VerifySystemWeaks");
1757 }
1758
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001759 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001760 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001761 total_bytes_freed_ += bytes_freed;
1762 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001763 }
1764
1765 GrowForUtilization();
1766 timings.AddSplit("GrowForUtilization");
1767
1768 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001769 timings.AddSplit("EnqueueClearedReferences");
1770
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001771 RequestHeapTrim();
1772 timings.AddSplit("Finish");
1773
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001774 // If the GC was slow, then print timings in the log.
1775 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1776 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001777 uint64_t duration = (NanoTime() - gc_begin) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001778 total_paused_time_ += pause_roots + pause_dirty;
Mathieu Chartier0051be62012-10-12 17:47:11 -07001779 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5) ||
1780 (gc_cause == kGcCauseForAlloc && duration > MsToNs(20))) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001781 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001782 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001783 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001784 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001785 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001786 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001787 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1788 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001789 if (VLOG_IS_ON(heap)) {
1790 timings.Dump();
1791 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001792 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001793
Mathieu Chartier0325e622012-09-05 14:22:51 -07001794 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1795 logger->Start();
1796 logger->AddLogger(timings);
1797 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001798}
1799
Ian Rogers81d425b2012-09-27 16:03:43 -07001800GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001801 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001802 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001803 bool do_wait;
1804 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001805 {
1806 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001807 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001808 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001809 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001810 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001811 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001812 // We must wait, change thread state then sleep on gc_complete_cond_;
1813 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1814 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001815 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001816 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001817 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001818 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001819 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001820 wait_time = NanoTime() - wait_start;;
1821 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001822 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001823 if (wait_time > MsToNs(5)) {
1824 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1825 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001826 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001827 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001828 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001829}
1830
Elliott Hughesc967f782012-04-16 10:23:15 -07001831void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001832 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1833 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001834 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001835}
1836
1837size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001838 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001839}
1840
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001841void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001842 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001843 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001844 << PrettySize(GetMaxMemory());
1845 max_allowed_footprint = GetMaxMemory();
1846 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001847 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001848}
1849
Carl Shapiro69759ea2011-07-21 18:13:35 -07001850void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001851 // We know what our utilization is at this moment.
1852 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1853 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Mathieu Chartier0051be62012-10-12 17:47:11 -07001854 if (target_size > num_bytes_allocated_ + max_free_) {
1855 target_size = num_bytes_allocated_ + max_free_;
1856 } else if (target_size < num_bytes_allocated_ + min_free_) {
1857 target_size = num_bytes_allocated_ + min_free_;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001858 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001859
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001860 // Calculate when to perform the next ConcurrentGC.
1861 if (GetFreeMemory() < concurrent_min_free_) {
1862 // Not enough free memory to perform concurrent GC.
1863 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1864 } else {
1865 // Start a concurrent Gc when we get close to the target size.
1866 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001867 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001868
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001869 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001870}
1871
jeffhaoc1160702011-10-27 15:48:45 -07001872void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001873 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001874 alloc_space_->ClearGrowthLimit();
1875}
1876
Elliott Hughesadb460d2011-10-05 17:02:34 -07001877void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001878 MemberOffset reference_queue_offset,
1879 MemberOffset reference_queueNext_offset,
1880 MemberOffset reference_pendingNext_offset,
1881 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001882 reference_referent_offset_ = reference_referent_offset;
1883 reference_queue_offset_ = reference_queue_offset;
1884 reference_queueNext_offset_ = reference_queueNext_offset;
1885 reference_pendingNext_offset_ = reference_pendingNext_offset;
1886 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1887 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1888 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1889 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1890 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1891 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1892}
1893
1894Object* Heap::GetReferenceReferent(Object* reference) {
1895 DCHECK(reference != NULL);
1896 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1897 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1898}
1899
1900void Heap::ClearReferenceReferent(Object* reference) {
1901 DCHECK(reference != NULL);
1902 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1903 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1904}
1905
1906// Returns true if the reference object has not yet been enqueued.
1907bool Heap::IsEnqueuable(const Object* ref) {
1908 DCHECK(ref != NULL);
1909 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1910 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1911 return (queue != NULL) && (queue_next == NULL);
1912}
1913
1914void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1915 DCHECK(ref != NULL);
1916 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1917 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1918 EnqueuePendingReference(ref, cleared_reference_list);
1919}
1920
1921void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1922 DCHECK(ref != NULL);
1923 DCHECK(list != NULL);
1924
1925 if (*list == NULL) {
1926 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1927 *list = ref;
1928 } else {
1929 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1930 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1931 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1932 }
1933}
1934
1935Object* Heap::DequeuePendingReference(Object** list) {
1936 DCHECK(list != NULL);
1937 DCHECK(*list != NULL);
1938 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1939 Object* ref;
1940 if (*list == head) {
1941 ref = *list;
1942 *list = NULL;
1943 } else {
1944 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1945 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1946 ref = head;
1947 }
1948 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1949 return ref;
1950}
1951
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001952void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001953 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001954 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001955 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001956 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1957 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001958}
1959
1960size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001961 return num_bytes_allocated_;
1962}
1963
1964size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001965 size_t total = 0;
1966 // TODO: C++0x
1967 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1968 Space* space = *it;
1969 if (space->IsAllocSpace()) {
1970 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1971 }
1972 }
1973 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001974}
1975
1976size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001977 return concurrent_start_size_;
1978}
1979
1980size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001981 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001982}
1983
1984void Heap::EnqueueClearedReferences(Object** cleared) {
1985 DCHECK(cleared != NULL);
1986 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001987 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001988 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001989 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001990 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1991 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001992 *cleared = NULL;
1993 }
1994}
1995
Ian Rogers1f539342012-10-03 21:09:42 -07001996void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001997 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001998 Runtime* runtime = Runtime::Current();
1999 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
2000 !runtime->IsConcurrentGcEnabled()) {
2001 return;
2002 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002003 {
2004 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2005 if (runtime->IsShuttingDown()) {
2006 return;
2007 }
2008 }
2009 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002010 return;
2011 }
2012
2013 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07002014 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002015 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2016 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002017 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2018 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002019 CHECK(!env->ExceptionCheck());
2020 requesting_gc_ = false;
2021}
2022
Ian Rogers81d425b2012-09-27 16:03:43 -07002023void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002024 {
2025 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2026 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2027 return;
2028 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002029 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002030
Ian Rogers81d425b2012-09-27 16:03:43 -07002031 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002032 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002033 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002034 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002035 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002036 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002037 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002038 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002039 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002040}
2041
Mathieu Chartier3056d0c2012-10-19 10:49:56 -07002042void Heap::Trim() {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002043 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002044}
2045
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002046void Heap::RequestHeapTrim() {
2047 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2048 // because that only marks object heads, so a large array looks like lots of empty space. We
2049 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2050 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2051 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2052 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002053 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002054 float utilization =
2055 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2056 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2057 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2058 // heap trim occurred in the last two seconds.
2059 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002060 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002061
2062 Thread* self = Thread::Current();
2063 {
2064 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2065 Runtime* runtime = Runtime::Current();
2066 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2067 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2068 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2069 // as we don't hold the lock while requesting the trim).
2070 return;
2071 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002072 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002073 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002074 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002075 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2076 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002077 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2078 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002079 CHECK(!env->ExceptionCheck());
2080}
2081
Carl Shapiro69759ea2011-07-21 18:13:35 -07002082} // namespace art