blob: 2f5362ec61a84cbfaaefc699914bc6c9c1e49082 [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 Chartier0b0b5152012-10-15 13:53:46 -0700507 // Note: Doing this only works for the free list version of the large object space since the
508 // multiple memory map version uses a lock to do the contains check.
509 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700510}
511
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700512bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700513 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700514 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700515}
516
Elliott Hughes3e465b12011-09-02 18:26:12 -0700517#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700518void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700519 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700520 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700521 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700522 return;
523 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700524 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700525}
526#endif
527
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700528void Heap::DumpSpaces() {
529 // TODO: C++0x auto
530 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700531 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700532 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
533 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
534 LOG(INFO) << space << " " << *space << "\n"
535 << live_bitmap << " " << *live_bitmap << "\n"
536 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700537 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700538 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700539}
540
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700541void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700542 if (!IsAligned<kObjectAlignment>(obj)) {
543 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700544 }
545
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700546 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
547 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700548 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700549 // Check the allocation stack / live stack.
550 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
551 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
552 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700553 if (large_object_space_->GetLiveObjects()->Test(obj)) {
554 DumpSpaces();
555 LOG(FATAL) << "Object is dead: " << obj;
556 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700557 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700558 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700559
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700560 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700561 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700562 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
563 Object::ClassOffset().Int32Value();
564 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
565 if (c == NULL) {
566 LOG(FATAL) << "Null class in object: " << obj;
567 } else if (!IsAligned<kObjectAlignment>(c)) {
568 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
569 } else if (!GetLiveBitmap()->Test(c)) {
570 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
571 }
572 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
573 // Note: we don't use the accessors here as they have internal sanity checks
574 // that we don't want to run
575 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
576 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
577 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
578 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
579 CHECK_EQ(c_c, c_c_c);
580 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700581}
582
Brian Carlstrom78128a62011-09-15 17:21:19 -0700583void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700584 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700585 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700586}
587
588void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700589 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700590 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700591}
592
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700593void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700594 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700595 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700596 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700597
598 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700599 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700600 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700601 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700602
603 // TODO: Update these atomically.
604 RuntimeStats* global_stats = Runtime::Current()->GetStats();
605 ++global_stats->allocated_objects;
606 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700607 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700608
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700609 // This is safe to do since the GC will never free objects which are neither in the allocation
610 // stack or the live bitmap.
611 while (!allocation_stack_->AtomicPushBack(obj)) {
612 Thread* self = Thread::Current();
613 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
614 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
615 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
616 self->TransitionFromSuspendedToRunnable();
617 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700618}
619
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700620void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700621 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
622 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700623
624 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700625 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700626 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700627 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700628
629 // TODO: Do this concurrently.
630 RuntimeStats* global_stats = Runtime::Current()->GetStats();
631 global_stats->freed_objects += freed_objects;
632 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700633 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700634}
635
Ian Rogers50b35e22012-10-04 10:09:15 -0700636Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700637 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700638 if (enforce_heap_growth_rate_ && num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
639 if (grow) {
640 // Grow the heap by alloc_size extra bytes.
641 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
642 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
643 << " for a " << PrettySize(alloc_size) << " allocation";
644 } else {
645 return NULL;
646 }
647 }
648
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700649 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700650 // Completely out of memory.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700651 return NULL;
652 }
653
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700654 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700655}
656
Ian Rogers50b35e22012-10-04 10:09:15 -0700657Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700658 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
659 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700660 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700661 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700662
Ian Rogers50b35e22012-10-04 10:09:15 -0700663 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700664 if (ptr != NULL) {
665 return ptr;
666 }
667
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700668 // The allocation failed. If the GC is running, block until it completes, and then retry the
669 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700670 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700671 if (last_gc != kGcTypeNone) {
672 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700673 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700674 if (ptr != NULL) {
675 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700676 }
677 }
678
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700679 // Loop through our different Gc types and try to Gc until we get enough free memory.
680 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
681 bool run_gc = false;
682 GcType gc_type = static_cast<GcType>(i);
683 switch (gc_type) {
684 case kGcTypeSticky: {
685 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700686 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
687 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700688 break;
689 }
690 case kGcTypePartial:
691 run_gc = have_zygote_space_;
692 break;
693 case kGcTypeFull:
694 run_gc = true;
695 break;
696 default:
697 break;
698 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700699
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700700 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700701 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
702
703 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700704 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700705 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
706 i = static_cast<size_t>(gc_type_ran);
707 self->TransitionFromSuspendedToRunnable();
708
709 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700710 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700711 if (ptr != NULL) {
712 return ptr;
713 }
714 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700715 }
716
717 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700718 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700719 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700720 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700721 return ptr;
722 }
723
Elliott Hughes81ff3182012-03-23 20:35:56 -0700724 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
725 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
726 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700727
Elliott Hughes418dfe72011-10-06 18:56:27 -0700728 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700729 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
730 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700731
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700732 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700733 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700734 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700735 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700736 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700737}
738
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700739void Heap::SetTargetHeapUtilization(float target) {
740 DCHECK_GT(target, 0.0f); // asserted in Java code
741 DCHECK_LT(target, 1.0f);
742 target_utilization_ = target;
743}
744
745int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700746 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700747}
748
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700749int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700750 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700751}
752
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700753int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700754 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700755}
756
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700757size_t Heap::GetTotalBytesFreed() const {
758 return total_bytes_freed_;
759}
760
761size_t Heap::GetTotalObjectsFreed() const {
762 return total_objects_freed_;
763}
764
765size_t Heap::GetTotalObjectsAllocated() const {
766 size_t total = large_object_space_->GetTotalObjectsAllocated();
767 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
768 Space* space = *it;
769 if (space->IsAllocSpace()) {
770 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
771 }
772 }
773 return total;
774}
775
776size_t Heap::GetTotalBytesAllocated() const {
777 size_t total = large_object_space_->GetTotalBytesAllocated();
778 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
779 Space* space = *it;
780 if (space->IsAllocSpace()) {
781 total += space->AsAllocSpace()->GetTotalBytesAllocated();
782 }
783 }
784 return total;
785}
786
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700787class InstanceCounter {
788 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700789 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700790 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700791 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700792
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700793 }
794
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700795 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
796 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700797 if (count_assignable_) {
798 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700799 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700800 }
801 } else {
802 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700803 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700804 }
805 }
806 }
807
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700808 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700809 Class* class_;
810 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700811 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700812};
813
814int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700815 size_t count = 0;
816 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700817 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700818 GetLiveBitmap()->Visit(counter);
819 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700820}
821
Ian Rogers30fab402012-01-23 15:43:46 -0800822void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700823 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
824 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700825 Thread* self = Thread::Current();
826 WaitForConcurrentGcToComplete(self);
827 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700828 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
829 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700830}
831
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700832void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700833 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700834 Thread* self = Thread::Current();
835 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700836
837 // Try to see if we have any Zygote spaces.
838 if (have_zygote_space_) {
839 return;
840 }
841
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700842 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
843
844 {
845 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700846 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700847 FlushAllocStack();
848 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700849
850 // Replace the first alloc space we find with a zygote space.
851 // TODO: C++0x auto
852 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
853 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700854 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700855
856 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
857 // of the remaining available heap memory.
858 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700859 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700860
861 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700862 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700863 AddSpace(alloc_space_);
864 have_zygote_space_ = true;
865 break;
866 }
867 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700868
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700869 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700870 // TODO: C++0x
871 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
872 it != cumulative_timings_.end(); ++it) {
873 it->second->Reset();
874 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700875}
876
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700877void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700878 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
879 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700880 allocation_stack_->Reset();
881}
882
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700883size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700884 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700885}
886
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700887void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
888 Object** limit = stack->End();
889 for (Object** it = stack->Begin(); it != limit; ++it) {
890 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700891 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700892 if (LIKELY(bitmap->HasAddress(obj))) {
893 bitmap->Set(obj);
894 } else {
895 large_objects->Set(obj);
896 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700897 }
898}
899
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700900void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
901 Object** limit = stack->End();
902 for (Object** it = stack->Begin(); it != limit; ++it) {
903 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700904 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700905 if (LIKELY(bitmap->HasAddress(obj))) {
906 bitmap->Clear(obj);
907 } else {
908 large_objects->Clear(obj);
909 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700910 }
911}
912
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700913GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700914 Thread* self = Thread::Current();
915 Locks::mutator_lock_->AssertNotHeld(self);
916 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700917
Ian Rogers120f1c72012-09-28 17:17:10 -0700918 if (self->IsHandlingStackOverflow()) {
919 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
920 }
921
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700922 // Ensure there is only one GC at a time.
923 bool start_collect = false;
924 while (!start_collect) {
925 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700926 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700927 if (!is_gc_running_) {
928 is_gc_running_ = true;
929 start_collect = true;
930 }
931 }
932 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700933 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700934 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
935 // Not doing at the moment to ensure soft references are cleared.
936 }
937 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700938 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700939
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700940 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
941 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
942 ++Thread::Current()->GetStats()->gc_for_alloc_count;
943 }
944
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700945 // We need to do partial GCs every now and then to avoid the heap growing too much and
946 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700947 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700948 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700949 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700950 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700951 sticky_gc_count_ = 0;
952 }
953
Mathieu Chartier637e3482012-08-17 10:41:32 -0700954 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700955 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700956 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700957 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700958 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700959 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700960
Ian Rogers15bf2d32012-08-28 17:33:04 -0700961 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700962 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700963 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700964 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700965 // Wake anyone who may have been waiting for the GC to complete.
966 gc_complete_cond_->Broadcast();
967 }
968 // Inform DDMS that a GC completed.
969 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700970 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700971}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700972
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700973void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
974 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700975 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700976
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700977 std::stringstream gc_type_str;
978 gc_type_str << gc_type << " ";
979
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700980 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700981 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700982 ThreadList* thread_list = Runtime::Current()->GetThreadList();
983 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700984 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700985 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700986
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700987 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700988 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700989 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700990 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700991 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700992 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700993
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700994 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700995 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700996 if (!VerifyHeapReferences()) {
997 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
998 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700999 timings.AddSplit("VerifyHeapReferencesPreGC");
1000 }
1001
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001002 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001003 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001004
1005 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1006 // TODO: Investigate using a mark stack instead of a vector.
1007 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001008 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001009 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1010 card_table_->GetDirtyCards(*it, dirty_cards);
1011 }
1012 }
1013
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001014 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001015 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001016
Ian Rogers120f1c72012-09-28 17:17:10 -07001017 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001018 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001019 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1020 // accidentally un-mark roots.
1021 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001022 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001023 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1024 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001025 }
1026 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001027 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001028
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001029 // We can assume that everything from the start of the first space to the alloc space is marked.
1030 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1031 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001032 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001033 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001034 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1035 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001036 }
1037 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001038 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001039 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001040 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001041 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1042 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001043 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001044 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001045
Carl Shapiro58551df2011-07-24 03:09:51 -07001046 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001047 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001048
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001049 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001050 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -07001051
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001052 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1053
1054 if (gc_type != kGcTypeSticky) {
1055 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1056 live_stack_.get());
1057 timings.AddSplit("MarkStackAsLive");
1058 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001059
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001060 if (verify_mod_union_table_) {
1061 zygote_mod_union_table_->Update();
1062 zygote_mod_union_table_->Verify();
1063 mod_union_table_->Update();
1064 mod_union_table_->Verify();
1065 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001066
1067 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001068 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001069 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001070 } else {
1071 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1072 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001073 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001074
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001075 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001076 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001077 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001078
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001079#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001080 // Verify that we only reach marked objects from the image space
1081 mark_sweep.VerifyImageRoots();
1082 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001083#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001084
Mathieu Chartier0325e622012-09-05 14:22:51 -07001085 if (gc_type != kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001086 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1087 timings.AddSplit("Sweep");
1088 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001089 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001090 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001091 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001092 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001093 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001094 live_stack_->Reset();
1095
1096 // Unbind the live and mark bitmaps.
1097 mark_sweep.UnBindBitmaps();
1098
1099 const bool swap = true;
1100 if (swap) {
1101 if (gc_type == kGcTypeSticky) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001102 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001103 } else {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001104 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001105 }
1106 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001107
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001108 if (verify_system_weaks_) {
1109 mark_sweep.VerifySystemWeaks();
1110 timings.AddSplit("VerifySystemWeaks");
1111 }
1112
Elliott Hughesadb460d2011-10-05 17:02:34 -07001113 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001114 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001115 total_bytes_freed_ += bytes_freed;
1116 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001117 }
1118
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001119 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001120 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001121 if (!VerifyHeapReferences()) {
1122 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1123 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001124 timings.AddSplit("VerifyHeapReferencesPostGC");
1125 }
1126
Carl Shapiro58551df2011-07-24 03:09:51 -07001127 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001128 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001129
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001130 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001131 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001132
1133 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001134 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001135 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001136
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001137 // If the GC was slow, then print timings in the log.
1138 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001139 total_paused_time_ += duration;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001140 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001141 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001142 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001143 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001144 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001145 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001146 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001147 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001148 if (VLOG_IS_ON(heap)) {
1149 timings.Dump();
1150 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001151 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001152
Mathieu Chartier0325e622012-09-05 14:22:51 -07001153 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1154 logger->Start();
1155 logger->AddLogger(timings);
1156 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001157}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001158
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001159void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001160 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001161 // 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 -07001162 // cards.
1163 return;
1164 }
1165
1166 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001167 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001168 zygote_mod_union_table_->Update();
1169 timings.AddSplit("UpdateZygoteModUnionTable");
1170
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001171 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001172 timings.AddSplit("ZygoteMarkReferences");
1173 }
1174
1175 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1176 mod_union_table_->Update();
1177 timings.AddSplit("UpdateModUnionTable");
1178
1179 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001180 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001181 timings.AddSplit("MarkImageToAllocSpaceReferences");
1182}
1183
1184void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1185 Object* obj = reinterpret_cast<Object*>(arg);
1186 if (root == obj) {
1187 LOG(INFO) << "Object " << obj << " is a root";
1188 }
1189}
1190
1191class ScanVisitor {
1192 public:
1193 void operator ()(const Object* obj) const {
1194 LOG(INFO) << "Would have rescanned object " << obj;
1195 }
1196};
1197
1198class VerifyReferenceVisitor {
1199 public:
1200 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001201 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1202 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001203 : heap_(heap),
1204 failed_(failed) {
1205 }
1206
1207 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1208 // analysis.
1209 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1210 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1211 // Verify that the reference is live.
1212 if (ref != NULL && !IsLive(ref)) {
1213 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001214 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1215 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001216
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001217 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001218 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1219 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1220 << "Obj type " << PrettyTypeOf(obj) << "\n"
1221 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001222 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001223 void* cover_begin = card_table->AddrFromCard(card_addr);
1224 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001225 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001226 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001227 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001228 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1229
1230 // Print out how the object is live.
1231 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001232 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1233 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001234 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1235 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1236 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001237 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1238 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001239 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001241 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001242 }
1243
1244 // Attempt to see if the card table missed the reference.
1245 ScanVisitor scan_visitor;
1246 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001247 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1248 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001249
1250 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001251 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001252 MarkSweep ms(mark_stack);
1253 ms.Init();
1254 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001255 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001256
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001257 // All the references should end up in the mark stack.
1258 ms.ScanRoot(obj);
1259 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001260 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001261 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001262 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001263 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001264 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001265 }
1266 }
1267 mark_stack->Reset();
1268
1269 // Search to see if any of the roots reference our object.
1270 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1271 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1272 *failed_ = true;
1273 }
1274 }
1275
1276 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1277 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1278 if (bitmap != NULL) {
1279 if (bitmap->Test(obj)) {
1280 return true;
1281 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001282 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001283 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001284 } else {
1285 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001286 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001287 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001288 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001289 // At this point we need to search the allocation since things in the live stack may get swept.
1290 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1291 return true;
1292 }
1293 // Not either in the live bitmap or allocation stack, so the object must be dead.
1294 return false;
1295 }
1296
1297 private:
1298 Heap* heap_;
1299 bool* failed_;
1300};
1301
1302class VerifyObjectVisitor {
1303 public:
1304 VerifyObjectVisitor(Heap* heap)
1305 : heap_(heap),
1306 failed_(false) {
1307
1308 }
1309
1310 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001311 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001312 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1313 MarkSweep::VisitObjectReferences(obj, visitor);
1314 }
1315
1316 bool Failed() const {
1317 return failed_;
1318 }
1319
1320 private:
1321 Heap* heap_;
1322 bool failed_;
1323};
1324
1325// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001326bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001327 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001328 // Lets sort our allocation stacks so that we can efficiently binary search them.
1329 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1330 std::sort(live_stack_->Begin(), live_stack_->End());
1331 // Perform the verification.
1332 VerifyObjectVisitor visitor(this);
1333 GetLiveBitmap()->Visit(visitor);
1334 // We don't want to verify the objects in the allocation stack since they themselves may be
1335 // pointing to dead objects if they are not reachable.
1336 if (visitor.Failed()) {
1337 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001338 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001339 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001340 return true;
1341}
1342
1343class VerifyReferenceCardVisitor {
1344 public:
1345 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1346 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1347 Locks::heap_bitmap_lock_)
1348 : heap_(heap),
1349 failed_(failed) {
1350 }
1351
1352 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1353 // analysis.
1354 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1355 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001356 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001357 CardTable* card_table = heap_->GetCardTable();
1358 // If the object is not dirty and it is referencing something in the live stack other than
1359 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001360 if (!card_table->AddrIsInCardTable(obj)) {
1361 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1362 *failed_ = true;
1363 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001364 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001365 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1366 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1367 LOG(ERROR) << "Object " << obj << " found in live stack";
1368 }
1369 if (heap_->GetLiveBitmap()->Test(obj)) {
1370 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1371 }
1372 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1373 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1374
1375 // Print which field of the object is dead.
1376 if (!obj->IsObjectArray()) {
1377 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1378 CHECK(klass != NULL);
1379 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1380 CHECK(fields != NULL);
1381 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1382 const Field* cur = fields->Get(i);
1383 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1384 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1385 << PrettyField(cur);
1386 break;
1387 }
1388 }
1389 } else {
1390 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1391 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1392 if (object_array->Get(i) == ref) {
1393 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1394 }
1395 }
1396 }
1397
1398 *failed_ = true;
1399 }
1400 }
1401 }
1402 }
1403
1404 private:
1405 Heap* heap_;
1406 bool* failed_;
1407};
1408
1409class VerifyLiveStackReferences {
1410 public:
1411 VerifyLiveStackReferences(Heap* heap)
1412 : heap_(heap),
1413 failed_(false) {
1414
1415 }
1416
1417 void operator ()(const Object* obj) const
1418 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1419 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1420 MarkSweep::VisitObjectReferences(obj, visitor);
1421 }
1422
1423 bool Failed() const {
1424 return failed_;
1425 }
1426
1427 private:
1428 Heap* heap_;
1429 bool failed_;
1430};
1431
1432bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001433 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001434
1435 VerifyLiveStackReferences visitor(this);
1436 GetLiveBitmap()->Visit(visitor);
1437
1438 // We can verify objects in the live stack since none of these should reference dead objects.
1439 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1440 visitor(*it);
1441 }
1442
1443 if (visitor.Failed()) {
1444 DumpSpaces();
1445 return false;
1446 }
1447 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001448}
1449
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001450void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001451 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001452 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1453 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001454 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1455 ContinuousSpace* space = *it;
1456 // We never allocate into zygote spaces.
1457 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1458 (gc_type == kGcTypeFull &&
1459 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
1460 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1461 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1462 space->AsAllocSpace()->SwapBitmaps();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001463 }
1464 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001465 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001466}
1467
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001468void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001469 large_object_space_->SwapBitmaps();
1470 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1471 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001472}
1473
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001474void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001475 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001476 allocation_stack_.reset(live_stack_.release());
1477 live_stack_.reset(temp);
1478
1479 // Sort the live stack so that we can quickly binary search it later.
1480 if (VERIFY_OBJECT_ENABLED) {
1481 std::sort(live_stack_->Begin(), live_stack_->End());
1482 }
1483}
1484
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001485void Heap::ClearCards(TimingLogger& timings) {
1486 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1487 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1488 ContinuousSpace* space = *it;
1489 if (space->IsImageSpace()) {
1490 mod_union_table_->ClearCards(*it);
1491 timings.AddSplit("ModUnionClearCards");
1492 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1493 zygote_mod_union_table_->ClearCards(space);
1494 timings.AddSplit("ZygoteModUnionClearCards");
1495 } else {
1496 card_table_->ClearSpaceCards(space);
1497 timings.AddSplit("ClearCards");
1498 }
1499 }
1500}
1501
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001502void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1503 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001504 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1505 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001506 std::stringstream gc_type_str;
1507 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001508
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001509 // Suspend all threads are get exclusive access to the heap.
1510 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1511 thread_list->SuspendAll();
1512 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001513 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001514
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001515 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001516 Object* cleared_references = NULL;
1517 {
1518 MarkSweep mark_sweep(mark_stack_.get());
1519 timings.AddSplit("ctor");
1520
1521 mark_sweep.Init();
1522 timings.AddSplit("Init");
1523
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001524 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001525 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001526 if (!VerifyHeapReferences()) {
1527 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1528 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001529 timings.AddSplit("VerifyHeapReferencesPreGC");
1530 }
1531
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001532 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1533 SwapStacks();
1534
1535 // Check that all objects which reference things in the live stack are on dirty cards.
1536 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001537 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001538 // Sort the live stack so that we can quickly binary search it later.
1539 std::sort(live_stack_->Begin(), live_stack_->End());
1540 if (!VerifyMissingCardMarks()) {
1541 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1542 }
1543 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001544
1545 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1546 // TODO: Investigate using a mark stack instead of a vector.
1547 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001548 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001549 dirty_cards.reserve(4 * KB);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001550 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1551 card_table_->GetDirtyCards(*it, dirty_cards);
1552 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001553 timings.AddSplit("GetDirtyCards");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001554 }
1555
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001557 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001558
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001559 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001560 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001561
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001562 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001563 DCHECK(!GetLiveBitmap()->Test(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001564 }
1565
Mathieu Chartier0325e622012-09-05 14:22:51 -07001566 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001567 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1568 // accidentally un-mark roots.
1569 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001570 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001571 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1572 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001573 }
1574 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001575 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001576 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1577 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001578 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001579 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001580 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1581 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001582 }
1583 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001584 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001585 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001586 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001587 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1588 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001589 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001590 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001591
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001592 // Marking roots is not necessary for sticky mark bits since we only actually require the
1593 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001594 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001595 mark_sweep.MarkRoots();
1596 timings.AddSplit("MarkRoots");
1597 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001598
1599 if (verify_mod_union_table_) {
1600 zygote_mod_union_table_->Update();
1601 zygote_mod_union_table_->Verify();
1602 mod_union_table_->Update();
1603 mod_union_table_->Verify();
1604 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001605 }
1606
1607 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001608 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001609
1610 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1611 thread_list->ResumeAll();
1612 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001613 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001614 root_end = NanoTime();
1615 timings.AddSplit("RootEnd");
1616
Ian Rogers81d425b2012-09-27 16:03:43 -07001617 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001618 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001619
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001620 if (gc_type != kGcTypeSticky) {
1621 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1622 // knowing that new allocations won't be marked as live.
1623 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1624 live_stack_.get());
1625 timings.AddSplit("MarkStackAsLive");
1626 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001627
Mathieu Chartier0325e622012-09-05 14:22:51 -07001628 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001629 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001630 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001631 } else {
1632 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001633 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001634 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001635 }
1636 // Release share on mutator_lock_ and then get exclusive access.
1637 dirty_begin = NanoTime();
1638 thread_list->SuspendAll();
1639 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001640 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001641
1642 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001643 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001644
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001645 // Re-mark root set.
1646 mark_sweep.ReMarkRoots();
1647 timings.AddSplit("ReMarkRoots");
1648
1649 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001650 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001651 timings.AddSplit("RecursiveMarkDirtyObjects");
1652 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001653
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001654 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001655 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001656
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001657 mark_sweep.ProcessReferences(clear_soft_references);
1658 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001659 }
1660
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001661 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1662 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001663 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001664 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001665 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001666 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001667 // We only sweep over the live stack, and the live stack should not intersect with the
1668 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001669 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1670 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001671 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001672#ifndef NDEBUG
1673 if (gc_type == kGcTypeSticky) {
1674 // Make sure everything in the live stack isn't something we unmarked.
1675 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1676 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001677 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1678 << "Unmarked object " << *it << " in the live stack";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001679 }
1680 } else {
1681 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001682 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001683 }
1684 }
1685#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001686 }
1687
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001688 if (kIsDebugBuild) {
1689 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001690 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001691 mark_sweep.VerifyImageRoots();
1692 timings.AddSplit("VerifyImageRoots");
1693 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001694
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001695 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001696 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1697 SwapBitmaps(gc_type);
1698 if (!VerifyHeapReferences()) {
1699 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001700 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001701 SwapBitmaps(gc_type);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001702 timings.AddSplit("VerifyHeapReferencesPostGC");
1703 }
1704
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001705 thread_list->ResumeAll();
1706 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001707 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001708
1709 {
1710 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001711 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001712 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001713 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1714 timings.AddSplit("Sweep");
1715 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001716 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001717 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001718 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001719 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001720 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001721 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001722 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001723 }
1724
1725 {
1726 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1727 // Unbind the live and mark bitmaps.
1728 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001729
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001730 // Swap the live and mark bitmaps for each space which we modified space. This is an
1731 // optimization that enables us to not clear live bits inside of the sweep.
1732 const bool swap = true;
1733 if (swap) {
1734 if (gc_type == kGcTypeSticky) {
1735 SwapLargeObjects();
1736 } else {
1737 SwapBitmaps(gc_type);
1738 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001739 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001740 }
1741
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001742 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001743 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001744 mark_sweep.VerifySystemWeaks();
1745 timings.AddSplit("VerifySystemWeaks");
1746 }
1747
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001748 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001749 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001750 total_bytes_freed_ += bytes_freed;
1751 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001752 }
1753
1754 GrowForUtilization();
1755 timings.AddSplit("GrowForUtilization");
1756
1757 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001758 timings.AddSplit("EnqueueClearedReferences");
1759
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001760 RequestHeapTrim();
1761 timings.AddSplit("Finish");
1762
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001763 // If the GC was slow, then print timings in the log.
1764 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1765 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001766 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001767 total_paused_time_ += pause_roots + pause_dirty;
Mathieu Chartier0051be62012-10-12 17:47:11 -07001768 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5) ||
1769 (gc_cause == kGcCauseForAlloc && duration > MsToNs(20))) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001770 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001771 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001772 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001773 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001774 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001775 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001776 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1777 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001778 if (VLOG_IS_ON(heap)) {
1779 timings.Dump();
1780 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001781 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001782
Mathieu Chartier0325e622012-09-05 14:22:51 -07001783 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1784 logger->Start();
1785 logger->AddLogger(timings);
1786 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001787}
1788
Ian Rogers81d425b2012-09-27 16:03:43 -07001789GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001790 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001791 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001792 bool do_wait;
1793 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001794 {
1795 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001796 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001797 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001798 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001799 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001800 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001801 // We must wait, change thread state then sleep on gc_complete_cond_;
1802 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1803 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001804 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001805 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001806 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001807 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001808 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001809 wait_time = NanoTime() - wait_start;;
1810 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001811 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001812 if (wait_time > MsToNs(5)) {
1813 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1814 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001815 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001816 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001817 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001818}
1819
Elliott Hughesc967f782012-04-16 10:23:15 -07001820void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001821 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1822 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001823 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001824}
1825
1826size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001827 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001828}
1829
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001830void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001831 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001832 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001833 << PrettySize(GetMaxMemory());
1834 max_allowed_footprint = GetMaxMemory();
1835 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001836 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001837}
1838
Carl Shapiro69759ea2011-07-21 18:13:35 -07001839void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001840 // We know what our utilization is at this moment.
1841 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1842 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Mathieu Chartier0051be62012-10-12 17:47:11 -07001843 if (target_size > num_bytes_allocated_ + max_free_) {
1844 target_size = num_bytes_allocated_ + max_free_;
1845 } else if (target_size < num_bytes_allocated_ + min_free_) {
1846 target_size = num_bytes_allocated_ + min_free_;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001847 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001848
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001849 // Calculate when to perform the next ConcurrentGC.
1850 if (GetFreeMemory() < concurrent_min_free_) {
1851 // Not enough free memory to perform concurrent GC.
1852 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1853 } else {
1854 // Start a concurrent Gc when we get close to the target size.
1855 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001856 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001857
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001858 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001859}
1860
jeffhaoc1160702011-10-27 15:48:45 -07001861void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001862 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001863 alloc_space_->ClearGrowthLimit();
1864}
1865
Elliott Hughesadb460d2011-10-05 17:02:34 -07001866void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001867 MemberOffset reference_queue_offset,
1868 MemberOffset reference_queueNext_offset,
1869 MemberOffset reference_pendingNext_offset,
1870 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001871 reference_referent_offset_ = reference_referent_offset;
1872 reference_queue_offset_ = reference_queue_offset;
1873 reference_queueNext_offset_ = reference_queueNext_offset;
1874 reference_pendingNext_offset_ = reference_pendingNext_offset;
1875 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1876 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1877 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1878 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1879 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1880 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1881}
1882
1883Object* Heap::GetReferenceReferent(Object* reference) {
1884 DCHECK(reference != NULL);
1885 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1886 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1887}
1888
1889void Heap::ClearReferenceReferent(Object* reference) {
1890 DCHECK(reference != NULL);
1891 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1892 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1893}
1894
1895// Returns true if the reference object has not yet been enqueued.
1896bool Heap::IsEnqueuable(const Object* ref) {
1897 DCHECK(ref != NULL);
1898 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1899 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1900 return (queue != NULL) && (queue_next == NULL);
1901}
1902
1903void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1904 DCHECK(ref != NULL);
1905 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1906 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1907 EnqueuePendingReference(ref, cleared_reference_list);
1908}
1909
1910void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1911 DCHECK(ref != NULL);
1912 DCHECK(list != NULL);
1913
1914 if (*list == NULL) {
1915 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1916 *list = ref;
1917 } else {
1918 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1919 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1920 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1921 }
1922}
1923
1924Object* Heap::DequeuePendingReference(Object** list) {
1925 DCHECK(list != NULL);
1926 DCHECK(*list != NULL);
1927 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1928 Object* ref;
1929 if (*list == head) {
1930 ref = *list;
1931 *list = NULL;
1932 } else {
1933 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1934 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1935 ref = head;
1936 }
1937 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1938 return ref;
1939}
1940
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001941void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001942 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001943 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001944 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001945 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1946 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001947}
1948
1949size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001950 return num_bytes_allocated_;
1951}
1952
1953size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001954 size_t total = 0;
1955 // TODO: C++0x
1956 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1957 Space* space = *it;
1958 if (space->IsAllocSpace()) {
1959 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1960 }
1961 }
1962 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001963}
1964
1965size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001966 return concurrent_start_size_;
1967}
1968
1969size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001970 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001971}
1972
1973void Heap::EnqueueClearedReferences(Object** cleared) {
1974 DCHECK(cleared != NULL);
1975 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001976 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001977 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001978 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001979 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1980 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001981 *cleared = NULL;
1982 }
1983}
1984
Ian Rogers1f539342012-10-03 21:09:42 -07001985void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001986 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001987 Runtime* runtime = Runtime::Current();
1988 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1989 !runtime->IsConcurrentGcEnabled()) {
1990 return;
1991 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001992 {
1993 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1994 if (runtime->IsShuttingDown()) {
1995 return;
1996 }
1997 }
1998 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001999 return;
2000 }
2001
2002 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07002003 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002004 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2005 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002006 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2007 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002008 CHECK(!env->ExceptionCheck());
2009 requesting_gc_ = false;
2010}
2011
Ian Rogers81d425b2012-09-27 16:03:43 -07002012void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002013 {
2014 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2015 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2016 return;
2017 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002018 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002019
Ian Rogers81d425b2012-09-27 16:03:43 -07002020 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002021 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002022 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002023 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002024 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002025 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002026 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002027 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002028 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002029}
2030
Ian Rogers81d425b2012-09-27 16:03:43 -07002031void Heap::Trim(Thread* self) {
2032 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002033 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002034}
2035
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002036void Heap::RequestHeapTrim() {
2037 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2038 // because that only marks object heads, so a large array looks like lots of empty space. We
2039 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2040 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2041 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2042 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002043 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002044 float utilization =
2045 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2046 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2047 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2048 // heap trim occurred in the last two seconds.
2049 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002050 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002051
2052 Thread* self = Thread::Current();
2053 {
2054 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2055 Runtime* runtime = Runtime::Current();
2056 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2057 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2058 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2059 // as we don't hold the lock while requesting the trim).
2060 return;
2061 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002062 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002063 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002064 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002065 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2066 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002067 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2068 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002069 CHECK(!env->ExceptionCheck());
2070}
2071
Carl Shapiro69759ea2011-07-21 18:13:35 -07002072} // namespace art