blob: 98845d8b92800803f521dae28a98acb3bee90db1 [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) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700520 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700521 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700522 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700523 return;
524 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700525 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700526}
527#endif
528
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700529void Heap::DumpSpaces() {
530 // TODO: C++0x auto
531 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700532 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700533 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
534 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
535 LOG(INFO) << space << " " << *space << "\n"
536 << live_bitmap << " " << *live_bitmap << "\n"
537 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700538 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700539 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700540}
541
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700542void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700543 if (!IsAligned<kObjectAlignment>(obj)) {
544 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700545 }
546
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700547 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
548 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700549 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700550 // Check the allocation stack / live stack.
551 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
552 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
553 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700554 if (large_object_space_->GetLiveObjects()->Test(obj)) {
555 DumpSpaces();
556 LOG(FATAL) << "Object is dead: " << obj;
557 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700558 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700560
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700561 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700562 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700563 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
564 Object::ClassOffset().Int32Value();
565 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
566 if (c == NULL) {
567 LOG(FATAL) << "Null class in object: " << obj;
568 } else if (!IsAligned<kObjectAlignment>(c)) {
569 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
570 } else if (!GetLiveBitmap()->Test(c)) {
571 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
572 }
573 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
574 // Note: we don't use the accessors here as they have internal sanity checks
575 // that we don't want to run
576 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
577 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
578 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
579 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
580 CHECK_EQ(c_c, c_c_c);
581 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700582}
583
Brian Carlstrom78128a62011-09-15 17:21:19 -0700584void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700585 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700586 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700587}
588
589void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700590 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700591 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700592}
593
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700594void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700595 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700596 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700597 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700598
599 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700600 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700601 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700602 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700603
604 // TODO: Update these atomically.
605 RuntimeStats* global_stats = Runtime::Current()->GetStats();
606 ++global_stats->allocated_objects;
607 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700608 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700609
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700610 // This is safe to do since the GC will never free objects which are neither in the allocation
611 // stack or the live bitmap.
612 while (!allocation_stack_->AtomicPushBack(obj)) {
613 Thread* self = Thread::Current();
614 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
615 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
616 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
617 self->TransitionFromSuspendedToRunnable();
618 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700619}
620
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700621void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700622 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
623 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700624
625 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700626 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700627 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700628 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700629
630 // TODO: Do this concurrently.
631 RuntimeStats* global_stats = Runtime::Current()->GetStats();
632 global_stats->freed_objects += freed_objects;
633 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700634 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700635}
636
Ian Rogers50b35e22012-10-04 10:09:15 -0700637Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700638 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700639 if (enforce_heap_growth_rate_ && num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
640 if (grow) {
641 // Grow the heap by alloc_size extra bytes.
642 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
643 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
644 << " for a " << PrettySize(alloc_size) << " allocation";
645 } else {
646 return NULL;
647 }
648 }
649
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700650 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700651 // Completely out of memory.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700652 return NULL;
653 }
654
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700655 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700656}
657
Ian Rogers50b35e22012-10-04 10:09:15 -0700658Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700659 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
660 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700661 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700662 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700663
Ian Rogers50b35e22012-10-04 10:09:15 -0700664 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700665 if (ptr != NULL) {
666 return ptr;
667 }
668
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700669 // The allocation failed. If the GC is running, block until it completes, and then retry the
670 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700671 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700672 if (last_gc != kGcTypeNone) {
673 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700674 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700675 if (ptr != NULL) {
676 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700677 }
678 }
679
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700680 // Loop through our different Gc types and try to Gc until we get enough free memory.
681 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
682 bool run_gc = false;
683 GcType gc_type = static_cast<GcType>(i);
684 switch (gc_type) {
685 case kGcTypeSticky: {
686 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700687 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
688 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700689 break;
690 }
691 case kGcTypePartial:
692 run_gc = have_zygote_space_;
693 break;
694 case kGcTypeFull:
695 run_gc = true;
696 break;
697 default:
698 break;
699 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700700
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700701 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700702 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
703
704 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700705 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700706 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
707 i = static_cast<size_t>(gc_type_ran);
708 self->TransitionFromSuspendedToRunnable();
709
710 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700711 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700712 if (ptr != NULL) {
713 return ptr;
714 }
715 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700716 }
717
718 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700719 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700720 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700721 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700722 return ptr;
723 }
724
Elliott Hughes81ff3182012-03-23 20:35:56 -0700725 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
726 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
727 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700728
Elliott Hughes418dfe72011-10-06 18:56:27 -0700729 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700730 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
731 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700732
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700733 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700734 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700735 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700736 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700737 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700738}
739
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700740void Heap::SetTargetHeapUtilization(float target) {
741 DCHECK_GT(target, 0.0f); // asserted in Java code
742 DCHECK_LT(target, 1.0f);
743 target_utilization_ = target;
744}
745
746int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700747 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700748}
749
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700750int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700751 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700752}
753
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700754int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700755 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700756}
757
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700758size_t Heap::GetTotalBytesFreed() const {
759 return total_bytes_freed_;
760}
761
762size_t Heap::GetTotalObjectsFreed() const {
763 return total_objects_freed_;
764}
765
766size_t Heap::GetTotalObjectsAllocated() const {
767 size_t total = large_object_space_->GetTotalObjectsAllocated();
768 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
769 Space* space = *it;
770 if (space->IsAllocSpace()) {
771 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
772 }
773 }
774 return total;
775}
776
777size_t Heap::GetTotalBytesAllocated() const {
778 size_t total = large_object_space_->GetTotalBytesAllocated();
779 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
780 Space* space = *it;
781 if (space->IsAllocSpace()) {
782 total += space->AsAllocSpace()->GetTotalBytesAllocated();
783 }
784 }
785 return total;
786}
787
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700788class InstanceCounter {
789 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700790 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700791 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700792 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700793
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700794 }
795
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700796 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
797 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700798 if (count_assignable_) {
799 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700800 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700801 }
802 } else {
803 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700804 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700805 }
806 }
807 }
808
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700809 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700810 Class* class_;
811 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700812 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700813};
814
815int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700816 size_t count = 0;
817 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700818 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700819 GetLiveBitmap()->Visit(counter);
820 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700821}
822
Ian Rogers30fab402012-01-23 15:43:46 -0800823void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700824 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
825 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700826 Thread* self = Thread::Current();
827 WaitForConcurrentGcToComplete(self);
828 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700829 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
830 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700831}
832
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700833void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700834 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700835 Thread* self = Thread::Current();
836 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700837
838 // Try to see if we have any Zygote spaces.
839 if (have_zygote_space_) {
840 return;
841 }
842
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700843 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
844
845 {
846 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700847 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700848 FlushAllocStack();
849 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700850
851 // Replace the first alloc space we find with a zygote space.
852 // TODO: C++0x auto
853 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
854 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700855 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700856
857 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
858 // of the remaining available heap memory.
859 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700860 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700861
862 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700863 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700864 AddSpace(alloc_space_);
865 have_zygote_space_ = true;
866 break;
867 }
868 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700869
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700870 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700871 // TODO: C++0x
872 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
873 it != cumulative_timings_.end(); ++it) {
874 it->second->Reset();
875 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700876}
877
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700878void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700879 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
880 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700881 allocation_stack_->Reset();
882}
883
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700884size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700885 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700886}
887
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700888void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
889 Object** limit = stack->End();
890 for (Object** it = stack->Begin(); it != limit; ++it) {
891 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700892 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700893 if (LIKELY(bitmap->HasAddress(obj))) {
894 bitmap->Set(obj);
895 } else {
896 large_objects->Set(obj);
897 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700898 }
899}
900
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700901void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
902 Object** limit = stack->End();
903 for (Object** it = stack->Begin(); it != limit; ++it) {
904 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700905 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700906 if (LIKELY(bitmap->HasAddress(obj))) {
907 bitmap->Clear(obj);
908 } else {
909 large_objects->Clear(obj);
910 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700911 }
912}
913
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700914GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700915 Thread* self = Thread::Current();
916 Locks::mutator_lock_->AssertNotHeld(self);
917 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700918
Ian Rogers120f1c72012-09-28 17:17:10 -0700919 if (self->IsHandlingStackOverflow()) {
920 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
921 }
922
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700923 // Ensure there is only one GC at a time.
924 bool start_collect = false;
925 while (!start_collect) {
926 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700927 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700928 if (!is_gc_running_) {
929 is_gc_running_ = true;
930 start_collect = true;
931 }
932 }
933 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700934 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700935 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
936 // Not doing at the moment to ensure soft references are cleared.
937 }
938 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700939 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700940
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700941 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
942 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
943 ++Thread::Current()->GetStats()->gc_for_alloc_count;
944 }
945
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700946 // We need to do partial GCs every now and then to avoid the heap growing too much and
947 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700948 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700949 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700950 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700951 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700952 sticky_gc_count_ = 0;
953 }
954
Mathieu Chartier637e3482012-08-17 10:41:32 -0700955 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700956 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700957 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700958 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700959 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700960 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700961
Ian Rogers15bf2d32012-08-28 17:33:04 -0700962 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700963 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700964 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700965 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700966 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -0700967 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700968 }
969 // Inform DDMS that a GC completed.
970 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700971 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700972}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700973
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700974void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
975 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700976 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700977
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700978 std::stringstream gc_type_str;
979 gc_type_str << gc_type << " ";
980
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700981 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700982 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700983 ThreadList* thread_list = Runtime::Current()->GetThreadList();
984 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700985 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700986 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700987
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700988 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700989 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700990 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700991 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700992 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700993 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700994
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700995 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700996 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700997 if (!VerifyHeapReferences()) {
998 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
999 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001000 timings.AddSplit("VerifyHeapReferencesPreGC");
1001 }
1002
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001003 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001004 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001005
1006 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1007 // TODO: Investigate using a mark stack instead of a vector.
1008 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001009 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001010 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1011 card_table_->GetDirtyCards(*it, dirty_cards);
1012 }
1013 }
1014
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001015 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001016 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001017
Ian Rogers120f1c72012-09-28 17:17:10 -07001018 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001019 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001020 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1021 // accidentally un-mark roots.
1022 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001023 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001024 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1025 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001026 }
1027 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001028 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001029
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001030 // We can assume that everything from the start of the first space to the alloc space is marked.
1031 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1032 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001033 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001034 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001035 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1036 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001037 }
1038 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001039 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001040 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001041 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001042 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1043 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001044 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001045 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001046
Carl Shapiro58551df2011-07-24 03:09:51 -07001047 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001048 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001049
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001050 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001051 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -07001052
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001053 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1054
1055 if (gc_type != kGcTypeSticky) {
1056 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1057 live_stack_.get());
1058 timings.AddSplit("MarkStackAsLive");
1059 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001060
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001061 if (verify_mod_union_table_) {
1062 zygote_mod_union_table_->Update();
1063 zygote_mod_union_table_->Verify();
1064 mod_union_table_->Update();
1065 mod_union_table_->Verify();
1066 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001067
1068 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001069 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001070 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001071 } else {
1072 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1073 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001074 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001075
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001076 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001077 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001078 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001079
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001080#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001081 // Verify that we only reach marked objects from the image space
1082 mark_sweep.VerifyImageRoots();
1083 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001084#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001085
Mathieu Chartier0325e622012-09-05 14:22:51 -07001086 if (gc_type != kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001087 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1088 timings.AddSplit("Sweep");
1089 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001090 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001091 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001092 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001093 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001094 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001095 live_stack_->Reset();
1096
1097 // Unbind the live and mark bitmaps.
1098 mark_sweep.UnBindBitmaps();
1099
1100 const bool swap = true;
1101 if (swap) {
1102 if (gc_type == kGcTypeSticky) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001103 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001104 } else {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001105 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001106 }
1107 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001108
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001109 if (verify_system_weaks_) {
1110 mark_sweep.VerifySystemWeaks();
1111 timings.AddSplit("VerifySystemWeaks");
1112 }
1113
Elliott Hughesadb460d2011-10-05 17:02:34 -07001114 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001115 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001116 total_bytes_freed_ += bytes_freed;
1117 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001118 }
1119
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001120 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001121 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001122 if (!VerifyHeapReferences()) {
1123 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1124 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001125 timings.AddSplit("VerifyHeapReferencesPostGC");
1126 }
1127
Carl Shapiro58551df2011-07-24 03:09:51 -07001128 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001129 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001130
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001131 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001132 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001133
1134 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001135 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001136 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001137
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001138 // If the GC was slow, then print timings in the log.
1139 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001140 total_paused_time_ += duration;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001141 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001142 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001143 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001144 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001145 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001146 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001147 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001148 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001149 if (VLOG_IS_ON(heap)) {
1150 timings.Dump();
1151 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001152 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001153
Mathieu Chartier0325e622012-09-05 14:22:51 -07001154 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1155 logger->Start();
1156 logger->AddLogger(timings);
1157 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001158}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001159
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001160void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001161 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001162 // 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 -07001163 // cards.
1164 return;
1165 }
1166
1167 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001168 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001169 zygote_mod_union_table_->Update();
1170 timings.AddSplit("UpdateZygoteModUnionTable");
1171
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001172 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001173 timings.AddSplit("ZygoteMarkReferences");
1174 }
1175
1176 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1177 mod_union_table_->Update();
1178 timings.AddSplit("UpdateModUnionTable");
1179
1180 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001181 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001182 timings.AddSplit("MarkImageToAllocSpaceReferences");
1183}
1184
1185void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1186 Object* obj = reinterpret_cast<Object*>(arg);
1187 if (root == obj) {
1188 LOG(INFO) << "Object " << obj << " is a root";
1189 }
1190}
1191
1192class ScanVisitor {
1193 public:
1194 void operator ()(const Object* obj) const {
1195 LOG(INFO) << "Would have rescanned object " << obj;
1196 }
1197};
1198
1199class VerifyReferenceVisitor {
1200 public:
1201 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001202 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1203 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001204 : heap_(heap),
1205 failed_(failed) {
1206 }
1207
1208 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1209 // analysis.
1210 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1211 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1212 // Verify that the reference is live.
1213 if (ref != NULL && !IsLive(ref)) {
1214 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001215 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1216 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001217
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001218 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001219 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1220 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1221 << "Obj type " << PrettyTypeOf(obj) << "\n"
1222 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001223 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001224 void* cover_begin = card_table->AddrFromCard(card_addr);
1225 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001226 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001227 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001228 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001229 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1230
1231 // Print out how the object is live.
1232 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001233 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1234 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001235 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1236 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1237 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001238 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1239 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001241 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001242 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001243 }
1244
1245 // Attempt to see if the card table missed the reference.
1246 ScanVisitor scan_visitor;
1247 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001248 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1249 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001250
1251 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001252 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001253 MarkSweep ms(mark_stack);
1254 ms.Init();
1255 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001256 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001257
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001258 // All the references should end up in the mark stack.
1259 ms.ScanRoot(obj);
1260 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001261 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001262 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001263 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001264 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001265 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001266 }
1267 }
1268 mark_stack->Reset();
1269
1270 // Search to see if any of the roots reference our object.
1271 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1272 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1273 *failed_ = true;
1274 }
1275 }
1276
1277 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1278 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1279 if (bitmap != NULL) {
1280 if (bitmap->Test(obj)) {
1281 return true;
1282 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001283 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001284 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001285 } else {
1286 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001287 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001288 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001289 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001290 // At this point we need to search the allocation since things in the live stack may get swept.
1291 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1292 return true;
1293 }
1294 // Not either in the live bitmap or allocation stack, so the object must be dead.
1295 return false;
1296 }
1297
1298 private:
1299 Heap* heap_;
1300 bool* failed_;
1301};
1302
1303class VerifyObjectVisitor {
1304 public:
1305 VerifyObjectVisitor(Heap* heap)
1306 : heap_(heap),
1307 failed_(false) {
1308
1309 }
1310
1311 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001312 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001313 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1314 MarkSweep::VisitObjectReferences(obj, visitor);
1315 }
1316
1317 bool Failed() const {
1318 return failed_;
1319 }
1320
1321 private:
1322 Heap* heap_;
1323 bool failed_;
1324};
1325
1326// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001327bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001328 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001329 // Lets sort our allocation stacks so that we can efficiently binary search them.
1330 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1331 std::sort(live_stack_->Begin(), live_stack_->End());
1332 // Perform the verification.
1333 VerifyObjectVisitor visitor(this);
1334 GetLiveBitmap()->Visit(visitor);
1335 // We don't want to verify the objects in the allocation stack since they themselves may be
1336 // pointing to dead objects if they are not reachable.
1337 if (visitor.Failed()) {
1338 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001339 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001340 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001341 return true;
1342}
1343
1344class VerifyReferenceCardVisitor {
1345 public:
1346 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1347 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1348 Locks::heap_bitmap_lock_)
1349 : heap_(heap),
1350 failed_(failed) {
1351 }
1352
1353 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1354 // analysis.
1355 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1356 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001357 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001358 CardTable* card_table = heap_->GetCardTable();
1359 // If the object is not dirty and it is referencing something in the live stack other than
1360 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001361 if (!card_table->AddrIsInCardTable(obj)) {
1362 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1363 *failed_ = true;
1364 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001365 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001366 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1367 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1368 LOG(ERROR) << "Object " << obj << " found in live stack";
1369 }
1370 if (heap_->GetLiveBitmap()->Test(obj)) {
1371 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1372 }
1373 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1374 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1375
1376 // Print which field of the object is dead.
1377 if (!obj->IsObjectArray()) {
1378 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1379 CHECK(klass != NULL);
1380 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1381 CHECK(fields != NULL);
1382 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1383 const Field* cur = fields->Get(i);
1384 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1385 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1386 << PrettyField(cur);
1387 break;
1388 }
1389 }
1390 } else {
1391 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1392 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1393 if (object_array->Get(i) == ref) {
1394 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1395 }
1396 }
1397 }
1398
1399 *failed_ = true;
1400 }
1401 }
1402 }
1403 }
1404
1405 private:
1406 Heap* heap_;
1407 bool* failed_;
1408};
1409
1410class VerifyLiveStackReferences {
1411 public:
1412 VerifyLiveStackReferences(Heap* heap)
1413 : heap_(heap),
1414 failed_(false) {
1415
1416 }
1417
1418 void operator ()(const Object* obj) const
1419 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1420 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1421 MarkSweep::VisitObjectReferences(obj, visitor);
1422 }
1423
1424 bool Failed() const {
1425 return failed_;
1426 }
1427
1428 private:
1429 Heap* heap_;
1430 bool failed_;
1431};
1432
1433bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001434 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001435
1436 VerifyLiveStackReferences visitor(this);
1437 GetLiveBitmap()->Visit(visitor);
1438
1439 // We can verify objects in the live stack since none of these should reference dead objects.
1440 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1441 visitor(*it);
1442 }
1443
1444 if (visitor.Failed()) {
1445 DumpSpaces();
1446 return false;
1447 }
1448 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001449}
1450
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001451void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001452 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001453 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1454 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001455 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1456 ContinuousSpace* space = *it;
1457 // We never allocate into zygote spaces.
1458 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1459 (gc_type == kGcTypeFull &&
1460 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
1461 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1462 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1463 space->AsAllocSpace()->SwapBitmaps();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001464 }
1465 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001466 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001467}
1468
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001469void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001470 large_object_space_->SwapBitmaps();
1471 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1472 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001473}
1474
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001475void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001476 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001477 allocation_stack_.reset(live_stack_.release());
1478 live_stack_.reset(temp);
1479
1480 // Sort the live stack so that we can quickly binary search it later.
1481 if (VERIFY_OBJECT_ENABLED) {
1482 std::sort(live_stack_->Begin(), live_stack_->End());
1483 }
1484}
1485
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001486void Heap::ClearCards(TimingLogger& timings) {
1487 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1488 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1489 ContinuousSpace* space = *it;
1490 if (space->IsImageSpace()) {
1491 mod_union_table_->ClearCards(*it);
1492 timings.AddSplit("ModUnionClearCards");
1493 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1494 zygote_mod_union_table_->ClearCards(space);
1495 timings.AddSplit("ZygoteModUnionClearCards");
1496 } else {
1497 card_table_->ClearSpaceCards(space);
1498 timings.AddSplit("ClearCards");
1499 }
1500 }
1501}
1502
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001503void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1504 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001505 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1506 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001507 std::stringstream gc_type_str;
1508 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001509
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001510 // Suspend all threads are get exclusive access to the heap.
1511 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1512 thread_list->SuspendAll();
1513 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001514 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001515
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001516 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001517 Object* cleared_references = NULL;
1518 {
1519 MarkSweep mark_sweep(mark_stack_.get());
1520 timings.AddSplit("ctor");
1521
1522 mark_sweep.Init();
1523 timings.AddSplit("Init");
1524
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001525 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001526 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001527 if (!VerifyHeapReferences()) {
1528 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1529 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001530 timings.AddSplit("VerifyHeapReferencesPreGC");
1531 }
1532
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001533 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1534 SwapStacks();
1535
1536 // Check that all objects which reference things in the live stack are on dirty cards.
1537 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001538 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001539 // Sort the live stack so that we can quickly binary search it later.
1540 std::sort(live_stack_->Begin(), live_stack_->End());
1541 if (!VerifyMissingCardMarks()) {
1542 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1543 }
1544 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001545
1546 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1547 // TODO: Investigate using a mark stack instead of a vector.
1548 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001549 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001550 dirty_cards.reserve(4 * KB);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001551 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1552 card_table_->GetDirtyCards(*it, dirty_cards);
1553 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001554 timings.AddSplit("GetDirtyCards");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001555 }
1556
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001558 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001559
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001560 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001561 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001562
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001563 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001564 DCHECK(!GetLiveBitmap()->Test(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001565 }
1566
Mathieu Chartier0325e622012-09-05 14:22:51 -07001567 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001568 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1569 // accidentally un-mark roots.
1570 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001571 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001572 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1573 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001574 }
1575 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001576 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001577 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1578 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001579 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001580 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001581 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1582 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001583 }
1584 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001585 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001586 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001587 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001588 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1589 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001590 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001591 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001592
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001593 // Marking roots is not necessary for sticky mark bits since we only actually require the
1594 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001595 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001596 mark_sweep.MarkRoots();
1597 timings.AddSplit("MarkRoots");
1598 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001599
1600 if (verify_mod_union_table_) {
1601 zygote_mod_union_table_->Update();
1602 zygote_mod_union_table_->Verify();
1603 mod_union_table_->Update();
1604 mod_union_table_->Verify();
1605 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001606 }
1607
1608 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001609 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001610
1611 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1612 thread_list->ResumeAll();
1613 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001614 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001615 root_end = NanoTime();
1616 timings.AddSplit("RootEnd");
1617
Ian Rogers81d425b2012-09-27 16:03:43 -07001618 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001619 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001620
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001621 if (gc_type != kGcTypeSticky) {
1622 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1623 // knowing that new allocations won't be marked as live.
1624 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1625 live_stack_.get());
1626 timings.AddSplit("MarkStackAsLive");
1627 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001628
Mathieu Chartier0325e622012-09-05 14:22:51 -07001629 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001630 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001631 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001632 } else {
1633 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001634 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001635 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001636 }
1637 // Release share on mutator_lock_ and then get exclusive access.
1638 dirty_begin = NanoTime();
1639 thread_list->SuspendAll();
1640 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001641 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001642
1643 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001644 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001645
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001646 // Re-mark root set.
1647 mark_sweep.ReMarkRoots();
1648 timings.AddSplit("ReMarkRoots");
1649
1650 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001651 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001652 timings.AddSplit("RecursiveMarkDirtyObjects");
1653 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001654
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001656 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001657
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001658 mark_sweep.ProcessReferences(clear_soft_references);
1659 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001660 }
1661
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001662 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1663 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001664 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001665 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001666 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001667 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001668 // We only sweep over the live stack, and the live stack should not intersect with the
1669 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001670 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1671 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001672 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001673#ifndef NDEBUG
1674 if (gc_type == kGcTypeSticky) {
1675 // Make sure everything in the live stack isn't something we unmarked.
1676 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1677 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001678 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1679 << "Unmarked object " << *it << " in the live stack";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001680 }
1681 } else {
1682 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001683 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001684 }
1685 }
1686#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001687 }
1688
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001689 if (kIsDebugBuild) {
1690 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001691 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001692 mark_sweep.VerifyImageRoots();
1693 timings.AddSplit("VerifyImageRoots");
1694 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001695
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001696 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001697 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1698 SwapBitmaps(gc_type);
1699 if (!VerifyHeapReferences()) {
1700 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001701 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001702 SwapBitmaps(gc_type);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001703 timings.AddSplit("VerifyHeapReferencesPostGC");
1704 }
1705
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001706 thread_list->ResumeAll();
1707 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001708 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001709
1710 {
1711 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001712 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001713 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001714 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1715 timings.AddSplit("Sweep");
1716 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001717 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001718 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001719 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001720 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001721 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001722 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001723 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001724 }
1725
1726 {
1727 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1728 // Unbind the live and mark bitmaps.
1729 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001730
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001731 // Swap the live and mark bitmaps for each space which we modified space. This is an
1732 // optimization that enables us to not clear live bits inside of the sweep.
1733 const bool swap = true;
1734 if (swap) {
1735 if (gc_type == kGcTypeSticky) {
1736 SwapLargeObjects();
1737 } else {
1738 SwapBitmaps(gc_type);
1739 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001740 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001741 }
1742
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001743 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001744 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001745 mark_sweep.VerifySystemWeaks();
1746 timings.AddSplit("VerifySystemWeaks");
1747 }
1748
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001749 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001750 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001751 total_bytes_freed_ += bytes_freed;
1752 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001753 }
1754
1755 GrowForUtilization();
1756 timings.AddSplit("GrowForUtilization");
1757
1758 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001759 timings.AddSplit("EnqueueClearedReferences");
1760
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001761 RequestHeapTrim();
1762 timings.AddSplit("Finish");
1763
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001764 // If the GC was slow, then print timings in the log.
1765 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1766 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001767 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001768 total_paused_time_ += pause_roots + pause_dirty;
Mathieu Chartier0051be62012-10-12 17:47:11 -07001769 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5) ||
1770 (gc_cause == kGcCauseForAlloc && duration > MsToNs(20))) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001771 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001772 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001773 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001774 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001775 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001776 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001777 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1778 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001779 if (VLOG_IS_ON(heap)) {
1780 timings.Dump();
1781 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001782 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001783
Mathieu Chartier0325e622012-09-05 14:22:51 -07001784 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1785 logger->Start();
1786 logger->AddLogger(timings);
1787 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001788}
1789
Ian Rogers81d425b2012-09-27 16:03:43 -07001790GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001791 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001792 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001793 bool do_wait;
1794 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001795 {
1796 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001797 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001798 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001799 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001800 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001801 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001802 // We must wait, change thread state then sleep on gc_complete_cond_;
1803 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1804 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001805 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001806 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001807 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001808 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001809 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001810 wait_time = NanoTime() - wait_start;;
1811 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001812 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001813 if (wait_time > MsToNs(5)) {
1814 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1815 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001816 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001817 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001818 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001819}
1820
Elliott Hughesc967f782012-04-16 10:23:15 -07001821void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001822 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1823 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001824 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001825}
1826
1827size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001828 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001829}
1830
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001831void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001832 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001833 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001834 << PrettySize(GetMaxMemory());
1835 max_allowed_footprint = GetMaxMemory();
1836 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001837 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001838}
1839
Carl Shapiro69759ea2011-07-21 18:13:35 -07001840void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001841 // We know what our utilization is at this moment.
1842 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1843 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Mathieu Chartier0051be62012-10-12 17:47:11 -07001844 if (target_size > num_bytes_allocated_ + max_free_) {
1845 target_size = num_bytes_allocated_ + max_free_;
1846 } else if (target_size < num_bytes_allocated_ + min_free_) {
1847 target_size = num_bytes_allocated_ + min_free_;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001848 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001849
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001850 // Calculate when to perform the next ConcurrentGC.
1851 if (GetFreeMemory() < concurrent_min_free_) {
1852 // Not enough free memory to perform concurrent GC.
1853 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1854 } else {
1855 // Start a concurrent Gc when we get close to the target size.
1856 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001857 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001858
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001859 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001860}
1861
jeffhaoc1160702011-10-27 15:48:45 -07001862void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001863 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001864 alloc_space_->ClearGrowthLimit();
1865}
1866
Elliott Hughesadb460d2011-10-05 17:02:34 -07001867void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001868 MemberOffset reference_queue_offset,
1869 MemberOffset reference_queueNext_offset,
1870 MemberOffset reference_pendingNext_offset,
1871 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001872 reference_referent_offset_ = reference_referent_offset;
1873 reference_queue_offset_ = reference_queue_offset;
1874 reference_queueNext_offset_ = reference_queueNext_offset;
1875 reference_pendingNext_offset_ = reference_pendingNext_offset;
1876 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1877 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1878 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1879 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1880 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1881 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1882}
1883
1884Object* Heap::GetReferenceReferent(Object* reference) {
1885 DCHECK(reference != NULL);
1886 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1887 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1888}
1889
1890void Heap::ClearReferenceReferent(Object* reference) {
1891 DCHECK(reference != NULL);
1892 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1893 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1894}
1895
1896// Returns true if the reference object has not yet been enqueued.
1897bool Heap::IsEnqueuable(const Object* ref) {
1898 DCHECK(ref != NULL);
1899 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1900 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1901 return (queue != NULL) && (queue_next == NULL);
1902}
1903
1904void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1905 DCHECK(ref != NULL);
1906 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1907 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1908 EnqueuePendingReference(ref, cleared_reference_list);
1909}
1910
1911void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1912 DCHECK(ref != NULL);
1913 DCHECK(list != NULL);
1914
1915 if (*list == NULL) {
1916 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1917 *list = ref;
1918 } else {
1919 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1920 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1921 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1922 }
1923}
1924
1925Object* Heap::DequeuePendingReference(Object** list) {
1926 DCHECK(list != NULL);
1927 DCHECK(*list != NULL);
1928 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1929 Object* ref;
1930 if (*list == head) {
1931 ref = *list;
1932 *list = NULL;
1933 } else {
1934 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1935 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1936 ref = head;
1937 }
1938 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1939 return ref;
1940}
1941
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001942void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001943 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001944 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001945 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001946 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1947 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001948}
1949
1950size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001951 return num_bytes_allocated_;
1952}
1953
1954size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001955 size_t total = 0;
1956 // TODO: C++0x
1957 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1958 Space* space = *it;
1959 if (space->IsAllocSpace()) {
1960 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1961 }
1962 }
1963 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001964}
1965
1966size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001967 return concurrent_start_size_;
1968}
1969
1970size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001971 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001972}
1973
1974void Heap::EnqueueClearedReferences(Object** cleared) {
1975 DCHECK(cleared != NULL);
1976 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001977 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001978 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001979 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001980 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1981 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001982 *cleared = NULL;
1983 }
1984}
1985
Ian Rogers1f539342012-10-03 21:09:42 -07001986void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001987 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001988 Runtime* runtime = Runtime::Current();
1989 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1990 !runtime->IsConcurrentGcEnabled()) {
1991 return;
1992 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001993 {
1994 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1995 if (runtime->IsShuttingDown()) {
1996 return;
1997 }
1998 }
1999 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002000 return;
2001 }
2002
2003 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07002004 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002005 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2006 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002007 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2008 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002009 CHECK(!env->ExceptionCheck());
2010 requesting_gc_ = false;
2011}
2012
Ian Rogers81d425b2012-09-27 16:03:43 -07002013void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002014 {
2015 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2016 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2017 return;
2018 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002019 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002020
Ian Rogers81d425b2012-09-27 16:03:43 -07002021 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002022 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002023 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002024 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002025 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002026 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002027 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002028 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002029 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002030}
2031
Ian Rogers81d425b2012-09-27 16:03:43 -07002032void Heap::Trim(Thread* self) {
2033 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002034 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002035}
2036
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002037void Heap::RequestHeapTrim() {
2038 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2039 // because that only marks object heads, so a large array looks like lots of empty space. We
2040 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2041 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2042 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2043 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002044 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002045 float utilization =
2046 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2047 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2048 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2049 // heap trim occurred in the last two seconds.
2050 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002051 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002052
2053 Thread* self = Thread::Current();
2054 {
2055 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2056 Runtime* runtime = Runtime::Current();
2057 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2058 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2059 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2060 // as we don't hold the lock while requesting the trim).
2061 return;
2062 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002063 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002064 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002065 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002066 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2067 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002068 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2069 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002070 CHECK(!env->ExceptionCheck());
2071}
2072
Carl Shapiro69759ea2011-07-21 18:13:35 -07002073} // namespace art