blob: f91ce84d1bfcc0dfa5e78441357808a81bfa3de7 [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 Rogers00f7d0e2012-07-19 15:28:27 -0700282 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700283
Mathieu Chartier0325e622012-09-05 14:22:51 -0700284 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700285 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
286 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700287 std::ostringstream name;
288 name << static_cast<GcType>(i);
289 cumulative_timings_.Put(static_cast<GcType>(i),
290 new CumulativeLogger(name.str().c_str(), true));
291 }
292
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800293 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800294 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700295 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700296}
297
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700298// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700299struct SpaceSorter {
300 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700301 return a->Begin() < b->Begin();
302 }
303};
304
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700305void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700306 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700307 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700308 DCHECK(space->GetLiveBitmap() != NULL);
309 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700310 DCHECK(space->GetMarkBitmap() != NULL);
311 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800312 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700313 if (space->IsAllocSpace()) {
314 alloc_space_ = space->AsAllocSpace();
315 }
316
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700317 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
318 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700319
320 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
321 // avoid redundant marking.
322 bool seen_zygote = false, seen_alloc = false;
323 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
324 Space* space = *it;
325 if (space->IsImageSpace()) {
326 DCHECK(!seen_zygote);
327 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700328 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700329 DCHECK(!seen_alloc);
330 seen_zygote = true;
331 } else if (space->IsAllocSpace()) {
332 seen_alloc = true;
333 }
334 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800335}
336
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700337void Heap::DumpGcPerformanceInfo() {
338 // Dump cumulative timings.
339 LOG(INFO) << "Dumping cumulative Gc timings";
340 uint64_t total_duration = 0;
341 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
342 it != cumulative_timings_.end(); ++it) {
343 CumulativeLogger* logger = it->second;
344 if (logger->GetTotalNs() != 0) {
345 logger->Dump();
346 total_duration += logger->GetTotalNs();
347 }
348 }
349 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
350 size_t total_objects_allocated = GetTotalObjectsAllocated();
351 size_t total_bytes_allocated = GetTotalBytesAllocated();
352 if (total_duration != 0) {
353 const double total_seconds = double(total_duration / 1000) / 1000000.0;
354 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
355 LOG(INFO) << "Mean GC size throughput: "
356 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
357 LOG(INFO) << "Mean GC object throughput: " << GetTotalObjectsFreed() / total_seconds << "/s";
358 }
359 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
360 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
361 if (measure_allocation_time_) {
362 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
363 LOG(INFO) << "Mean allocation time: "
364 << PrettyDuration(allocation_time / total_objects_allocated);
365 }
366 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time_);
367 LOG(INFO) << "Total waiting for Gc to complete time: " << PrettyDuration(total_wait_time_);
368}
369
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800370Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700371 // If we don't reset then the mark stack complains in it's destructor.
372 allocation_stack_->Reset();
373 live_stack_->Reset();
374
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800375 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800376 // We can't take the heap lock here because there might be a daemon thread suspended with the
377 // heap lock held. We know though that no non-daemon threads are executing, and we know that
378 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
379 // 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 -0700380 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700381 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700382 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700383}
384
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700385ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700386 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700387 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
388 if ((*it)->Contains(obj)) {
389 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700390 }
391 }
392 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
393 return NULL;
394}
395
396ImageSpace* Heap::GetImageSpace() {
397 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700398 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
399 if ((*it)->IsImageSpace()) {
400 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700401 }
402 }
403 return NULL;
404}
405
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700406DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700407 return alloc_space_;
408}
409
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700410static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700411 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700412 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700413 size_t chunk_free_bytes = chunk_size - used_bytes;
414 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
415 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700416 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700417}
418
Ian Rogers50b35e22012-10-04 10:09:15 -0700419Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700420 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
421 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
422 strlen(ClassHelper(c).GetDescriptor()) == 0);
423 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700424
425 Object* obj = NULL;
426 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700427 uint64_t allocation_start = 0;
428 if (measure_allocation_time_) {
429 allocation_start = NanoTime();
430 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700431
432 // We need to have a zygote space or else our newly allocated large object can end up in the
433 // Zygote resulting in it being prematurely freed.
434 // We can only do this for primive objects since large objects will not be within the card table
435 // range. This also means that we rely on SetClass not dirtying the object's card.
436 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700437 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700438 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700439 // Make sure that our large object didn't get placed anywhere within the space interval or else
440 // it breaks the immune range.
441 DCHECK(obj == NULL ||
442 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
443 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700444 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700445 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700446
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700447 // Ensure that we did not allocate into a zygote space.
448 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
449 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700450 }
451
Mathieu Chartier037813d2012-08-23 16:44:59 -0700452 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700453 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700454
455 // Record allocation after since we want to use the atomic add for the atomic fence to guard
456 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700457 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700458
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700459 if (Dbg::IsAllocTrackingEnabled()) {
460 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700461 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700462 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700463 // We already have a request pending, no reason to start more until we update
464 // concurrent_start_bytes_.
465 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700467 SirtRef<Object> ref(self, obj);
468 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 }
470 VerifyObject(obj);
471
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700472 if (measure_allocation_time_) {
473 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
474 }
475
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476 return obj;
477 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700478 int64_t total_bytes_free = GetFreeMemory();
479 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700481 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
482 if ((*it)->IsAllocSpace()) {
483 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700484 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700485 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700486
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700487 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 -0700488 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700489 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700490 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700491}
492
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700493bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700494 // Note: we deliberately don't take the lock here, and mustn't test anything that would
495 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700496 if (obj == NULL) {
497 return true;
498 }
499 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700500 return false;
501 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800502 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800503 if (spaces_[i]->Contains(obj)) {
504 return true;
505 }
506 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700507 // TODO: Find a way to check large object space without using a lock.
508 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700509}
510
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700511bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700512 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700513 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700514}
515
Elliott Hughes3e465b12011-09-02 18:26:12 -0700516#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700518 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700519 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700520 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700521 return;
522 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700523 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700524}
525#endif
526
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700527void Heap::DumpSpaces() {
528 // TODO: C++0x auto
529 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700530 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700531 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
532 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
533 LOG(INFO) << space << " " << *space << "\n"
534 << live_bitmap << " " << *live_bitmap << "\n"
535 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700536 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700537 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700538}
539
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700540void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700541 if (!IsAligned<kObjectAlignment>(obj)) {
542 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700543 }
544
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700545 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
546 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700547 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700548 // Check the allocation stack / live stack.
549 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
550 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
551 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700552 if (large_object_space_->GetLiveObjects()->Test(obj)) {
553 DumpSpaces();
554 LOG(FATAL) << "Object is dead: " << obj;
555 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700556 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700557 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700558
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700559 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700560 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700561 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
562 Object::ClassOffset().Int32Value();
563 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
564 if (c == NULL) {
565 LOG(FATAL) << "Null class in object: " << obj;
566 } else if (!IsAligned<kObjectAlignment>(c)) {
567 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
568 } else if (!GetLiveBitmap()->Test(c)) {
569 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
570 }
571 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
572 // Note: we don't use the accessors here as they have internal sanity checks
573 // that we don't want to run
574 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
575 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
576 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
577 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
578 CHECK_EQ(c_c, c_c_c);
579 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700580}
581
Brian Carlstrom78128a62011-09-15 17:21:19 -0700582void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700583 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700584 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700585}
586
587void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700588 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700589 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700590}
591
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700592void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700593 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700594 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700595 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700596
597 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700598 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700599 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700600 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700601
602 // TODO: Update these atomically.
603 RuntimeStats* global_stats = Runtime::Current()->GetStats();
604 ++global_stats->allocated_objects;
605 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700606 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700607
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700608 // This is safe to do since the GC will never free objects which are neither in the allocation
609 // stack or the live bitmap.
610 while (!allocation_stack_->AtomicPushBack(obj)) {
611 Thread* self = Thread::Current();
612 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
613 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
614 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
615 self->TransitionFromSuspendedToRunnable();
616 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700617}
618
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700619void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700620 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
621 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700622
623 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700624 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700625 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700626 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700627
628 // TODO: Do this concurrently.
629 RuntimeStats* global_stats = Runtime::Current()->GetStats();
630 global_stats->freed_objects += freed_objects;
631 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700632 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700633}
634
Ian Rogers50b35e22012-10-04 10:09:15 -0700635Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700636 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700637 if (enforce_heap_growth_rate_ && num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
638 if (grow) {
639 // Grow the heap by alloc_size extra bytes.
640 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
641 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
642 << " for a " << PrettySize(alloc_size) << " allocation";
643 } else {
644 return NULL;
645 }
646 }
647
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700648 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700649 // Completely out of memory.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700650 return NULL;
651 }
652
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700653 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700654}
655
Ian Rogers50b35e22012-10-04 10:09:15 -0700656Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700657 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
658 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700659 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700660 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700661
Ian Rogers50b35e22012-10-04 10:09:15 -0700662 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700663 if (ptr != NULL) {
664 return ptr;
665 }
666
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700667 // The allocation failed. If the GC is running, block until it completes, and then retry the
668 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700669 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700670 if (last_gc != kGcTypeNone) {
671 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700672 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700673 if (ptr != NULL) {
674 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700675 }
676 }
677
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700678 // Loop through our different Gc types and try to Gc until we get enough free memory.
679 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
680 bool run_gc = false;
681 GcType gc_type = static_cast<GcType>(i);
682 switch (gc_type) {
683 case kGcTypeSticky: {
684 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700685 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
686 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700687 break;
688 }
689 case kGcTypePartial:
690 run_gc = have_zygote_space_;
691 break;
692 case kGcTypeFull:
693 run_gc = true;
694 break;
695 default:
696 break;
697 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700698
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700699 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700700 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
701
702 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700703 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700704 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
705 i = static_cast<size_t>(gc_type_ran);
706 self->TransitionFromSuspendedToRunnable();
707
708 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700709 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700710 if (ptr != NULL) {
711 return ptr;
712 }
713 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700714 }
715
716 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700717 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700718 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700719 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700720 return ptr;
721 }
722
Elliott Hughes81ff3182012-03-23 20:35:56 -0700723 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
724 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
725 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700726
Elliott Hughes418dfe72011-10-06 18:56:27 -0700727 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700728 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
729 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700730
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700731 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700732 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700733 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700734 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700735 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700736}
737
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700738void Heap::SetTargetHeapUtilization(float target) {
739 DCHECK_GT(target, 0.0f); // asserted in Java code
740 DCHECK_LT(target, 1.0f);
741 target_utilization_ = target;
742}
743
744int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700745 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700746}
747
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700748int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700749 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700750}
751
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700752int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700753 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700754}
755
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700756size_t Heap::GetTotalBytesFreed() const {
757 return total_bytes_freed_;
758}
759
760size_t Heap::GetTotalObjectsFreed() const {
761 return total_objects_freed_;
762}
763
764size_t Heap::GetTotalObjectsAllocated() const {
765 size_t total = large_object_space_->GetTotalObjectsAllocated();
766 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
767 Space* space = *it;
768 if (space->IsAllocSpace()) {
769 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
770 }
771 }
772 return total;
773}
774
775size_t Heap::GetTotalBytesAllocated() const {
776 size_t total = large_object_space_->GetTotalBytesAllocated();
777 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
778 Space* space = *it;
779 if (space->IsAllocSpace()) {
780 total += space->AsAllocSpace()->GetTotalBytesAllocated();
781 }
782 }
783 return total;
784}
785
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700786class InstanceCounter {
787 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700788 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700789 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700790 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700791
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700792 }
793
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700794 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
795 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700796 if (count_assignable_) {
797 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700798 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700799 }
800 } else {
801 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700802 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700803 }
804 }
805 }
806
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700807 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700808 Class* class_;
809 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700810 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700811};
812
813int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700814 size_t count = 0;
815 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700816 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700817 GetLiveBitmap()->Visit(counter);
818 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700819}
820
Ian Rogers30fab402012-01-23 15:43:46 -0800821void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700822 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
823 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700824 Thread* self = Thread::Current();
825 WaitForConcurrentGcToComplete(self);
826 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700827 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
828 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700829}
830
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700831void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700832 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700833 Thread* self = Thread::Current();
834 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700835
836 // Try to see if we have any Zygote spaces.
837 if (have_zygote_space_) {
838 return;
839 }
840
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700841 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
842
843 {
844 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700845 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700846 FlushAllocStack();
847 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700848
849 // Replace the first alloc space we find with a zygote space.
850 // TODO: C++0x auto
851 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
852 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700853 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700854
855 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
856 // of the remaining available heap memory.
857 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700858 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700859
860 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700861 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700862 AddSpace(alloc_space_);
863 have_zygote_space_ = true;
864 break;
865 }
866 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700867
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700868 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700869 // TODO: C++0x
870 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
871 it != cumulative_timings_.end(); ++it) {
872 it->second->Reset();
873 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700874}
875
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700876void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700877 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
878 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700879 allocation_stack_->Reset();
880}
881
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700882size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700883 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700884}
885
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700886void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
887 Object** limit = stack->End();
888 for (Object** it = stack->Begin(); it != limit; ++it) {
889 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700890 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700891 if (LIKELY(bitmap->HasAddress(obj))) {
892 bitmap->Set(obj);
893 } else {
894 large_objects->Set(obj);
895 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700896 }
897}
898
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700899void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
900 Object** limit = stack->End();
901 for (Object** it = stack->Begin(); it != limit; ++it) {
902 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700903 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700904 if (LIKELY(bitmap->HasAddress(obj))) {
905 bitmap->Clear(obj);
906 } else {
907 large_objects->Clear(obj);
908 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700909 }
910}
911
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700912GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700913 Thread* self = Thread::Current();
914 Locks::mutator_lock_->AssertNotHeld(self);
915 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700916
Ian Rogers120f1c72012-09-28 17:17:10 -0700917 if (self->IsHandlingStackOverflow()) {
918 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
919 }
920
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700921 // Ensure there is only one GC at a time.
922 bool start_collect = false;
923 while (!start_collect) {
924 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700925 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700926 if (!is_gc_running_) {
927 is_gc_running_ = true;
928 start_collect = true;
929 }
930 }
931 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700932 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700933 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
934 // Not doing at the moment to ensure soft references are cleared.
935 }
936 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700937 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700938
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700939 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
940 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
941 ++Thread::Current()->GetStats()->gc_for_alloc_count;
942 }
943
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700944 // We need to do partial GCs every now and then to avoid the heap growing too much and
945 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700946 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700947 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700948 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700949 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700950 sticky_gc_count_ = 0;
951 }
952
Mathieu Chartier637e3482012-08-17 10:41:32 -0700953 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700954 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700955 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700956 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700957 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700958 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700959
Ian Rogers15bf2d32012-08-28 17:33:04 -0700960 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700961 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700962 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700963 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700964 // Wake anyone who may have been waiting for the GC to complete.
965 gc_complete_cond_->Broadcast();
966 }
967 // Inform DDMS that a GC completed.
968 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700969 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700970}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700971
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700972void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
973 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700974 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700975
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700976 std::stringstream gc_type_str;
977 gc_type_str << gc_type << " ";
978
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700979 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700980 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700981 ThreadList* thread_list = Runtime::Current()->GetThreadList();
982 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700983 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700984 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700985
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700986 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700987 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700988 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700989 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700990 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700991 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700992
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700993 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700994 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700995 if (!VerifyHeapReferences()) {
996 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
997 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700998 timings.AddSplit("VerifyHeapReferencesPreGC");
999 }
1000
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001001 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001002 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001003
1004 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1005 // TODO: Investigate using a mark stack instead of a vector.
1006 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001007 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001008 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1009 card_table_->GetDirtyCards(*it, dirty_cards);
1010 }
1011 }
1012
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001013 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001014 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001015
Ian Rogers120f1c72012-09-28 17:17:10 -07001016 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001017 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001018 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1019 // accidentally un-mark roots.
1020 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001021 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001022 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1023 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001024 }
1025 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001026 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001027
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001028 // We can assume that everything from the start of the first space to the alloc space is marked.
1029 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1030 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001031 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001032 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001033 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1034 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001035 }
1036 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001037 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001038 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001039 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001040 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1041 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001042 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001043 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001044
Carl Shapiro58551df2011-07-24 03:09:51 -07001045 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001046 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001047
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001048 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001049 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -07001050
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001051 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1052
1053 if (gc_type != kGcTypeSticky) {
1054 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1055 live_stack_.get());
1056 timings.AddSplit("MarkStackAsLive");
1057 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001058
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001059 if (verify_mod_union_table_) {
1060 zygote_mod_union_table_->Update();
1061 zygote_mod_union_table_->Verify();
1062 mod_union_table_->Update();
1063 mod_union_table_->Verify();
1064 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001065
1066 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001067 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001068 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001069 } else {
1070 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1071 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001072 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001073
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001074 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001075 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001076 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001077
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001078#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001079 // Verify that we only reach marked objects from the image space
1080 mark_sweep.VerifyImageRoots();
1081 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001082#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001083
Mathieu Chartier0325e622012-09-05 14:22:51 -07001084 if (gc_type != kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001085 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1086 timings.AddSplit("Sweep");
1087 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001088 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001089 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001090 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001091 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001093 live_stack_->Reset();
1094
1095 // Unbind the live and mark bitmaps.
1096 mark_sweep.UnBindBitmaps();
1097
1098 const bool swap = true;
1099 if (swap) {
1100 if (gc_type == kGcTypeSticky) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001101 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001102 } else {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001103 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001104 }
1105 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001106
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001107 if (verify_system_weaks_) {
1108 mark_sweep.VerifySystemWeaks();
1109 timings.AddSplit("VerifySystemWeaks");
1110 }
1111
Elliott Hughesadb460d2011-10-05 17:02:34 -07001112 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001113 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001114 total_bytes_freed_ += bytes_freed;
1115 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001116 }
1117
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001118 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001119 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001120 if (!VerifyHeapReferences()) {
1121 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1122 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001123 timings.AddSplit("VerifyHeapReferencesPostGC");
1124 }
1125
Carl Shapiro58551df2011-07-24 03:09:51 -07001126 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001127 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001128
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001129 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001130 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001131
1132 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001133 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001134 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001135
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001136 // If the GC was slow, then print timings in the log.
1137 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001138 total_paused_time_ += duration / kTimeAdjust;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001139 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001140 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001141 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001142 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001143 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001144 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001145 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001146 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001147 if (VLOG_IS_ON(heap)) {
1148 timings.Dump();
1149 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001150 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001151
Mathieu Chartier0325e622012-09-05 14:22:51 -07001152 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1153 logger->Start();
1154 logger->AddLogger(timings);
1155 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001156}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001157
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001158void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001159 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001160 // 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 -07001161 // cards.
1162 return;
1163 }
1164
1165 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001166 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001167 zygote_mod_union_table_->Update();
1168 timings.AddSplit("UpdateZygoteModUnionTable");
1169
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001170 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001171 timings.AddSplit("ZygoteMarkReferences");
1172 }
1173
1174 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1175 mod_union_table_->Update();
1176 timings.AddSplit("UpdateModUnionTable");
1177
1178 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001179 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001180 timings.AddSplit("MarkImageToAllocSpaceReferences");
1181}
1182
1183void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1184 Object* obj = reinterpret_cast<Object*>(arg);
1185 if (root == obj) {
1186 LOG(INFO) << "Object " << obj << " is a root";
1187 }
1188}
1189
1190class ScanVisitor {
1191 public:
1192 void operator ()(const Object* obj) const {
1193 LOG(INFO) << "Would have rescanned object " << obj;
1194 }
1195};
1196
1197class VerifyReferenceVisitor {
1198 public:
1199 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001200 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1201 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001202 : heap_(heap),
1203 failed_(failed) {
1204 }
1205
1206 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1207 // analysis.
1208 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1209 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1210 // Verify that the reference is live.
1211 if (ref != NULL && !IsLive(ref)) {
1212 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001213 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1214 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001215
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001216 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001217 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1218 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1219 << "Obj type " << PrettyTypeOf(obj) << "\n"
1220 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001221 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001222 void* cover_begin = card_table->AddrFromCard(card_addr);
1223 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001224 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001225 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001226 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001227 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1228
1229 // Print out how the object is live.
1230 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001231 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1232 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001233 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1234 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1235 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001236 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1237 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001238 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001239 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001240 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001241 }
1242
1243 // Attempt to see if the card table missed the reference.
1244 ScanVisitor scan_visitor;
1245 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001246 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1247 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001248
1249 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001250 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001251 MarkSweep ms(mark_stack);
1252 ms.Init();
1253 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001254 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001255
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001256 // All the references should end up in the mark stack.
1257 ms.ScanRoot(obj);
1258 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001259 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001260 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001261 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001262 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001263 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001264 }
1265 }
1266 mark_stack->Reset();
1267
1268 // Search to see if any of the roots reference our object.
1269 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1270 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1271 *failed_ = true;
1272 }
1273 }
1274
1275 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1276 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1277 if (bitmap != NULL) {
1278 if (bitmap->Test(obj)) {
1279 return true;
1280 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001281 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001282 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001283 } else {
1284 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001285 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001286 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001287 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001288 // At this point we need to search the allocation since things in the live stack may get swept.
1289 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1290 return true;
1291 }
1292 // Not either in the live bitmap or allocation stack, so the object must be dead.
1293 return false;
1294 }
1295
1296 private:
1297 Heap* heap_;
1298 bool* failed_;
1299};
1300
1301class VerifyObjectVisitor {
1302 public:
1303 VerifyObjectVisitor(Heap* heap)
1304 : heap_(heap),
1305 failed_(false) {
1306
1307 }
1308
1309 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001310 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001311 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1312 MarkSweep::VisitObjectReferences(obj, visitor);
1313 }
1314
1315 bool Failed() const {
1316 return failed_;
1317 }
1318
1319 private:
1320 Heap* heap_;
1321 bool failed_;
1322};
1323
1324// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001325bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001326 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001327 // Lets sort our allocation stacks so that we can efficiently binary search them.
1328 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1329 std::sort(live_stack_->Begin(), live_stack_->End());
1330 // Perform the verification.
1331 VerifyObjectVisitor visitor(this);
1332 GetLiveBitmap()->Visit(visitor);
1333 // We don't want to verify the objects in the allocation stack since they themselves may be
1334 // pointing to dead objects if they are not reachable.
1335 if (visitor.Failed()) {
1336 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001337 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001338 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001339 return true;
1340}
1341
1342class VerifyReferenceCardVisitor {
1343 public:
1344 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1345 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1346 Locks::heap_bitmap_lock_)
1347 : heap_(heap),
1348 failed_(failed) {
1349 }
1350
1351 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1352 // analysis.
1353 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1354 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001355 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001356 CardTable* card_table = heap_->GetCardTable();
1357 // If the object is not dirty and it is referencing something in the live stack other than
1358 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001359 if (!card_table->AddrIsInCardTable(obj)) {
1360 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1361 *failed_ = true;
1362 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001363 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001364 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1365 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1366 LOG(ERROR) << "Object " << obj << " found in live stack";
1367 }
1368 if (heap_->GetLiveBitmap()->Test(obj)) {
1369 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1370 }
1371 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1372 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1373
1374 // Print which field of the object is dead.
1375 if (!obj->IsObjectArray()) {
1376 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1377 CHECK(klass != NULL);
1378 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1379 CHECK(fields != NULL);
1380 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1381 const Field* cur = fields->Get(i);
1382 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1383 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1384 << PrettyField(cur);
1385 break;
1386 }
1387 }
1388 } else {
1389 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1390 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1391 if (object_array->Get(i) == ref) {
1392 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1393 }
1394 }
1395 }
1396
1397 *failed_ = true;
1398 }
1399 }
1400 }
1401 }
1402
1403 private:
1404 Heap* heap_;
1405 bool* failed_;
1406};
1407
1408class VerifyLiveStackReferences {
1409 public:
1410 VerifyLiveStackReferences(Heap* heap)
1411 : heap_(heap),
1412 failed_(false) {
1413
1414 }
1415
1416 void operator ()(const Object* obj) const
1417 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1418 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1419 MarkSweep::VisitObjectReferences(obj, visitor);
1420 }
1421
1422 bool Failed() const {
1423 return failed_;
1424 }
1425
1426 private:
1427 Heap* heap_;
1428 bool failed_;
1429};
1430
1431bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001432 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001433
1434 VerifyLiveStackReferences visitor(this);
1435 GetLiveBitmap()->Visit(visitor);
1436
1437 // We can verify objects in the live stack since none of these should reference dead objects.
1438 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1439 visitor(*it);
1440 }
1441
1442 if (visitor.Failed()) {
1443 DumpSpaces();
1444 return false;
1445 }
1446 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001447}
1448
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001449void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001450 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001451 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1452 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001453 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1454 ContinuousSpace* space = *it;
1455 // We never allocate into zygote spaces.
1456 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1457 (gc_type == kGcTypeFull &&
1458 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
1459 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1460 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1461 space->AsAllocSpace()->SwapBitmaps();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001462 }
1463 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001464 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001465}
1466
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001467void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001468 large_object_space_->SwapBitmaps();
1469 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1470 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001471}
1472
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001473void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001474 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001475 allocation_stack_.reset(live_stack_.release());
1476 live_stack_.reset(temp);
1477
1478 // Sort the live stack so that we can quickly binary search it later.
1479 if (VERIFY_OBJECT_ENABLED) {
1480 std::sort(live_stack_->Begin(), live_stack_->End());
1481 }
1482}
1483
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001484void Heap::ClearCards(TimingLogger& timings) {
1485 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1486 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1487 ContinuousSpace* space = *it;
1488 if (space->IsImageSpace()) {
1489 mod_union_table_->ClearCards(*it);
1490 timings.AddSplit("ModUnionClearCards");
1491 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1492 zygote_mod_union_table_->ClearCards(space);
1493 timings.AddSplit("ZygoteModUnionClearCards");
1494 } else {
1495 card_table_->ClearSpaceCards(space);
1496 timings.AddSplit("ClearCards");
1497 }
1498 }
1499}
1500
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001501void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1502 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001503 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1504 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001505 std::stringstream gc_type_str;
1506 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001507
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001508 // Suspend all threads are get exclusive access to the heap.
1509 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1510 thread_list->SuspendAll();
1511 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001512 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001513
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001514 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001515 Object* cleared_references = NULL;
1516 {
1517 MarkSweep mark_sweep(mark_stack_.get());
1518 timings.AddSplit("ctor");
1519
1520 mark_sweep.Init();
1521 timings.AddSplit("Init");
1522
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001523 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001524 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001525 if (!VerifyHeapReferences()) {
1526 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1527 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001528 timings.AddSplit("VerifyHeapReferencesPreGC");
1529 }
1530
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001531 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1532 SwapStacks();
1533
1534 // Check that all objects which reference things in the live stack are on dirty cards.
1535 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001536 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001537 // Sort the live stack so that we can quickly binary search it later.
1538 std::sort(live_stack_->Begin(), live_stack_->End());
1539 if (!VerifyMissingCardMarks()) {
1540 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1541 }
1542 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001543
1544 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1545 // TODO: Investigate using a mark stack instead of a vector.
1546 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001547 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001548 dirty_cards.reserve(4 * KB);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001549 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1550 card_table_->GetDirtyCards(*it, dirty_cards);
1551 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001552 timings.AddSplit("GetDirtyCards");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001553 }
1554
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001555 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001556 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001558 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001559 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001560
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001561 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001562 DCHECK(!GetLiveBitmap()->Test(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001563 }
1564
Mathieu Chartier0325e622012-09-05 14:22:51 -07001565 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001566 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1567 // accidentally un-mark roots.
1568 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001569 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001570 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1571 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001572 }
1573 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001574 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001575 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1576 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001577 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001578 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001579 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1580 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001581 }
1582 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001583 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001584 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001585 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001586 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1587 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001588 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001589 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001590
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001591 // Marking roots is not necessary for sticky mark bits since we only actually require the
1592 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001593 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001594 mark_sweep.MarkRoots();
1595 timings.AddSplit("MarkRoots");
1596 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001597
1598 if (verify_mod_union_table_) {
1599 zygote_mod_union_table_->Update();
1600 zygote_mod_union_table_->Verify();
1601 mod_union_table_->Update();
1602 mod_union_table_->Verify();
1603 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001604 }
1605
1606 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001607 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001608
1609 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1610 thread_list->ResumeAll();
1611 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001612 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001613 root_end = NanoTime();
1614 timings.AddSplit("RootEnd");
1615
Ian Rogers81d425b2012-09-27 16:03:43 -07001616 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001617 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001618
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001619 if (gc_type != kGcTypeSticky) {
1620 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1621 // knowing that new allocations won't be marked as live.
1622 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1623 live_stack_.get());
1624 timings.AddSplit("MarkStackAsLive");
1625 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001626
Mathieu Chartier0325e622012-09-05 14:22:51 -07001627 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001628 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001629 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001630 } else {
1631 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001632 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001633 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001634 }
1635 // Release share on mutator_lock_ and then get exclusive access.
1636 dirty_begin = NanoTime();
1637 thread_list->SuspendAll();
1638 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001639 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001640
1641 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001642 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001643
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001644 // Re-mark root set.
1645 mark_sweep.ReMarkRoots();
1646 timings.AddSplit("ReMarkRoots");
1647
1648 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001649 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001650 timings.AddSplit("RecursiveMarkDirtyObjects");
1651 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001652
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001653 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001654 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001655
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001656 mark_sweep.ProcessReferences(clear_soft_references);
1657 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001658 }
1659
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001660 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1661 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001662 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001663 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001664 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001665 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001666 // We only sweep over the live stack, and the live stack should not intersect with the
1667 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001668 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1669 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001670 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001671#ifndef NDEBUG
1672 if (gc_type == kGcTypeSticky) {
1673 // Make sure everything in the live stack isn't something we unmarked.
1674 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1675 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001676 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1677 << "Unmarked object " << *it << " in the live stack";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001678 }
1679 } else {
1680 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001681 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001682 }
1683 }
1684#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001685 }
1686
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001687 if (kIsDebugBuild) {
1688 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001689 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001690 mark_sweep.VerifyImageRoots();
1691 timings.AddSplit("VerifyImageRoots");
1692 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001693
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001694 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001695 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1696 SwapBitmaps(gc_type);
1697 if (!VerifyHeapReferences()) {
1698 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001699 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001700 SwapBitmaps(gc_type);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001701 timings.AddSplit("VerifyHeapReferencesPostGC");
1702 }
1703
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001704 thread_list->ResumeAll();
1705 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001706 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707
1708 {
1709 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001710 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001711 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001712 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1713 timings.AddSplit("Sweep");
1714 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001715 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001716 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001717 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001718 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001719 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001720 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001721 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001722 }
1723
1724 {
1725 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1726 // Unbind the live and mark bitmaps.
1727 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001728
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001729 // Swap the live and mark bitmaps for each space which we modified space. This is an
1730 // optimization that enables us to not clear live bits inside of the sweep.
1731 const bool swap = true;
1732 if (swap) {
1733 if (gc_type == kGcTypeSticky) {
1734 SwapLargeObjects();
1735 } else {
1736 SwapBitmaps(gc_type);
1737 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001738 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001739 }
1740
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001741 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001742 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001743 mark_sweep.VerifySystemWeaks();
1744 timings.AddSplit("VerifySystemWeaks");
1745 }
1746
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001747 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001748 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001749 total_bytes_freed_ += bytes_freed;
1750 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001751 }
1752
1753 GrowForUtilization();
1754 timings.AddSplit("GrowForUtilization");
1755
1756 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001757 timings.AddSplit("EnqueueClearedReferences");
1758
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001759 RequestHeapTrim();
1760 timings.AddSplit("Finish");
1761
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001762 // If the GC was slow, then print timings in the log.
1763 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1764 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001765 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001766 total_paused_time_ += (pause_roots + pause_dirty) / kTimeAdjust;
Mathieu Chartier0051be62012-10-12 17:47:11 -07001767 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5) ||
1768 (gc_cause == kGcCauseForAlloc && duration > MsToNs(20))) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001769 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001770 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001771 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001772 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001773 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001774 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001775 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1776 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001777 if (VLOG_IS_ON(heap)) {
1778 timings.Dump();
1779 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001780 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001781
Mathieu Chartier0325e622012-09-05 14:22:51 -07001782 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1783 logger->Start();
1784 logger->AddLogger(timings);
1785 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001786}
1787
Ian Rogers81d425b2012-09-27 16:03:43 -07001788GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001789 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001790 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001791 bool do_wait;
1792 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001793 {
1794 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001795 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001796 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001797 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001798 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001799 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001800 // We must wait, change thread state then sleep on gc_complete_cond_;
1801 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1802 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001803 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001804 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001805 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001806 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001807 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001808 wait_time = NanoTime() - wait_start;;
1809 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001810 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001811 if (wait_time > MsToNs(5)) {
1812 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1813 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001814 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001815 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001816 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001817}
1818
Elliott Hughesc967f782012-04-16 10:23:15 -07001819void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001820 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1821 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001822 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001823}
1824
1825size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001826 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001827}
1828
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001829void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001830 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001831 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001832 << PrettySize(GetMaxMemory());
1833 max_allowed_footprint = GetMaxMemory();
1834 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001835 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001836}
1837
Carl Shapiro69759ea2011-07-21 18:13:35 -07001838void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001839 // We know what our utilization is at this moment.
1840 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1841 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Mathieu Chartier0051be62012-10-12 17:47:11 -07001842 if (target_size > num_bytes_allocated_ + max_free_) {
1843 target_size = num_bytes_allocated_ + max_free_;
1844 } else if (target_size < num_bytes_allocated_ + min_free_) {
1845 target_size = num_bytes_allocated_ + min_free_;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001846 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001847
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001848 // Calculate when to perform the next ConcurrentGC.
1849 if (GetFreeMemory() < concurrent_min_free_) {
1850 // Not enough free memory to perform concurrent GC.
1851 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1852 } else {
1853 // Start a concurrent Gc when we get close to the target size.
1854 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001855 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001856
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001857 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001858}
1859
jeffhaoc1160702011-10-27 15:48:45 -07001860void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001861 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001862 alloc_space_->ClearGrowthLimit();
1863}
1864
Elliott Hughesadb460d2011-10-05 17:02:34 -07001865void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001866 MemberOffset reference_queue_offset,
1867 MemberOffset reference_queueNext_offset,
1868 MemberOffset reference_pendingNext_offset,
1869 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001870 reference_referent_offset_ = reference_referent_offset;
1871 reference_queue_offset_ = reference_queue_offset;
1872 reference_queueNext_offset_ = reference_queueNext_offset;
1873 reference_pendingNext_offset_ = reference_pendingNext_offset;
1874 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1875 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1876 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1877 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1878 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1879 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1880}
1881
1882Object* Heap::GetReferenceReferent(Object* reference) {
1883 DCHECK(reference != NULL);
1884 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1885 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1886}
1887
1888void Heap::ClearReferenceReferent(Object* reference) {
1889 DCHECK(reference != NULL);
1890 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1891 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1892}
1893
1894// Returns true if the reference object has not yet been enqueued.
1895bool Heap::IsEnqueuable(const Object* ref) {
1896 DCHECK(ref != NULL);
1897 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1898 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1899 return (queue != NULL) && (queue_next == NULL);
1900}
1901
1902void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1903 DCHECK(ref != NULL);
1904 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1905 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1906 EnqueuePendingReference(ref, cleared_reference_list);
1907}
1908
1909void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1910 DCHECK(ref != NULL);
1911 DCHECK(list != NULL);
1912
1913 if (*list == NULL) {
1914 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1915 *list = ref;
1916 } else {
1917 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1918 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1919 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1920 }
1921}
1922
1923Object* Heap::DequeuePendingReference(Object** list) {
1924 DCHECK(list != NULL);
1925 DCHECK(*list != NULL);
1926 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1927 Object* ref;
1928 if (*list == head) {
1929 ref = *list;
1930 *list = NULL;
1931 } else {
1932 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1933 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1934 ref = head;
1935 }
1936 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1937 return ref;
1938}
1939
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001940void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001941 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001942 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001943 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001944 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1945 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001946}
1947
1948size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001949 return num_bytes_allocated_;
1950}
1951
1952size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001953 size_t total = 0;
1954 // TODO: C++0x
1955 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1956 Space* space = *it;
1957 if (space->IsAllocSpace()) {
1958 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1959 }
1960 }
1961 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001962}
1963
1964size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001965 return concurrent_start_size_;
1966}
1967
1968size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001969 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001970}
1971
1972void Heap::EnqueueClearedReferences(Object** cleared) {
1973 DCHECK(cleared != NULL);
1974 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001975 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001976 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001977 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001978 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1979 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001980 *cleared = NULL;
1981 }
1982}
1983
Ian Rogers1f539342012-10-03 21:09:42 -07001984void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001985 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001986 Runtime* runtime = Runtime::Current();
1987 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1988 !runtime->IsConcurrentGcEnabled()) {
1989 return;
1990 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001991 {
1992 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1993 if (runtime->IsShuttingDown()) {
1994 return;
1995 }
1996 }
1997 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001998 return;
1999 }
2000
2001 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07002002 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002003 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2004 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002005 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2006 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002007 CHECK(!env->ExceptionCheck());
2008 requesting_gc_ = false;
2009}
2010
Ian Rogers81d425b2012-09-27 16:03:43 -07002011void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002012 {
2013 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2014 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2015 return;
2016 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002017 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002018
Ian Rogers81d425b2012-09-27 16:03:43 -07002019 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002020 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002021 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002022 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002023 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002024 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002025 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002026 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002027 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002028}
2029
Ian Rogers81d425b2012-09-27 16:03:43 -07002030void Heap::Trim(Thread* self) {
2031 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002032 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002033}
2034
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002035void Heap::RequestHeapTrim() {
2036 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2037 // because that only marks object heads, so a large array looks like lots of empty space. We
2038 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2039 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2040 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2041 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002042 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002043 float utilization =
2044 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2045 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2046 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2047 // heap trim occurred in the last two seconds.
2048 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002049 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002050
2051 Thread* self = Thread::Current();
2052 {
2053 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2054 Runtime* runtime = Runtime::Current();
2055 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2056 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2057 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2058 // as we don't hold the lock while requesting the trim).
2059 return;
2060 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002061 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002062 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002063 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002064 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2065 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002066 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2067 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002068 CHECK(!env->ExceptionCheck());
2069}
2070
Carl Shapiro69759ea2011-07-21 18:13:35 -07002071} // namespace art