blob: 84030ba8464b86ffa9566e0d1c2c278246b8f7fc [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070018
Brian Carlstrom5643b782012-02-05 12:32:53 -080019#include <sys/types.h>
20#include <sys/wait.h>
21
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
24
Elliott Hughes767a1472011-10-26 18:49:02 -070025#include "debugger.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070026#include "gc/atomic_stack.h"
27#include "gc/card_table.h"
28#include "gc/heap_bitmap.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070029#include "gc/large_object_space.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070030#include "gc/mark_sweep.h"
31#include "gc/mod_union_table.h"
32#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070033#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080035#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080036#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070037#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070038#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070039#include "sirt_ref.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070040#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070041#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070042#include "timing_logger.h"
43#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070044#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070045
46namespace art {
47
Mathieu Chartier0051be62012-10-12 17:47:11 -070048const double Heap::kDefaultTargetUtilization = 0.5;
49
Elliott Hughesae80b492012-04-24 10:43:17 -070050static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080051 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080052 std::vector<std::string> boot_class_path;
53 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070054 if (boot_class_path.empty()) {
55 LOG(FATAL) << "Failed to generate image because no boot class path specified";
56 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080057
58 std::vector<char*> arg_vector;
59
60 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070061 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080062 const char* dex2oat = dex2oat_string.c_str();
63 arg_vector.push_back(strdup(dex2oat));
64
65 std::string image_option_string("--image=");
66 image_option_string += image_file_name;
67 const char* image_option = image_option_string.c_str();
68 arg_vector.push_back(strdup(image_option));
69
70 arg_vector.push_back(strdup("--runtime-arg"));
71 arg_vector.push_back(strdup("-Xms64m"));
72
73 arg_vector.push_back(strdup("--runtime-arg"));
74 arg_vector.push_back(strdup("-Xmx64m"));
75
76 for (size_t i = 0; i < boot_class_path.size(); i++) {
77 std::string dex_file_option_string("--dex-file=");
78 dex_file_option_string += boot_class_path[i];
79 const char* dex_file_option = dex_file_option_string.c_str();
80 arg_vector.push_back(strdup(dex_file_option));
81 }
82
83 std::string oat_file_option_string("--oat-file=");
84 oat_file_option_string += image_file_name;
85 oat_file_option_string.erase(oat_file_option_string.size() - 3);
86 oat_file_option_string += "oat";
87 const char* oat_file_option = oat_file_option_string.c_str();
88 arg_vector.push_back(strdup(oat_file_option));
89
90 arg_vector.push_back(strdup("--base=0x60000000"));
91
Elliott Hughes48436bb2012-02-07 15:23:28 -080092 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080093 LOG(INFO) << command_line;
94
Elliott Hughes48436bb2012-02-07 15:23:28 -080095 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -080096 char** argv = &arg_vector[0];
97
98 // fork and exec dex2oat
99 pid_t pid = fork();
100 if (pid == 0) {
101 // no allocation allowed between fork and exec
102
103 // change process groups, so we don't get reaped by ProcessManager
104 setpgid(0, 0);
105
106 execv(dex2oat, argv);
107
108 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
109 return false;
110 } else {
111 STLDeleteElements(&arg_vector);
112
113 // wait for dex2oat to finish
114 int status;
115 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
116 if (got_pid != pid) {
117 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
118 return false;
119 }
120 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
121 LOG(ERROR) << dex2oat << " failed: " << command_line;
122 return false;
123 }
124 }
125 return true;
126}
127
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700128void Heap::UnReserveOatFileAddressRange() {
129 oat_file_map_.reset(NULL);
130}
131
Mathieu Chartier0051be62012-10-12 17:47:11 -0700132Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
133 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700134 const std::string& original_image_file_name, bool concurrent_gc)
135 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800136 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137 concurrent_gc_(concurrent_gc),
138 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800139 card_marking_disabled_(false),
140 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700141 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700142 enforce_heap_growth_rate_(false),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700143 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700144 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700145 concurrent_start_size_(128 * KB),
146 concurrent_min_free_(256 * KB),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700147 concurrent_start_bytes_(initial_size - concurrent_start_size_),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700148 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700149 total_bytes_freed_(0),
150 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700151 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800152 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700153 verify_missing_card_marks_(false),
154 verify_system_weaks_(false),
155 verify_pre_gc_heap_(false),
156 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700157 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700158 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700159 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700160 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700161 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700162 requesting_gc_(false),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700163 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800164 reference_referent_offset_(0),
165 reference_queue_offset_(0),
166 reference_queueNext_offset_(0),
167 reference_pendingNext_offset_(0),
168 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700169 min_free_(min_free),
170 max_free_(max_free),
171 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700172 total_paused_time_(0),
173 total_wait_time_(0),
174 measure_allocation_time_(false),
175 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700176 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800177 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800178 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700179 }
180
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700181 live_bitmap_.reset(new HeapBitmap(this));
182 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700183
Ian Rogers30fab402012-01-23 15:43:46 -0800184 // Requested begin for the alloc space, to follow the mapped image and oat files
185 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800186 std::string image_file_name(original_image_file_name);
187 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700188 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700189
Brian Carlstrom5643b782012-02-05 12:32:53 -0800190 if (OS::FileExists(image_file_name.c_str())) {
191 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700192 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800193 } else {
194 // If the /system file didn't exist, we need to use one from the art-cache.
195 // If the cache file exists, try to open, but if it fails, regenerate.
196 // If it does not exist, generate.
197 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
198 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700199 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800200 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700201 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700202 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700203 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800204 }
205 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700206
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700207 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700208 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800209 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
210 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700211 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
212 CHECK_GT(oat_end_addr, image_space->End());
213
214 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
215 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
216 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
217 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
218 reinterpret_cast<byte*>(reserve_begin),
219 reserve_end - reserve_begin, PROT_READ));
220
Ian Rogers30fab402012-01-23 15:43:46 -0800221 if (oat_end_addr > requested_begin) {
222 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700223 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700224 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700225 }
226
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700227 // Allocate the large object space.
228 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700229 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
230 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
231
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700232 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
233 growth_limit, capacity,
234 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700235 alloc_space_ = alloc_space.release();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700236 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700237 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700238 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700239
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700240 // Spaces are sorted in order of Begin().
241 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700242 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
243 if (spaces_.back()->IsAllocSpace()) {
244 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
245 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700246
Ian Rogers30fab402012-01-23 15:43:46 -0800247 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700248 // TODO: C++0x
249 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
250 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800251 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700252 ImageSpace* image_space = space->AsImageSpace();
253 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800254 }
255 }
256
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800257 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700258 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
259 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700260
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700261 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
262 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700263
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700264 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
265 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700266
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700267 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700268 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700269
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700270 // Max stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700271 static const size_t default_mark_stack_size = 64 * KB;
272 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
273 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700274 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700275 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
276 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700277
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800278 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700279 // but we can create the heap lock now. We don't create it earlier to
280 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700281 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700282 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
283 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700284
Mathieu Chartier0325e622012-09-05 14:22:51 -0700285 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700286 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
287 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700288 std::ostringstream name;
289 name << static_cast<GcType>(i);
290 cumulative_timings_.Put(static_cast<GcType>(i),
291 new CumulativeLogger(name.str().c_str(), true));
292 }
293
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800294 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800295 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700296 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700297}
298
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700299// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700300struct SpaceSorter {
301 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700302 return a->Begin() < b->Begin();
303 }
304};
305
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700306void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700307 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700308 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700309 DCHECK(space->GetLiveBitmap() != NULL);
310 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700311 DCHECK(space->GetMarkBitmap() != NULL);
312 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800313 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700314 if (space->IsAllocSpace()) {
315 alloc_space_ = space->AsAllocSpace();
316 }
317
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700318 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
319 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700320
321 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
322 // avoid redundant marking.
323 bool seen_zygote = false, seen_alloc = false;
324 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
325 Space* space = *it;
326 if (space->IsImageSpace()) {
327 DCHECK(!seen_zygote);
328 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700329 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700330 DCHECK(!seen_alloc);
331 seen_zygote = true;
332 } else if (space->IsAllocSpace()) {
333 seen_alloc = true;
334 }
335 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800336}
337
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700338void Heap::DumpGcPerformanceInfo() {
339 // Dump cumulative timings.
340 LOG(INFO) << "Dumping cumulative Gc timings";
341 uint64_t total_duration = 0;
342 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
343 it != cumulative_timings_.end(); ++it) {
344 CumulativeLogger* logger = it->second;
345 if (logger->GetTotalNs() != 0) {
346 logger->Dump();
347 total_duration += logger->GetTotalNs();
348 }
349 }
350 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
351 size_t total_objects_allocated = GetTotalObjectsAllocated();
352 size_t total_bytes_allocated = GetTotalBytesAllocated();
353 if (total_duration != 0) {
354 const double total_seconds = double(total_duration / 1000) / 1000000.0;
355 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
356 LOG(INFO) << "Mean GC size throughput: "
357 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
358 LOG(INFO) << "Mean GC object throughput: " << GetTotalObjectsFreed() / total_seconds << "/s";
359 }
360 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
361 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
362 if (measure_allocation_time_) {
363 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
364 LOG(INFO) << "Mean allocation time: "
365 << PrettyDuration(allocation_time / total_objects_allocated);
366 }
367 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time_);
368 LOG(INFO) << "Total waiting for Gc to complete time: " << PrettyDuration(total_wait_time_);
369}
370
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800371Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700372 // If we don't reset then the mark stack complains in it's destructor.
373 allocation_stack_->Reset();
374 live_stack_->Reset();
375
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800376 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800377 // We can't take the heap lock here because there might be a daemon thread suspended with the
378 // heap lock held. We know though that no non-daemon threads are executing, and we know that
379 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
380 // those threads can't resume. We're the only running thread, and we can do whatever we like...
Carl Shapiro58551df2011-07-24 03:09:51 -0700381 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700382 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700383 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700384}
385
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700386ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700387 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700388 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
389 if ((*it)->Contains(obj)) {
390 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700391 }
392 }
393 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
394 return NULL;
395}
396
397ImageSpace* Heap::GetImageSpace() {
398 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700399 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
400 if ((*it)->IsImageSpace()) {
401 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700402 }
403 }
404 return NULL;
405}
406
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700407DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700408 return alloc_space_;
409}
410
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700411static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700412 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700413 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700414 size_t chunk_free_bytes = chunk_size - used_bytes;
415 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
416 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700417 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700418}
419
Ian Rogers50b35e22012-10-04 10:09:15 -0700420Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
422 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
423 strlen(ClassHelper(c).GetDescriptor()) == 0);
424 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700425
426 Object* obj = NULL;
427 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700428 uint64_t allocation_start = 0;
429 if (measure_allocation_time_) {
430 allocation_start = NanoTime();
431 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700432
433 // We need to have a zygote space or else our newly allocated large object can end up in the
434 // Zygote resulting in it being prematurely freed.
435 // We can only do this for primive objects since large objects will not be within the card table
436 // range. This also means that we rely on SetClass not dirtying the object's card.
437 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700438 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700439 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700440 // Make sure that our large object didn't get placed anywhere within the space interval or else
441 // it breaks the immune range.
442 DCHECK(obj == NULL ||
443 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
444 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700445 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700446 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700447
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700448 // Ensure that we did not allocate into a zygote space.
449 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
450 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700451 }
452
Mathieu Chartier037813d2012-08-23 16:44:59 -0700453 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700455
456 // Record allocation after since we want to use the atomic add for the atomic fence to guard
457 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700458 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700459
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460 if (Dbg::IsAllocTrackingEnabled()) {
461 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700462 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700463 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700464 // We already have a request pending, no reason to start more until we update
465 // concurrent_start_bytes_.
466 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700468 SirtRef<Object> ref(self, obj);
469 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 }
471 VerifyObject(obj);
472
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700473 if (measure_allocation_time_) {
474 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
475 }
476
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 return obj;
478 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700479 int64_t total_bytes_free = GetFreeMemory();
480 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700482 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
483 if ((*it)->IsAllocSpace()) {
484 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700485 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700486 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700487
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700488 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700489 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700490 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700491 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700492}
493
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700494bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700495 // Note: we deliberately don't take the lock here, and mustn't test anything that would
496 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700497 if (obj == NULL) {
498 return true;
499 }
500 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700501 return false;
502 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800503 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800504 if (spaces_[i]->Contains(obj)) {
505 return true;
506 }
507 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700508 // Note: Doing this only works for the free list version of the large object space since the
509 // multiple memory map version uses a lock to do the contains check.
510 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700511}
512
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700513bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700514 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700515 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700516}
517
Elliott Hughes3e465b12011-09-02 18:26:12 -0700518#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700519void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700520 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700521 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700522 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700523 return;
524 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700525 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700526}
527#endif
528
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700529void Heap::DumpSpaces() {
530 // TODO: C++0x auto
531 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700532 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700533 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
534 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
535 LOG(INFO) << space << " " << *space << "\n"
536 << live_bitmap << " " << *live_bitmap << "\n"
537 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700538 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700539 if (large_object_space_.get() != NULL) {
540 large_object_space_->Dump(LOG(INFO));
541 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700542}
543
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700544void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700545 if (!IsAligned<kObjectAlignment>(obj)) {
546 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700547 }
548
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700549 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
550 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700551 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700552 // Check the allocation stack / live stack.
553 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
554 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
555 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700556 if (large_object_space_->GetLiveObjects()->Test(obj)) {
557 DumpSpaces();
558 LOG(FATAL) << "Object is dead: " << obj;
559 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700560 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700561 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700562
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700563 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700564 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700565 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
566 Object::ClassOffset().Int32Value();
567 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
568 if (c == NULL) {
569 LOG(FATAL) << "Null class in object: " << obj;
570 } else if (!IsAligned<kObjectAlignment>(c)) {
571 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
572 } else if (!GetLiveBitmap()->Test(c)) {
573 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
574 }
575 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
576 // Note: we don't use the accessors here as they have internal sanity checks
577 // that we don't want to run
578 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
579 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
580 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
581 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
582 CHECK_EQ(c_c, c_c_c);
583 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700584}
585
Brian Carlstrom78128a62011-09-15 17:21:19 -0700586void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700587 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700588 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700589}
590
591void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700592 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700593 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700594}
595
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700596void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700597 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700598 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700599 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700600
601 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700602 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700603 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700604 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700605
606 // TODO: Update these atomically.
607 RuntimeStats* global_stats = Runtime::Current()->GetStats();
608 ++global_stats->allocated_objects;
609 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700610 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700611
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700612 // This is safe to do since the GC will never free objects which are neither in the allocation
613 // stack or the live bitmap.
614 while (!allocation_stack_->AtomicPushBack(obj)) {
615 Thread* self = Thread::Current();
616 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
617 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
618 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
619 self->TransitionFromSuspendedToRunnable();
620 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700621}
622
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700623void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700624 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
625 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700626
627 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700628 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700629 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700630 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700631
632 // TODO: Do this concurrently.
633 RuntimeStats* global_stats = Runtime::Current()->GetStats();
634 global_stats->freed_objects += freed_objects;
635 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700636 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700637}
638
Ian Rogers50b35e22012-10-04 10:09:15 -0700639Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700640 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700641 if (enforce_heap_growth_rate_ && num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
642 if (grow) {
643 // Grow the heap by alloc_size extra bytes.
644 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
645 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
646 << " for a " << PrettySize(alloc_size) << " allocation";
647 } else {
648 return NULL;
649 }
650 }
651
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700652 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700653 // Completely out of memory.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700654 return NULL;
655 }
656
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700657 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700658}
659
Ian Rogers50b35e22012-10-04 10:09:15 -0700660Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700661 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
662 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700663 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700665
Ian Rogers50b35e22012-10-04 10:09:15 -0700666 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700667 if (ptr != NULL) {
668 return ptr;
669 }
670
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700671 // The allocation failed. If the GC is running, block until it completes, and then retry the
672 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700673 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700674 if (last_gc != kGcTypeNone) {
675 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700676 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700677 if (ptr != NULL) {
678 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700679 }
680 }
681
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700682 // Loop through our different Gc types and try to Gc until we get enough free memory.
683 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
684 bool run_gc = false;
685 GcType gc_type = static_cast<GcType>(i);
686 switch (gc_type) {
687 case kGcTypeSticky: {
688 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700689 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
690 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700691 break;
692 }
693 case kGcTypePartial:
694 run_gc = have_zygote_space_;
695 break;
696 case kGcTypeFull:
697 run_gc = true;
698 break;
699 default:
700 break;
701 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700702
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700703 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700704 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
705
706 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700707 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700708 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
709 i = static_cast<size_t>(gc_type_ran);
710 self->TransitionFromSuspendedToRunnable();
711
712 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700713 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700714 if (ptr != NULL) {
715 return ptr;
716 }
717 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700718 }
719
720 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700721 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700722 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700723 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700724 return ptr;
725 }
726
Elliott Hughes81ff3182012-03-23 20:35:56 -0700727 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
728 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
729 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700730
Elliott Hughes418dfe72011-10-06 18:56:27 -0700731 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700732 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
733 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700734
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700735 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700736 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700737 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700738 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700739 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700740}
741
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700742void Heap::SetTargetHeapUtilization(float target) {
743 DCHECK_GT(target, 0.0f); // asserted in Java code
744 DCHECK_LT(target, 1.0f);
745 target_utilization_ = target;
746}
747
748int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700749 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700750}
751
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700752int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700753 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700754}
755
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700756int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700757 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700758}
759
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700760size_t Heap::GetTotalBytesFreed() const {
761 return total_bytes_freed_;
762}
763
764size_t Heap::GetTotalObjectsFreed() const {
765 return total_objects_freed_;
766}
767
768size_t Heap::GetTotalObjectsAllocated() const {
769 size_t total = large_object_space_->GetTotalObjectsAllocated();
770 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
771 Space* space = *it;
772 if (space->IsAllocSpace()) {
773 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
774 }
775 }
776 return total;
777}
778
779size_t Heap::GetTotalBytesAllocated() const {
780 size_t total = large_object_space_->GetTotalBytesAllocated();
781 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
782 Space* space = *it;
783 if (space->IsAllocSpace()) {
784 total += space->AsAllocSpace()->GetTotalBytesAllocated();
785 }
786 }
787 return total;
788}
789
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700790class InstanceCounter {
791 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700792 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700793 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700794 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700795
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700796 }
797
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700798 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
799 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700800 if (count_assignable_) {
801 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700802 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700803 }
804 } else {
805 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700806 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700807 }
808 }
809 }
810
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700811 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700812 Class* class_;
813 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700814 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700815};
816
817int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700818 size_t count = 0;
819 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700820 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700821 GetLiveBitmap()->Visit(counter);
822 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700823}
824
Ian Rogers30fab402012-01-23 15:43:46 -0800825void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700826 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
827 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700828 Thread* self = Thread::Current();
829 WaitForConcurrentGcToComplete(self);
830 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700831 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
832 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700833}
834
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700835void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700836 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700837 Thread* self = Thread::Current();
838 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700839
840 // Try to see if we have any Zygote spaces.
841 if (have_zygote_space_) {
842 return;
843 }
844
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700845 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
846
847 {
848 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700849 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700850 FlushAllocStack();
851 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700852
853 // Replace the first alloc space we find with a zygote space.
854 // TODO: C++0x auto
855 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
856 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700857 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700858
859 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
860 // of the remaining available heap memory.
861 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700862 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700863
864 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700865 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700866 AddSpace(alloc_space_);
867 have_zygote_space_ = true;
868 break;
869 }
870 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700871
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700872 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700873 // TODO: C++0x
874 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
875 it != cumulative_timings_.end(); ++it) {
876 it->second->Reset();
877 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700878}
879
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700880void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700881 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
882 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700883 allocation_stack_->Reset();
884}
885
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700886size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700887 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700888}
889
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700890void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
891 Object** limit = stack->End();
892 for (Object** it = stack->Begin(); it != limit; ++it) {
893 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700894 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700895 if (LIKELY(bitmap->HasAddress(obj))) {
896 bitmap->Set(obj);
897 } else {
898 large_objects->Set(obj);
899 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700900 }
901}
902
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700903void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
904 Object** limit = stack->End();
905 for (Object** it = stack->Begin(); it != limit; ++it) {
906 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700907 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700908 if (LIKELY(bitmap->HasAddress(obj))) {
909 bitmap->Clear(obj);
910 } else {
911 large_objects->Clear(obj);
912 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700913 }
914}
915
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700916GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700917 Thread* self = Thread::Current();
918 Locks::mutator_lock_->AssertNotHeld(self);
919 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700920
Ian Rogers120f1c72012-09-28 17:17:10 -0700921 if (self->IsHandlingStackOverflow()) {
922 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
923 }
924
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700925 // Ensure there is only one GC at a time.
926 bool start_collect = false;
927 while (!start_collect) {
928 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700929 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700930 if (!is_gc_running_) {
931 is_gc_running_ = true;
932 start_collect = true;
933 }
934 }
935 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700936 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700937 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
938 // Not doing at the moment to ensure soft references are cleared.
939 }
940 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700941 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700942
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700943 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
944 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
945 ++Thread::Current()->GetStats()->gc_for_alloc_count;
946 }
947
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700948 // We need to do partial GCs every now and then to avoid the heap growing too much and
949 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700950 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700951 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700952 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700953 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700954 sticky_gc_count_ = 0;
955 }
956
Mathieu Chartier637e3482012-08-17 10:41:32 -0700957 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700958 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700959 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700960 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700961 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700962 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700963
Ian Rogers15bf2d32012-08-28 17:33:04 -0700964 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700965 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700966 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700967 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700968 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -0700969 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700970 }
971 // Inform DDMS that a GC completed.
972 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700973 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700974}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700975
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700976void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
977 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700978 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700979
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700980 std::stringstream gc_type_str;
981 gc_type_str << gc_type << " ";
982
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700983 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700984 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700985 ThreadList* thread_list = Runtime::Current()->GetThreadList();
986 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700987 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700988 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700989
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700990 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700991 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700992 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700993 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700994 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700995 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700996
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700997 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700998 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700999 if (!VerifyHeapReferences()) {
1000 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1001 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001002 timings.AddSplit("VerifyHeapReferencesPreGC");
1003 }
1004
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001005 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001006 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001007
1008 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1009 // TODO: Investigate using a mark stack instead of a vector.
1010 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001011 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001012 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1013 card_table_->GetDirtyCards(*it, dirty_cards);
1014 }
1015 }
1016
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001017 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001018 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001019
Ian Rogers120f1c72012-09-28 17:17:10 -07001020 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001021 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001022 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1023 // accidentally un-mark roots.
1024 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001025 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001026 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1027 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001028 }
1029 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001030 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001031
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001032 // We can assume that everything from the start of the first space to the alloc space is marked.
1033 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1034 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001035 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001036 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001037 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1038 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001039 }
1040 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001041 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001042 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001043 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001044 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1045 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001046 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001047 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001048
Carl Shapiro58551df2011-07-24 03:09:51 -07001049 mark_sweep.MarkRoots();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001050 mark_sweep.MarkConcurrentRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001051 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001052
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001053 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001054 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -07001055
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001056 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1057
1058 if (gc_type != kGcTypeSticky) {
1059 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1060 live_stack_.get());
1061 timings.AddSplit("MarkStackAsLive");
1062 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001063
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001064 if (verify_mod_union_table_) {
1065 zygote_mod_union_table_->Update();
1066 zygote_mod_union_table_->Verify();
1067 mod_union_table_->Update();
1068 mod_union_table_->Verify();
1069 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001070
1071 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001072 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001073 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001074 } else {
1075 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1076 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001077 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001078
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001079 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001080 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001081 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001082
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001083#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001084 // Verify that we only reach marked objects from the image space
1085 mark_sweep.VerifyImageRoots();
1086 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001087#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001088
Mathieu Chartier0325e622012-09-05 14:22:51 -07001089 if (gc_type != kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001090 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1091 timings.AddSplit("Sweep");
1092 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001093 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001094 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001095 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001096 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001097 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001098 live_stack_->Reset();
1099
1100 // Unbind the live and mark bitmaps.
1101 mark_sweep.UnBindBitmaps();
1102
1103 const bool swap = true;
1104 if (swap) {
1105 if (gc_type == kGcTypeSticky) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001106 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001107 } else {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001108 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001109 }
1110 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001111
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001112 if (verify_system_weaks_) {
1113 mark_sweep.VerifySystemWeaks();
1114 timings.AddSplit("VerifySystemWeaks");
1115 }
1116
Elliott Hughesadb460d2011-10-05 17:02:34 -07001117 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001118 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001119 total_bytes_freed_ += bytes_freed;
1120 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001121 }
1122
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001123 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001124 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001125 if (!VerifyHeapReferences()) {
1126 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1127 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001128 timings.AddSplit("VerifyHeapReferencesPostGC");
1129 }
1130
Carl Shapiro58551df2011-07-24 03:09:51 -07001131 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001132 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001133
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001134 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001135 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001136
1137 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001138 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001139 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001140
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001141 // If the GC was slow, then print timings in the log.
1142 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001143 total_paused_time_ += duration;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001144 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001145 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001146 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001147 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001148 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001149 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001150 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001151 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001152 if (VLOG_IS_ON(heap)) {
1153 timings.Dump();
1154 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001155 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001156
Mathieu Chartier0325e622012-09-05 14:22:51 -07001157 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1158 logger->Start();
1159 logger->AddLogger(timings);
1160 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001161}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001162
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001163void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001164 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001165 // 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 -07001166 // cards.
1167 return;
1168 }
1169
1170 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001171 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001172 zygote_mod_union_table_->Update();
1173 timings.AddSplit("UpdateZygoteModUnionTable");
1174
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001175 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001176 timings.AddSplit("ZygoteMarkReferences");
1177 }
1178
1179 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1180 mod_union_table_->Update();
1181 timings.AddSplit("UpdateModUnionTable");
1182
1183 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001184 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001185 timings.AddSplit("MarkImageToAllocSpaceReferences");
1186}
1187
1188void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1189 Object* obj = reinterpret_cast<Object*>(arg);
1190 if (root == obj) {
1191 LOG(INFO) << "Object " << obj << " is a root";
1192 }
1193}
1194
1195class ScanVisitor {
1196 public:
1197 void operator ()(const Object* obj) const {
1198 LOG(INFO) << "Would have rescanned object " << obj;
1199 }
1200};
1201
1202class VerifyReferenceVisitor {
1203 public:
1204 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001205 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1206 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001207 : heap_(heap),
1208 failed_(failed) {
1209 }
1210
1211 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1212 // analysis.
1213 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1214 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1215 // Verify that the reference is live.
1216 if (ref != NULL && !IsLive(ref)) {
1217 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001218 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1219 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001220
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001221 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001222 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1223 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1224 << "Obj type " << PrettyTypeOf(obj) << "\n"
1225 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001226 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001227 void* cover_begin = card_table->AddrFromCard(card_addr);
1228 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001229 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001230 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001231 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001232 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1233
1234 // Print out how the object is live.
1235 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001236 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1237 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001238 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1239 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1240 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001241 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1242 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001243 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001244 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001245 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001246 }
1247
1248 // Attempt to see if the card table missed the reference.
1249 ScanVisitor scan_visitor;
1250 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001251 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1252 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001253
1254 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001255 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001256 MarkSweep ms(mark_stack);
1257 ms.Init();
1258 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001259 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001260
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001261 // All the references should end up in the mark stack.
1262 ms.ScanRoot(obj);
1263 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001264 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001265 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001266 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001267 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001268 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001269 }
1270 }
1271 mark_stack->Reset();
1272
1273 // Search to see if any of the roots reference our object.
1274 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1275 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1276 *failed_ = true;
1277 }
1278 }
1279
1280 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1281 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1282 if (bitmap != NULL) {
1283 if (bitmap->Test(obj)) {
1284 return true;
1285 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001286 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001287 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001288 } else {
1289 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001290 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001291 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001292 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001293 // At this point we need to search the allocation since things in the live stack may get swept.
1294 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1295 return true;
1296 }
1297 // Not either in the live bitmap or allocation stack, so the object must be dead.
1298 return false;
1299 }
1300
1301 private:
1302 Heap* heap_;
1303 bool* failed_;
1304};
1305
1306class VerifyObjectVisitor {
1307 public:
1308 VerifyObjectVisitor(Heap* heap)
1309 : heap_(heap),
1310 failed_(false) {
1311
1312 }
1313
1314 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001315 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001316 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1317 MarkSweep::VisitObjectReferences(obj, visitor);
1318 }
1319
1320 bool Failed() const {
1321 return failed_;
1322 }
1323
1324 private:
1325 Heap* heap_;
1326 bool failed_;
1327};
1328
1329// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001330bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001331 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001332 // Lets sort our allocation stacks so that we can efficiently binary search them.
1333 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1334 std::sort(live_stack_->Begin(), live_stack_->End());
1335 // Perform the verification.
1336 VerifyObjectVisitor visitor(this);
1337 GetLiveBitmap()->Visit(visitor);
1338 // We don't want to verify the objects in the allocation stack since they themselves may be
1339 // pointing to dead objects if they are not reachable.
1340 if (visitor.Failed()) {
1341 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001342 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001343 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001344 return true;
1345}
1346
1347class VerifyReferenceCardVisitor {
1348 public:
1349 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1350 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1351 Locks::heap_bitmap_lock_)
1352 : heap_(heap),
1353 failed_(failed) {
1354 }
1355
1356 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1357 // analysis.
1358 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1359 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001360 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001361 CardTable* card_table = heap_->GetCardTable();
1362 // If the object is not dirty and it is referencing something in the live stack other than
1363 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001364 if (!card_table->AddrIsInCardTable(obj)) {
1365 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1366 *failed_ = true;
1367 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001368 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001369 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1370 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1371 LOG(ERROR) << "Object " << obj << " found in live stack";
1372 }
1373 if (heap_->GetLiveBitmap()->Test(obj)) {
1374 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1375 }
1376 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1377 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1378
1379 // Print which field of the object is dead.
1380 if (!obj->IsObjectArray()) {
1381 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1382 CHECK(klass != NULL);
1383 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1384 CHECK(fields != NULL);
1385 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1386 const Field* cur = fields->Get(i);
1387 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1388 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1389 << PrettyField(cur);
1390 break;
1391 }
1392 }
1393 } else {
1394 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1395 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1396 if (object_array->Get(i) == ref) {
1397 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1398 }
1399 }
1400 }
1401
1402 *failed_ = true;
1403 }
1404 }
1405 }
1406 }
1407
1408 private:
1409 Heap* heap_;
1410 bool* failed_;
1411};
1412
1413class VerifyLiveStackReferences {
1414 public:
1415 VerifyLiveStackReferences(Heap* heap)
1416 : heap_(heap),
1417 failed_(false) {
1418
1419 }
1420
1421 void operator ()(const Object* obj) const
1422 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1423 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1424 MarkSweep::VisitObjectReferences(obj, visitor);
1425 }
1426
1427 bool Failed() const {
1428 return failed_;
1429 }
1430
1431 private:
1432 Heap* heap_;
1433 bool failed_;
1434};
1435
1436bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001437 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001438
1439 VerifyLiveStackReferences visitor(this);
1440 GetLiveBitmap()->Visit(visitor);
1441
1442 // We can verify objects in the live stack since none of these should reference dead objects.
1443 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1444 visitor(*it);
1445 }
1446
1447 if (visitor.Failed()) {
1448 DumpSpaces();
1449 return false;
1450 }
1451 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001452}
1453
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001454void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001455 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001456 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1457 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001458 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1459 ContinuousSpace* space = *it;
1460 // We never allocate into zygote spaces.
1461 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1462 (gc_type == kGcTypeFull &&
1463 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001464 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1465 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1466 if (live_bitmap != mark_bitmap) {
1467 live_bitmap_->ReplaceBitmap(live_bitmap, mark_bitmap);
1468 mark_bitmap_->ReplaceBitmap(mark_bitmap, live_bitmap);
1469 space->AsAllocSpace()->SwapBitmaps();
1470 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001471 }
1472 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001473 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001474}
1475
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001476void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001477 large_object_space_->SwapBitmaps();
1478 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1479 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001480}
1481
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001482void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001483 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001484 allocation_stack_.reset(live_stack_.release());
1485 live_stack_.reset(temp);
1486
1487 // Sort the live stack so that we can quickly binary search it later.
1488 if (VERIFY_OBJECT_ENABLED) {
1489 std::sort(live_stack_->Begin(), live_stack_->End());
1490 }
1491}
1492
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001493void Heap::ClearCards(TimingLogger& timings) {
1494 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1495 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1496 ContinuousSpace* space = *it;
1497 if (space->IsImageSpace()) {
1498 mod_union_table_->ClearCards(*it);
1499 timings.AddSplit("ModUnionClearCards");
1500 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1501 zygote_mod_union_table_->ClearCards(space);
1502 timings.AddSplit("ZygoteModUnionClearCards");
1503 } else {
1504 card_table_->ClearSpaceCards(space);
1505 timings.AddSplit("ClearCards");
1506 }
1507 }
1508}
1509
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001510void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1511 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001512 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1513 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001514 std::stringstream gc_type_str;
1515 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001516
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001517 // Suspend all threads are get exclusive access to the heap.
1518 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1519 thread_list->SuspendAll();
1520 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001521 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001522
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001523 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001524 Object* cleared_references = NULL;
1525 {
1526 MarkSweep mark_sweep(mark_stack_.get());
1527 timings.AddSplit("ctor");
1528
1529 mark_sweep.Init();
1530 timings.AddSplit("Init");
1531
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001532 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001533 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001534 if (!VerifyHeapReferences()) {
1535 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1536 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001537 timings.AddSplit("VerifyHeapReferencesPreGC");
1538 }
1539
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001540 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1541 SwapStacks();
1542
1543 // Check that all objects which reference things in the live stack are on dirty cards.
1544 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001545 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001546 // Sort the live stack so that we can quickly binary search it later.
1547 std::sort(live_stack_->Begin(), live_stack_->End());
1548 if (!VerifyMissingCardMarks()) {
1549 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1550 }
1551 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001552
1553 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1554 // TODO: Investigate using a mark stack instead of a vector.
1555 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001556 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001557 dirty_cards.reserve(4 * KB);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001558 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1559 card_table_->GetDirtyCards(*it, dirty_cards);
1560 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001561 timings.AddSplit("GetDirtyCards");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001562 }
1563
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001565 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001566
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001567 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001568 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001569
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001570 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001571 DCHECK(!GetLiveBitmap()->Test(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001572 }
1573
Mathieu Chartier0325e622012-09-05 14:22:51 -07001574 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001575 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1576 // accidentally un-mark roots.
1577 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001578 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001579 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1580 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001581 }
1582 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001583 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001584 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1585 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001586 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001587 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001588 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1589 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001590 }
1591 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001592 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001593 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001594 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001595 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1596 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001597 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001598 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001599
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001600 // Marking roots is not necessary for sticky mark bits since we only actually require the
1601 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001602 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001603 mark_sweep.MarkRoots();
1604 timings.AddSplit("MarkRoots");
1605 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001606
1607 if (verify_mod_union_table_) {
1608 zygote_mod_union_table_->Update();
1609 zygote_mod_union_table_->Verify();
1610 mod_union_table_->Update();
1611 mod_union_table_->Verify();
1612 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001613 }
1614
1615 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001616 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001617
1618 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1619 thread_list->ResumeAll();
1620 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001621 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001622 root_end = NanoTime();
1623 timings.AddSplit("RootEnd");
1624
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001625 // Mark the roots which we can do concurrently.
1626 mark_sweep.MarkConcurrentRoots();
1627 timings.AddSplit("MarkConcurrentRoots");
1628
Ian Rogers81d425b2012-09-27 16:03:43 -07001629 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001630 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001631
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001632 if (gc_type != kGcTypeSticky) {
1633 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1634 // knowing that new allocations won't be marked as live.
1635 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1636 live_stack_.get());
1637 timings.AddSplit("MarkStackAsLive");
1638 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001639
Mathieu Chartier0325e622012-09-05 14:22:51 -07001640 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001641 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001642 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001643 } else {
1644 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001645 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001646 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001647 }
1648 // Release share on mutator_lock_ and then get exclusive access.
1649 dirty_begin = NanoTime();
1650 thread_list->SuspendAll();
1651 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001652 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001653
1654 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001655 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001656
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001657 // Re-mark root set.
1658 mark_sweep.ReMarkRoots();
1659 timings.AddSplit("ReMarkRoots");
1660
1661 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001662 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001663 timings.AddSplit("RecursiveMarkDirtyObjects");
1664 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001665
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001666 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001667 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001668
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001669 mark_sweep.ProcessReferences(clear_soft_references);
1670 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001671 }
1672
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001673 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1674 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001675 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001676 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001677 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001678 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001679 // We only sweep over the live stack, and the live stack should not intersect with the
1680 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001681 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1682 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001683 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001684#ifndef NDEBUG
1685 if (gc_type == kGcTypeSticky) {
1686 // Make sure everything in the live stack isn't something we unmarked.
1687 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1688 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001689 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1690 << "Unmarked object " << *it << " in the live stack";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001691 }
1692 } else {
1693 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001694 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001695 }
1696 }
1697#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001698 }
1699
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001700 if (kIsDebugBuild) {
1701 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001702 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001703 mark_sweep.VerifyImageRoots();
1704 timings.AddSplit("VerifyImageRoots");
1705 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001706
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001707 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001708 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001709 // Swapping bound bitmaps does nothing.
1710 SwapBitmaps(kGcTypeFull);
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001711 if (!VerifyHeapReferences()) {
1712 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001713 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001714 SwapBitmaps(kGcTypeFull);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001715 timings.AddSplit("VerifyHeapReferencesPostGC");
1716 }
1717
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001718 thread_list->ResumeAll();
1719 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001720 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001721
1722 {
1723 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001724 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001725 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001726 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1727 timings.AddSplit("Sweep");
1728 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001729 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001730 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001731 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001732 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001733 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001734 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001735 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001736 }
1737
1738 {
1739 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1740 // Unbind the live and mark bitmaps.
1741 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001742
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001743 // Swap the live and mark bitmaps for each space which we modified space. This is an
1744 // optimization that enables us to not clear live bits inside of the sweep.
1745 const bool swap = true;
1746 if (swap) {
1747 if (gc_type == kGcTypeSticky) {
1748 SwapLargeObjects();
1749 } else {
1750 SwapBitmaps(gc_type);
1751 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001752 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001753 }
1754
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001755 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001756 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001757 mark_sweep.VerifySystemWeaks();
1758 timings.AddSplit("VerifySystemWeaks");
1759 }
1760
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001761 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001762 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001763 total_bytes_freed_ += bytes_freed;
1764 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001765 }
1766
1767 GrowForUtilization();
1768 timings.AddSplit("GrowForUtilization");
1769
1770 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001771 timings.AddSplit("EnqueueClearedReferences");
1772
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001773 RequestHeapTrim();
1774 timings.AddSplit("Finish");
1775
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001776 // If the GC was slow, then print timings in the log.
1777 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1778 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001779 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001780 total_paused_time_ += pause_roots + pause_dirty;
Mathieu Chartier0051be62012-10-12 17:47:11 -07001781 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5) ||
1782 (gc_cause == kGcCauseForAlloc && duration > MsToNs(20))) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001783 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001784 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001785 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001786 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001787 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001788 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001789 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1790 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001791 if (VLOG_IS_ON(heap)) {
1792 timings.Dump();
1793 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001794 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001795
Mathieu Chartier0325e622012-09-05 14:22:51 -07001796 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1797 logger->Start();
1798 logger->AddLogger(timings);
1799 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001800}
1801
Ian Rogers81d425b2012-09-27 16:03:43 -07001802GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001803 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001804 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001805 bool do_wait;
1806 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001807 {
1808 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001809 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001810 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001811 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001812 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001813 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001814 // We must wait, change thread state then sleep on gc_complete_cond_;
1815 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1816 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001817 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001818 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001819 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001820 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001821 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001822 wait_time = NanoTime() - wait_start;;
1823 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001824 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001825 if (wait_time > MsToNs(5)) {
1826 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1827 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001828 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001829 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001830 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001831}
1832
Elliott Hughesc967f782012-04-16 10:23:15 -07001833void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001834 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1835 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001836 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001837}
1838
1839size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001840 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001841}
1842
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001843void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001844 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001845 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001846 << PrettySize(GetMaxMemory());
1847 max_allowed_footprint = GetMaxMemory();
1848 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001849 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001850}
1851
Carl Shapiro69759ea2011-07-21 18:13:35 -07001852void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001853 // We know what our utilization is at this moment.
1854 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1855 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Mathieu Chartier0051be62012-10-12 17:47:11 -07001856 if (target_size > num_bytes_allocated_ + max_free_) {
1857 target_size = num_bytes_allocated_ + max_free_;
1858 } else if (target_size < num_bytes_allocated_ + min_free_) {
1859 target_size = num_bytes_allocated_ + min_free_;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001860 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001861
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001862 // Calculate when to perform the next ConcurrentGC.
1863 if (GetFreeMemory() < concurrent_min_free_) {
1864 // Not enough free memory to perform concurrent GC.
1865 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1866 } else {
1867 // Start a concurrent Gc when we get close to the target size.
1868 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001869 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001870
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001871 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001872}
1873
jeffhaoc1160702011-10-27 15:48:45 -07001874void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001875 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001876 alloc_space_->ClearGrowthLimit();
1877}
1878
Elliott Hughesadb460d2011-10-05 17:02:34 -07001879void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001880 MemberOffset reference_queue_offset,
1881 MemberOffset reference_queueNext_offset,
1882 MemberOffset reference_pendingNext_offset,
1883 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001884 reference_referent_offset_ = reference_referent_offset;
1885 reference_queue_offset_ = reference_queue_offset;
1886 reference_queueNext_offset_ = reference_queueNext_offset;
1887 reference_pendingNext_offset_ = reference_pendingNext_offset;
1888 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1889 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1890 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1891 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1892 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1893 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1894}
1895
1896Object* Heap::GetReferenceReferent(Object* reference) {
1897 DCHECK(reference != NULL);
1898 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1899 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1900}
1901
1902void Heap::ClearReferenceReferent(Object* reference) {
1903 DCHECK(reference != NULL);
1904 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1905 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1906}
1907
1908// Returns true if the reference object has not yet been enqueued.
1909bool Heap::IsEnqueuable(const Object* ref) {
1910 DCHECK(ref != NULL);
1911 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1912 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1913 return (queue != NULL) && (queue_next == NULL);
1914}
1915
1916void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1917 DCHECK(ref != NULL);
1918 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1919 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1920 EnqueuePendingReference(ref, cleared_reference_list);
1921}
1922
1923void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1924 DCHECK(ref != NULL);
1925 DCHECK(list != NULL);
1926
1927 if (*list == NULL) {
1928 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1929 *list = ref;
1930 } else {
1931 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1932 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1933 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1934 }
1935}
1936
1937Object* Heap::DequeuePendingReference(Object** list) {
1938 DCHECK(list != NULL);
1939 DCHECK(*list != NULL);
1940 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1941 Object* ref;
1942 if (*list == head) {
1943 ref = *list;
1944 *list = NULL;
1945 } else {
1946 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1947 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1948 ref = head;
1949 }
1950 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1951 return ref;
1952}
1953
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001954void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001955 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001956 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001957 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001958 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1959 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001960}
1961
1962size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001963 return num_bytes_allocated_;
1964}
1965
1966size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001967 size_t total = 0;
1968 // TODO: C++0x
1969 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1970 Space* space = *it;
1971 if (space->IsAllocSpace()) {
1972 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1973 }
1974 }
1975 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001976}
1977
1978size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001979 return concurrent_start_size_;
1980}
1981
1982size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001983 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001984}
1985
1986void Heap::EnqueueClearedReferences(Object** cleared) {
1987 DCHECK(cleared != NULL);
1988 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001989 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001990 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001991 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001992 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1993 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001994 *cleared = NULL;
1995 }
1996}
1997
Ian Rogers1f539342012-10-03 21:09:42 -07001998void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001999 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07002000 Runtime* runtime = Runtime::Current();
2001 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
2002 !runtime->IsConcurrentGcEnabled()) {
2003 return;
2004 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002005 {
2006 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2007 if (runtime->IsShuttingDown()) {
2008 return;
2009 }
2010 }
2011 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002012 return;
2013 }
2014
2015 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07002016 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002017 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2018 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002019 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2020 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002021 CHECK(!env->ExceptionCheck());
2022 requesting_gc_ = false;
2023}
2024
Ian Rogers81d425b2012-09-27 16:03:43 -07002025void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002026 {
2027 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2028 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2029 return;
2030 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002031 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002032
Ian Rogers81d425b2012-09-27 16:03:43 -07002033 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002034 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002035 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002036 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002037 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002038 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002039 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002040 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002041 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002042}
2043
Ian Rogers81d425b2012-09-27 16:03:43 -07002044void Heap::Trim(Thread* self) {
2045 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002046 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002047}
2048
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002049void Heap::RequestHeapTrim() {
2050 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2051 // because that only marks object heads, so a large array looks like lots of empty space. We
2052 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2053 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2054 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2055 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002056 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002057 float utilization =
2058 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2059 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2060 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2061 // heap trim occurred in the last two seconds.
2062 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002063 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002064
2065 Thread* self = Thread::Current();
2066 {
2067 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2068 Runtime* runtime = Runtime::Current();
2069 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2070 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2071 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2072 // as we don't hold the lock while requesting the trim).
2073 return;
2074 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002075 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002076 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002077 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002078 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2079 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002080 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2081 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002082 CHECK(!env->ExceptionCheck());
2083}
2084
Carl Shapiro69759ea2011-07-21 18:13:35 -07002085} // namespace art