blob: df0641d94a9359951d3e69ad8210fff729217af8 [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"
29#include "gc/mark_sweep.h"
30#include "gc/mod_union_table.h"
31#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070032#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070033#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080034#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080035#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070036#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070037#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070038#include "sirt_ref.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070039#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070040#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070041#include "timing_logger.h"
42#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070043#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070044
45namespace art {
46
Elliott Hughesae80b492012-04-24 10:43:17 -070047static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080048 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080049 std::vector<std::string> boot_class_path;
50 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070051 if (boot_class_path.empty()) {
52 LOG(FATAL) << "Failed to generate image because no boot class path specified";
53 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080054
55 std::vector<char*> arg_vector;
56
57 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070058 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080059 const char* dex2oat = dex2oat_string.c_str();
60 arg_vector.push_back(strdup(dex2oat));
61
62 std::string image_option_string("--image=");
63 image_option_string += image_file_name;
64 const char* image_option = image_option_string.c_str();
65 arg_vector.push_back(strdup(image_option));
66
67 arg_vector.push_back(strdup("--runtime-arg"));
68 arg_vector.push_back(strdup("-Xms64m"));
69
70 arg_vector.push_back(strdup("--runtime-arg"));
71 arg_vector.push_back(strdup("-Xmx64m"));
72
73 for (size_t i = 0; i < boot_class_path.size(); i++) {
74 std::string dex_file_option_string("--dex-file=");
75 dex_file_option_string += boot_class_path[i];
76 const char* dex_file_option = dex_file_option_string.c_str();
77 arg_vector.push_back(strdup(dex_file_option));
78 }
79
80 std::string oat_file_option_string("--oat-file=");
81 oat_file_option_string += image_file_name;
82 oat_file_option_string.erase(oat_file_option_string.size() - 3);
83 oat_file_option_string += "oat";
84 const char* oat_file_option = oat_file_option_string.c_str();
85 arg_vector.push_back(strdup(oat_file_option));
86
87 arg_vector.push_back(strdup("--base=0x60000000"));
88
Elliott Hughes48436bb2012-02-07 15:23:28 -080089 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080090 LOG(INFO) << command_line;
91
Elliott Hughes48436bb2012-02-07 15:23:28 -080092 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -080093 char** argv = &arg_vector[0];
94
95 // fork and exec dex2oat
96 pid_t pid = fork();
97 if (pid == 0) {
98 // no allocation allowed between fork and exec
99
100 // change process groups, so we don't get reaped by ProcessManager
101 setpgid(0, 0);
102
103 execv(dex2oat, argv);
104
105 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
106 return false;
107 } else {
108 STLDeleteElements(&arg_vector);
109
110 // wait for dex2oat to finish
111 int status;
112 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
113 if (got_pid != pid) {
114 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
115 return false;
116 }
117 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
118 LOG(ERROR) << dex2oat << " failed: " << command_line;
119 return false;
120 }
121 }
122 return true;
123}
124
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700125void Heap::UnReserveOatFileAddressRange() {
126 oat_file_map_.reset(NULL);
127}
128
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800129Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700130 const std::string& original_image_file_name, bool concurrent_gc)
131 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800132 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700133 concurrent_gc_(concurrent_gc),
134 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800135 card_marking_disabled_(false),
136 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700137 last_gc_type_(kGcTypeNone),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700138 growth_limit_(growth_limit),
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700139 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700140 concurrent_start_size_(128 * KB),
141 concurrent_min_free_(256 * KB),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700142 concurrent_gc_start_rate_(3 * MB / 2),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700143 sticky_gc_count_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700144 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800145 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700146 verify_missing_card_marks_(false),
147 verify_system_weaks_(false),
148 verify_pre_gc_heap_(false),
149 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700150 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700151 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700152 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700153 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700154 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700155 try_running_gc_(false),
156 requesting_gc_(false),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700157 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800158 reference_referent_offset_(0),
159 reference_queue_offset_(0),
160 reference_queueNext_offset_(0),
161 reference_pendingNext_offset_(0),
162 finalizer_reference_zombie_offset_(0),
163 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700164 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800165 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800166 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700167 }
168
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700169 live_bitmap_.reset(new HeapBitmap(this));
170 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700171
Ian Rogers30fab402012-01-23 15:43:46 -0800172 // Requested begin for the alloc space, to follow the mapped image and oat files
173 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800174 std::string image_file_name(original_image_file_name);
175 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700176 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700177
Brian Carlstrom5643b782012-02-05 12:32:53 -0800178 if (OS::FileExists(image_file_name.c_str())) {
179 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700180 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800181 } else {
182 // If the /system file didn't exist, we need to use one from the art-cache.
183 // If the cache file exists, try to open, but if it fails, regenerate.
184 // If it does not exist, generate.
185 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
186 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700187 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800188 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700189 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700190 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700191 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800192 }
193 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700194
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700195 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700196 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800197 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
198 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700199 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
200 CHECK_GT(oat_end_addr, image_space->End());
201
202 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
203 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
204 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
205 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
206 reinterpret_cast<byte*>(reserve_begin),
207 reserve_end - reserve_begin, PROT_READ));
208
Ian Rogers30fab402012-01-23 15:43:46 -0800209 if (oat_end_addr > requested_begin) {
210 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700211 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700212 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700213 }
214
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700215 // Allocate the large object space.
216 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700217 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
218 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
219
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700220 UniquePtr<AllocSpace> alloc_space(AllocSpace::Create("alloc space", initial_size, growth_limit,
221 capacity, requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700222 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700223 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700224 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700225
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700226 // Spaces are sorted in order of Begin().
227 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700228 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
229 if (spaces_.back()->IsAllocSpace()) {
230 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
231 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700232
Ian Rogers30fab402012-01-23 15:43:46 -0800233 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700234 // TODO: C++0x
235 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
236 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800237 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700238 ImageSpace* image_space = space->AsImageSpace();
239 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800240 }
241 }
242
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800243 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700244 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
245 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700246
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700247 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
248 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700249
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700250 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
251 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700252
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700253 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700254 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700255
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700256 // Max stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700257 static const size_t default_mark_stack_size = 64 * KB;
258 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
259 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700260 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700261 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
262 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700263
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800264 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700265 // but we can create the heap lock now. We don't create it earlier to
266 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700267 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700268 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700269
Mathieu Chartier0325e622012-09-05 14:22:51 -0700270 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700271 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
272 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700273 std::ostringstream name;
274 name << static_cast<GcType>(i);
275 cumulative_timings_.Put(static_cast<GcType>(i),
276 new CumulativeLogger(name.str().c_str(), true));
277 }
278
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800279 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800280 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700281 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700282}
283
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700284// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700285struct SpaceSorter {
286 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700287 return a->Begin() < b->Begin();
288 }
289};
290
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700291void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700292 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700293 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700294 DCHECK(space->GetLiveBitmap() != NULL);
295 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700296 DCHECK(space->GetMarkBitmap() != NULL);
297 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800298 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700299 if (space->IsAllocSpace()) {
300 alloc_space_ = space->AsAllocSpace();
301 }
302
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700303 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
304 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700305
306 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
307 // avoid redundant marking.
308 bool seen_zygote = false, seen_alloc = false;
309 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
310 Space* space = *it;
311 if (space->IsImageSpace()) {
312 DCHECK(!seen_zygote);
313 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700314 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700315 DCHECK(!seen_alloc);
316 seen_zygote = true;
317 } else if (space->IsAllocSpace()) {
318 seen_alloc = true;
319 }
320 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800321}
322
323Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700324 // If we don't reset then the mark stack complains in it's destructor.
325 allocation_stack_->Reset();
326 live_stack_->Reset();
327
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800328 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800329 // We can't take the heap lock here because there might be a daemon thread suspended with the
330 // heap lock held. We know though that no non-daemon threads are executing, and we know that
331 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
332 // 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 -0700333 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700334 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700335 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700336}
337
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700338ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700339 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700340 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
341 if ((*it)->Contains(obj)) {
342 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700343 }
344 }
345 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
346 return NULL;
347}
348
349ImageSpace* Heap::GetImageSpace() {
350 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700351 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
352 if ((*it)->IsImageSpace()) {
353 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700354 }
355 }
356 return NULL;
357}
358
359AllocSpace* Heap::GetAllocSpace() {
360 return alloc_space_;
361}
362
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700363static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700364 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700365 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700366 size_t chunk_free_bytes = chunk_size - used_bytes;
367 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
368 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700369 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700370}
371
Ian Rogers50b35e22012-10-04 10:09:15 -0700372Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700373 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
374 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
375 strlen(ClassHelper(c).GetDescriptor()) == 0);
376 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700377
378 Object* obj = NULL;
379 size_t size = 0;
380
381 // We need to have a zygote space or else our newly allocated large object can end up in the
382 // Zygote resulting in it being prematurely freed.
383 // We can only do this for primive objects since large objects will not be within the card table
384 // range. This also means that we rely on SetClass not dirtying the object's card.
385 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700386 size = RoundUp(byte_count, kPageSize);
Ian Rogers50b35e22012-10-04 10:09:15 -0700387 obj = Allocate(self, NULL, size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700388
389 if (obj != NULL) {
390 // Make sure that our large object didn't get placed anywhere within the space interval or else
391 // it breaks the immune range.
392 DCHECK(reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
393 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
394 }
395 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700396 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700397 size = alloc_space_->AllocationSize(obj);
398
399 if (obj != NULL) {
400 // Additional verification to ensure that we did not allocate into a zygote space.
401 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
402 }
403 }
404
Mathieu Chartier037813d2012-08-23 16:44:59 -0700405 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700406 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700407
408 // Record allocation after since we want to use the atomic add for the atomic fence to guard
409 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700410 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700411
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700412 if (Dbg::IsAllocTrackingEnabled()) {
413 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700414 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700415 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700416 // We already have a request pending, no reason to start more until we update
417 // concurrent_start_bytes_.
418 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700419 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700420 SirtRef<Object> ref(self, obj);
421 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700422 }
423 VerifyObject(obj);
424
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700425 return obj;
426 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700427 int64_t total_bytes_free = GetFreeMemory();
428 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700430 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
431 if ((*it)->IsAllocSpace()) {
432 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700433 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700434 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700435
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700436 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 -0700437 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700438 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700439 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700440}
441
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700442bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700443 // Note: we deliberately don't take the lock here, and mustn't test anything that would
444 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700445 if (obj == NULL) {
446 return true;
447 }
448 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700449 return false;
450 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800451 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800452 if (spaces_[i]->Contains(obj)) {
453 return true;
454 }
455 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700456 // TODO: Find a way to check large object space without using a lock.
457 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700458}
459
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700460bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700461 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700462 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700463}
464
Elliott Hughes3e465b12011-09-02 18:26:12 -0700465#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700466void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700467 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700468 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700469 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700470 return;
471 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700472 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700473}
474#endif
475
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700476void Heap::DumpSpaces() {
477 // TODO: C++0x auto
478 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700479 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700480 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
481 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
482 LOG(INFO) << space << " " << *space << "\n"
483 << live_bitmap << " " << *live_bitmap << "\n"
484 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700485 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700486 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700487}
488
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700489void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700490 if (!IsAligned<kObjectAlignment>(obj)) {
491 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700492 }
493
Mathieu Chartier0325e622012-09-05 14:22:51 -0700494 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700495 // Check the allocation stack / live stack.
496 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
497 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
498 allocation_stack_->End()) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700499 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700500 if (large_object_space_->GetLiveObjects()->Test(obj)) {
501 DumpSpaces();
502 LOG(FATAL) << "Object is dead: " << obj;
503 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700504 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700505 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700506
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700507 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700508 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700509 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
510 Object::ClassOffset().Int32Value();
511 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
512 if (c == NULL) {
513 LOG(FATAL) << "Null class in object: " << obj;
514 } else if (!IsAligned<kObjectAlignment>(c)) {
515 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
516 } else if (!GetLiveBitmap()->Test(c)) {
517 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
518 }
519 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
520 // Note: we don't use the accessors here as they have internal sanity checks
521 // that we don't want to run
522 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
523 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
524 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
525 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
526 CHECK_EQ(c_c, c_c_c);
527 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700528}
529
Brian Carlstrom78128a62011-09-15 17:21:19 -0700530void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700531 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700532 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700533}
534
535void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700536 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700537 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700538}
539
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700540void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700541 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700542 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700543 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700544
545 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700546 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700547 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700548 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700549
550 // TODO: Update these atomically.
551 RuntimeStats* global_stats = Runtime::Current()->GetStats();
552 ++global_stats->allocated_objects;
553 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700554 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700555
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700556 // This is safe to do since the GC will never free objects which are neither in the allocation
557 // stack or the live bitmap.
558 while (!allocation_stack_->AtomicPushBack(obj)) {
559 Thread* self = Thread::Current();
560 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
561 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
562 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
563 self->TransitionFromSuspendedToRunnable();
564 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700565}
566
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700567void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier637e3482012-08-17 10:41:32 -0700568 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
569 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700570 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
571 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700572
573 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700574 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700575 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700576 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700577
578 // TODO: Do this concurrently.
579 RuntimeStats* global_stats = Runtime::Current()->GetStats();
580 global_stats->freed_objects += freed_objects;
581 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700582 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700583}
584
Ian Rogers50b35e22012-10-04 10:09:15 -0700585Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700586 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
587 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
588 return NULL;
589 }
590
Mathieu Chartier83cf3282012-09-26 17:54:27 -0700591 if (UNLIKELY(space == NULL)) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700592 return large_object_space_->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700593 } else if (grow) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700594 return space->AllocWithGrowth(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700595 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700596 return space->AllocWithoutGrowth(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700597 }
598}
599
Ian Rogers50b35e22012-10-04 10:09:15 -0700600Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700601 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
602 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700603 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700604 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700605
Ian Rogers50b35e22012-10-04 10:09:15 -0700606 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700607 if (ptr != NULL) {
608 return ptr;
609 }
610
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700611 // The allocation failed. If the GC is running, block until it completes, and then retry the
612 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700613 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700614 if (last_gc != kGcTypeNone) {
615 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700616 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700617 if (ptr != NULL) {
618 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700619 }
620 }
621
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700622 // Loop through our different Gc types and try to Gc until we get enough free memory.
623 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
624 bool run_gc = false;
625 GcType gc_type = static_cast<GcType>(i);
626 switch (gc_type) {
627 case kGcTypeSticky: {
628 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700629 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
630 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700631 break;
632 }
633 case kGcTypePartial:
634 run_gc = have_zygote_space_;
635 break;
636 case kGcTypeFull:
637 run_gc = true;
638 break;
639 default:
640 break;
641 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700642
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700643 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700644 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
645
646 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700647 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700648 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
649 i = static_cast<size_t>(gc_type_ran);
650 self->TransitionFromSuspendedToRunnable();
651
652 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700653 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700654 if (ptr != NULL) {
655 return ptr;
656 }
657 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700658 }
659
660 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700661 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700662 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700663 if (ptr != NULL) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700664 if (space != NULL) {
665 size_t new_footprint = space->GetFootprintLimit();
666 // OLD-TODO: may want to grow a little bit more so that the amount of
667 // free space is equal to the old free space + the
668 // utilization slop for the new allocation.
669 VLOG(gc) << "Grow alloc space (frag case) to " << PrettySize(new_footprint)
670 << " for a " << PrettySize(alloc_size) << " allocation";
671 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700672 return ptr;
673 }
674
Elliott Hughes81ff3182012-03-23 20:35:56 -0700675 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
676 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
677 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700678
Elliott Hughes418dfe72011-10-06 18:56:27 -0700679 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700680 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
681 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700682
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700683 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700684 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700685 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700686 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700687 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700688}
689
Elliott Hughesbf86d042011-08-31 17:53:14 -0700690int64_t Heap::GetMaxMemory() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700691 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700692}
693
694int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700695 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700696}
697
698int64_t Heap::GetFreeMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700699 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700700}
701
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700702class InstanceCounter {
703 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700704 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700705 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700706 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700707
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700708 }
709
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700710 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
711 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700712 if (count_assignable_) {
713 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700714 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700715 }
716 } else {
717 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700718 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700719 }
720 }
721 }
722
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700723 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700724 Class* class_;
725 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700726 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700727};
728
729int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700730 size_t count = 0;
731 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700732 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700733 GetLiveBitmap()->Visit(counter);
734 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700735}
736
Ian Rogers30fab402012-01-23 15:43:46 -0800737void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700738 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
739 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700740 Thread* self = Thread::Current();
741 WaitForConcurrentGcToComplete(self);
742 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700743 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
744 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700745}
746
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700747void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700748 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700749 Thread* self = Thread::Current();
750 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700751
752 // Try to see if we have any Zygote spaces.
753 if (have_zygote_space_) {
754 return;
755 }
756
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700757 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
758
759 {
760 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700761 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700762 FlushAllocStack();
763 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700764
765 // Replace the first alloc space we find with a zygote space.
766 // TODO: C++0x auto
767 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
768 if ((*it)->IsAllocSpace()) {
769 AllocSpace* zygote_space = (*it)->AsAllocSpace();
770
771 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
772 // of the remaining available heap memory.
773 alloc_space_ = zygote_space->CreateZygoteSpace();
774
775 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700776 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700777 AddSpace(alloc_space_);
778 have_zygote_space_ = true;
779 break;
780 }
781 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700782
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700783 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700784 // TODO: C++0x
785 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
786 it != cumulative_timings_.end(); ++it) {
787 it->second->Reset();
788 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700789}
790
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700791void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700792 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
793 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700794 allocation_stack_->Reset();
795}
796
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700797size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700798 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700799}
800
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700801void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
802 Object** limit = stack->End();
803 for (Object** it = stack->Begin(); it != limit; ++it) {
804 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700805 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700806 if (LIKELY(bitmap->HasAddress(obj))) {
807 bitmap->Set(obj);
808 } else {
809 large_objects->Set(obj);
810 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700811 }
812}
813
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700814void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
815 Object** limit = stack->End();
816 for (Object** it = stack->Begin(); it != limit; ++it) {
817 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700818 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700819 if (LIKELY(bitmap->HasAddress(obj))) {
820 bitmap->Clear(obj);
821 } else {
822 large_objects->Clear(obj);
823 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700824 }
825}
826
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700827GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700828 Thread* self = Thread::Current();
829 Locks::mutator_lock_->AssertNotHeld(self);
830 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700831
Ian Rogers120f1c72012-09-28 17:17:10 -0700832 if (self->IsHandlingStackOverflow()) {
833 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
834 }
835
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700836 // Ensure there is only one GC at a time.
837 bool start_collect = false;
838 while (!start_collect) {
839 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700840 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700841 if (!is_gc_running_) {
842 is_gc_running_ = true;
843 start_collect = true;
844 }
845 }
846 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700847 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700848 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
849 // Not doing at the moment to ensure soft references are cleared.
850 }
851 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700852 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700853
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700854 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
855 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
856 ++Thread::Current()->GetStats()->gc_for_alloc_count;
857 }
858
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700859 // We need to do partial GCs every now and then to avoid the heap growing too much and
860 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700861 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700862 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700863 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700864 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700865 sticky_gc_count_ = 0;
866 }
867
Mathieu Chartier637e3482012-08-17 10:41:32 -0700868 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700869 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700870 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700871 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700872 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700873 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700874
Ian Rogers15bf2d32012-08-28 17:33:04 -0700875 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700876 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700877 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700878 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700879 // Wake anyone who may have been waiting for the GC to complete.
880 gc_complete_cond_->Broadcast();
881 }
882 // Inform DDMS that a GC completed.
883 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700884 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700885}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700886
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700887void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
888 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700889 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700890
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700891 std::stringstream gc_type_str;
892 gc_type_str << gc_type << " ";
893
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700894 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700895 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700896 ThreadList* thread_list = Runtime::Current()->GetThreadList();
897 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700898 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700899 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700900
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700901 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700902 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700903 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700904 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700905 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700906 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700907
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700908 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700909 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700910 if (!VerifyHeapReferences()) {
911 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
912 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700913 timings.AddSplit("VerifyHeapReferencesPreGC");
914 }
915
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700916 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700917 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700918
919 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
920 // TODO: Investigate using a mark stack instead of a vector.
921 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700922 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700923 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
924 card_table_->GetDirtyCards(*it, dirty_cards);
925 }
926 }
927
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700928 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700929 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700930
Ian Rogers120f1c72012-09-28 17:17:10 -0700931 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700932 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700933 // Copy the mark bits over from the live bits, do this as early as possible or else we can
934 // accidentally un-mark roots.
935 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700936 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700937 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
938 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700939 }
940 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700941 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700942
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700943 // We can assume that everything from the start of the first space to the alloc space is marked.
944 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
945 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700946 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700947 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700948 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
949 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700950 }
951 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700952 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700953 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700954 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700955 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
956 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700957 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700958 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700959
Carl Shapiro58551df2011-07-24 03:09:51 -0700960 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700961 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700962
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700963 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700964 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700965
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700966 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
967
968 if (gc_type != kGcTypeSticky) {
969 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
970 live_stack_.get());
971 timings.AddSplit("MarkStackAsLive");
972 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700973
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700974 if (verify_mod_union_table_) {
975 zygote_mod_union_table_->Update();
976 zygote_mod_union_table_->Verify();
977 mod_union_table_->Update();
978 mod_union_table_->Verify();
979 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700980
981 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700982 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700983 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700984 } else {
985 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
986 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700987 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -0700988
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700989 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -0800990 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700991 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700992
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700993#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700994 // Verify that we only reach marked objects from the image space
995 mark_sweep.VerifyImageRoots();
996 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700997#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700998
Mathieu Chartier0325e622012-09-05 14:22:51 -0700999 if (gc_type != kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001000 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1001 timings.AddSplit("Sweep");
1002 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001003 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001004 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001005 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001006 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001007 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001008 live_stack_->Reset();
1009
1010 // Unbind the live and mark bitmaps.
1011 mark_sweep.UnBindBitmaps();
1012
1013 const bool swap = true;
1014 if (swap) {
1015 if (gc_type == kGcTypeSticky) {
1016 SwapLargeObjects(self);
1017 } else {
1018 SwapBitmaps(self, gc_type);
1019 }
1020 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001021
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001022 if (verify_system_weaks_) {
1023 mark_sweep.VerifySystemWeaks();
1024 timings.AddSplit("VerifySystemWeaks");
1025 }
1026
Elliott Hughesadb460d2011-10-05 17:02:34 -07001027 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001028 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001029 }
1030
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001031 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001032 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001033 if (!VerifyHeapReferences()) {
1034 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1035 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001036 timings.AddSplit("VerifyHeapReferencesPostGC");
1037 }
1038
Carl Shapiro58551df2011-07-24 03:09:51 -07001039 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001040 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001041
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001042 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001043 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001044
1045 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001046 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001047 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001048
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001049 // If the GC was slow, then print timings in the log.
1050 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1051 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001052 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001053 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001054 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001055 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001056 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001057 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001058 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001059 if (VLOG_IS_ON(heap)) {
1060 timings.Dump();
1061 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001062 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001063
Mathieu Chartier0325e622012-09-05 14:22:51 -07001064 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1065 logger->Start();
1066 logger->AddLogger(timings);
1067 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001068}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001069
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001070void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001071 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001072 // 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 -07001073 // cards.
1074 return;
1075 }
1076
1077 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001078 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001079 zygote_mod_union_table_->Update();
1080 timings.AddSplit("UpdateZygoteModUnionTable");
1081
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001082 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001083 timings.AddSplit("ZygoteMarkReferences");
1084 }
1085
1086 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1087 mod_union_table_->Update();
1088 timings.AddSplit("UpdateModUnionTable");
1089
1090 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001091 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001092 timings.AddSplit("MarkImageToAllocSpaceReferences");
1093}
1094
1095void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1096 Object* obj = reinterpret_cast<Object*>(arg);
1097 if (root == obj) {
1098 LOG(INFO) << "Object " << obj << " is a root";
1099 }
1100}
1101
1102class ScanVisitor {
1103 public:
1104 void operator ()(const Object* obj) const {
1105 LOG(INFO) << "Would have rescanned object " << obj;
1106 }
1107};
1108
1109class VerifyReferenceVisitor {
1110 public:
1111 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001112 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1113 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001114 : heap_(heap),
1115 failed_(failed) {
1116 }
1117
1118 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1119 // analysis.
1120 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1121 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1122 // Verify that the reference is live.
1123 if (ref != NULL && !IsLive(ref)) {
1124 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001125 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1126 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001127
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001128 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001129 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1130 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1131 << "Obj type " << PrettyTypeOf(obj) << "\n"
1132 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001133 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001134 void* cover_begin = card_table->AddrFromCard(card_addr);
1135 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001136 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001137 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001138 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001139 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1140
1141 // Print out how the object is live.
1142 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001143 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1144 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001145 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1146 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1147 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001148 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1149 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001150 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001151 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001152 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001153 }
1154
1155 // Attempt to see if the card table missed the reference.
1156 ScanVisitor scan_visitor;
1157 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001158 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1159 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001160
1161 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001162 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001163 MarkSweep ms(mark_stack);
1164 ms.Init();
1165 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001166 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001167
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001168 // All the references should end up in the mark stack.
1169 ms.ScanRoot(obj);
1170 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001171 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001172 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001173 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001174 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001175 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001176 }
1177 }
1178 mark_stack->Reset();
1179
1180 // Search to see if any of the roots reference our object.
1181 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1182 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1183 *failed_ = true;
1184 }
1185 }
1186
1187 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1188 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1189 if (bitmap != NULL) {
1190 if (bitmap->Test(obj)) {
1191 return true;
1192 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001193 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001194 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001195 } else {
1196 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001197 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001198 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001199 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001200 // At this point we need to search the allocation since things in the live stack may get swept.
1201 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1202 return true;
1203 }
1204 // Not either in the live bitmap or allocation stack, so the object must be dead.
1205 return false;
1206 }
1207
1208 private:
1209 Heap* heap_;
1210 bool* failed_;
1211};
1212
1213class VerifyObjectVisitor {
1214 public:
1215 VerifyObjectVisitor(Heap* heap)
1216 : heap_(heap),
1217 failed_(false) {
1218
1219 }
1220
1221 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001222 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001223 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1224 MarkSweep::VisitObjectReferences(obj, visitor);
1225 }
1226
1227 bool Failed() const {
1228 return failed_;
1229 }
1230
1231 private:
1232 Heap* heap_;
1233 bool failed_;
1234};
1235
1236// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001237bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001238 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001239 // Lets sort our allocation stacks so that we can efficiently binary search them.
1240 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1241 std::sort(live_stack_->Begin(), live_stack_->End());
1242 // Perform the verification.
1243 VerifyObjectVisitor visitor(this);
1244 GetLiveBitmap()->Visit(visitor);
1245 // We don't want to verify the objects in the allocation stack since they themselves may be
1246 // pointing to dead objects if they are not reachable.
1247 if (visitor.Failed()) {
1248 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001249 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001250 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001251 return true;
1252}
1253
1254class VerifyReferenceCardVisitor {
1255 public:
1256 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1257 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1258 Locks::heap_bitmap_lock_)
1259 : heap_(heap),
1260 failed_(failed) {
1261 }
1262
1263 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1264 // analysis.
1265 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1266 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001267 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001268 CardTable* card_table = heap_->GetCardTable();
1269 // If the object is not dirty and it is referencing something in the live stack other than
1270 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001271 if (!card_table->AddrIsInCardTable(obj)) {
1272 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1273 *failed_ = true;
1274 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001275 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001276 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1277 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1278 LOG(ERROR) << "Object " << obj << " found in live stack";
1279 }
1280 if (heap_->GetLiveBitmap()->Test(obj)) {
1281 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1282 }
1283 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1284 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1285
1286 // Print which field of the object is dead.
1287 if (!obj->IsObjectArray()) {
1288 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1289 CHECK(klass != NULL);
1290 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1291 CHECK(fields != NULL);
1292 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1293 const Field* cur = fields->Get(i);
1294 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1295 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1296 << PrettyField(cur);
1297 break;
1298 }
1299 }
1300 } else {
1301 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1302 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1303 if (object_array->Get(i) == ref) {
1304 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1305 }
1306 }
1307 }
1308
1309 *failed_ = true;
1310 }
1311 }
1312 }
1313 }
1314
1315 private:
1316 Heap* heap_;
1317 bool* failed_;
1318};
1319
1320class VerifyLiveStackReferences {
1321 public:
1322 VerifyLiveStackReferences(Heap* heap)
1323 : heap_(heap),
1324 failed_(false) {
1325
1326 }
1327
1328 void operator ()(const Object* obj) const
1329 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1330 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1331 MarkSweep::VisitObjectReferences(obj, visitor);
1332 }
1333
1334 bool Failed() const {
1335 return failed_;
1336 }
1337
1338 private:
1339 Heap* heap_;
1340 bool failed_;
1341};
1342
1343bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001344 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001345
1346 VerifyLiveStackReferences visitor(this);
1347 GetLiveBitmap()->Visit(visitor);
1348
1349 // We can verify objects in the live stack since none of these should reference dead objects.
1350 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1351 visitor(*it);
1352 }
1353
1354 if (visitor.Failed()) {
1355 DumpSpaces();
1356 return false;
1357 }
1358 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001359}
1360
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001361void Heap::SwapBitmaps(Thread* self, GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001362 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001363 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1364 // bits of dead objects in the live bitmap.
1365 {
1366 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1367 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1368 ContinuousSpace* space = *it;
1369 // We never allocate into zygote spaces.
1370 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1371 (gc_type == kGcTypeFull &&
1372 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
1373 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1374 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1375 space->AsAllocSpace()->SwapBitmaps();
1376 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001377 }
1378 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001379
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001380 SwapLargeObjects(self);
1381}
1382
1383void Heap::SwapLargeObjects(Thread* self) {
1384 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001385 large_object_space_->SwapBitmaps();
1386 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1387 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001388}
1389
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001390void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001391 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001392 allocation_stack_.reset(live_stack_.release());
1393 live_stack_.reset(temp);
1394
1395 // Sort the live stack so that we can quickly binary search it later.
1396 if (VERIFY_OBJECT_ENABLED) {
1397 std::sort(live_stack_->Begin(), live_stack_->End());
1398 }
1399}
1400
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001401void Heap::ClearCards(TimingLogger& timings) {
1402 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1403 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1404 ContinuousSpace* space = *it;
1405 if (space->IsImageSpace()) {
1406 mod_union_table_->ClearCards(*it);
1407 timings.AddSplit("ModUnionClearCards");
1408 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1409 zygote_mod_union_table_->ClearCards(space);
1410 timings.AddSplit("ZygoteModUnionClearCards");
1411 } else {
1412 card_table_->ClearSpaceCards(space);
1413 timings.AddSplit("ClearCards");
1414 }
1415 }
1416}
1417
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001418void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1419 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001420 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1421 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001422 std::stringstream gc_type_str;
1423 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001424
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001425 // Suspend all threads are get exclusive access to the heap.
1426 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1427 thread_list->SuspendAll();
1428 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001429 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001430
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001431 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001432 Object* cleared_references = NULL;
1433 {
1434 MarkSweep mark_sweep(mark_stack_.get());
1435 timings.AddSplit("ctor");
1436
1437 mark_sweep.Init();
1438 timings.AddSplit("Init");
1439
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001440 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001441 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001442 if (!VerifyHeapReferences()) {
1443 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1444 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001445 timings.AddSplit("VerifyHeapReferencesPreGC");
1446 }
1447
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001448 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1449 SwapStacks();
1450
1451 // Check that all objects which reference things in the live stack are on dirty cards.
1452 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001453 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001454 // Sort the live stack so that we can quickly binary search it later.
1455 std::sort(live_stack_->Begin(), live_stack_->End());
1456 if (!VerifyMissingCardMarks()) {
1457 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1458 }
1459 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001460
1461 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1462 // TODO: Investigate using a mark stack instead of a vector.
1463 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001464 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001465 dirty_cards.reserve(4 * KB);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001466 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1467 card_table_->GetDirtyCards(*it, dirty_cards);
1468 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001469 timings.AddSplit("GetDirtyCards");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001470 }
1471
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001472 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001473 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001474
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001475 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001476 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001477
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001478 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001479 DCHECK(!GetLiveBitmap()->Test(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001480 }
1481
Mathieu Chartier0325e622012-09-05 14:22:51 -07001482 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001483 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1484 // accidentally un-mark roots.
1485 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001486 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001487 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1488 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001489 }
1490 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001491 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001492 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1493 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001494 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001495 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001496 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1497 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001498 }
1499 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001500 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001501 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001502 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001503 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1504 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001505 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001506 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001507
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001508 // Marking roots is not necessary for sticky mark bits since we only actually require the
1509 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001510 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001511 mark_sweep.MarkRoots();
1512 timings.AddSplit("MarkRoots");
1513 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001514
1515 if (verify_mod_union_table_) {
1516 zygote_mod_union_table_->Update();
1517 zygote_mod_union_table_->Verify();
1518 mod_union_table_->Update();
1519 mod_union_table_->Verify();
1520 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001521 }
1522
1523 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001524 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001525
1526 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1527 thread_list->ResumeAll();
1528 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001529 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001530 root_end = NanoTime();
1531 timings.AddSplit("RootEnd");
1532
Ian Rogers81d425b2012-09-27 16:03:43 -07001533 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001534 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001535
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001536 if (gc_type != kGcTypeSticky) {
1537 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1538 // knowing that new allocations won't be marked as live.
1539 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1540 live_stack_.get());
1541 timings.AddSplit("MarkStackAsLive");
1542 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001543
Mathieu Chartier0325e622012-09-05 14:22:51 -07001544 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001545 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001546 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001547 } else {
1548 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001549 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001550 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001551 }
1552 // Release share on mutator_lock_ and then get exclusive access.
1553 dirty_begin = NanoTime();
1554 thread_list->SuspendAll();
1555 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001556 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557
1558 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001559 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001560
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001561 // Re-mark root set.
1562 mark_sweep.ReMarkRoots();
1563 timings.AddSplit("ReMarkRoots");
1564
1565 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001566 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001567 timings.AddSplit("RecursiveMarkDirtyObjects");
1568 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001569
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001570 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001571 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001572
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001573 mark_sweep.ProcessReferences(clear_soft_references);
1574 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001575 }
1576
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001577 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1578 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001579 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001580 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001581 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001582 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001583 // We only sweep over the live stack, and the live stack should not intersect with the
1584 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001585 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1586 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001587 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001588#ifndef NDEBUG
1589 if (gc_type == kGcTypeSticky) {
1590 // Make sure everything in the live stack isn't something we unmarked.
1591 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1592 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1593 if (std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it)) {
1594 LOG(FATAL) << "Unmarked object " << *it << " in the live stack";
1595 }
1596 }
1597 } else {
1598 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
1599 if (GetLiveBitmap()->Test(*it)) {
1600 LOG(FATAL) << "Object " << *it << " is marked as live";
1601 }
1602 }
1603 }
1604#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001605 }
1606
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001607 if (kIsDebugBuild) {
1608 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001609 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001610 mark_sweep.VerifyImageRoots();
1611 timings.AddSplit("VerifyImageRoots");
1612 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001613
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001614 if (verify_post_gc_heap_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001615 SwapBitmaps(self, gc_type);
1616 {
1617 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1618 if (!VerifyHeapReferences()) {
1619 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
1620 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001621 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001622 SwapBitmaps(self, gc_type);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001623 timings.AddSplit("VerifyHeapReferencesPostGC");
1624 }
1625
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001626 thread_list->ResumeAll();
1627 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001628 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001629
1630 {
1631 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001632 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001633 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001634 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1635 timings.AddSplit("Sweep");
1636 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001637 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001638 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001639 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001640 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001641 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001642 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001643 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001644 }
1645
1646 {
1647 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1648 // Unbind the live and mark bitmaps.
1649 mark_sweep.UnBindBitmaps();
1650 }
1651
1652 // Swap the live and mark bitmaps for each space which we modified space. This is an
1653 // optimization that enables us to not clear live bits inside of the sweep.
1654 const bool swap = true;
1655 if (swap) {
1656 if (gc_type == kGcTypeSticky) {
1657 SwapLargeObjects(self);
1658 } else {
1659 SwapBitmaps(self, gc_type);
1660 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001661 }
1662
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001663 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001664 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001665 mark_sweep.VerifySystemWeaks();
1666 timings.AddSplit("VerifySystemWeaks");
1667 }
1668
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001669 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001670 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001671 }
1672
1673 GrowForUtilization();
1674 timings.AddSplit("GrowForUtilization");
1675
1676 EnqueueClearedReferences(&cleared_references);
1677 RequestHeapTrim();
1678 timings.AddSplit("Finish");
1679
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001680 // If the GC was slow, then print timings in the log.
1681 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1682 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001683 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001684 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001685 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001686 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001687 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001688 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001689 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001690 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001691 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1692 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001693 if (VLOG_IS_ON(heap)) {
1694 timings.Dump();
1695 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001696 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001697
Mathieu Chartier0325e622012-09-05 14:22:51 -07001698 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1699 logger->Start();
1700 logger->AddLogger(timings);
1701 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001702}
1703
Ian Rogers81d425b2012-09-27 16:03:43 -07001704GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001705 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001706 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001707 bool do_wait;
1708 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001709 {
1710 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001711 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001712 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001713 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001714 if (do_wait) {
1715 // We must wait, change thread state then sleep on gc_complete_cond_;
1716 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1717 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001718 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001719 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001720 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001721 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001722 last_gc_type = last_gc_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001723 }
1724 uint64_t wait_time = NanoTime() - wait_start;
1725 if (wait_time > MsToNs(5)) {
1726 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1727 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001728 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001729 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001730 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001731}
1732
Elliott Hughesc967f782012-04-16 10:23:15 -07001733void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001734 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1735 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier0325e622012-09-05 14:22:51 -07001736 // Dump cumulative timings.
1737 LOG(INFO) << "Dumping cumulative Gc timings";
1738 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
1739 it != cumulative_timings_.end(); ++it) {
1740 it->second->Dump();
1741 }
Elliott Hughesc967f782012-04-16 10:23:15 -07001742}
1743
1744size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001745 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001746}
1747
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001748void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001749 AllocSpace* alloc_space = alloc_space_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001750 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001751 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001752 << PrettySize(GetMaxMemory());
1753 max_allowed_footprint = GetMaxMemory();
1754 }
1755 // We want to update the footprint for just the alloc space.
1756 max_allowed_footprint -= large_object_space_->GetNumBytesAllocated();
1757 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1758 if ((*it)->IsAllocSpace()) {
1759 AllocSpace* alloc_space = (*it)->AsAllocSpace();
1760 if (alloc_space != alloc_space_) {
1761 max_allowed_footprint -= alloc_space->GetNumBytesAllocated();
1762 }
1763 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001764 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001765 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001766}
1767
Ian Rogers3bb17a62012-01-27 23:56:44 -08001768// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001769static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001770// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1771// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001772static const size_t kHeapMinFree = kHeapIdealFree / 4;
1773
Carl Shapiro69759ea2011-07-21 18:13:35 -07001774void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001775 // We know what our utilization is at this moment.
1776 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1777 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
1778 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1779 target_size = num_bytes_allocated_ + kHeapIdealFree;
1780 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1781 target_size = num_bytes_allocated_ + kHeapMinFree;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001782 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001783
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001784 // Calculate when to perform the next ConcurrentGC.
1785 if (GetFreeMemory() < concurrent_min_free_) {
1786 // Not enough free memory to perform concurrent GC.
1787 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1788 } else {
1789 // Start a concurrent Gc when we get close to the target size.
1790 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001791 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001792
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001793 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001794}
1795
jeffhaoc1160702011-10-27 15:48:45 -07001796void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001797 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001798 alloc_space_->ClearGrowthLimit();
1799}
1800
Elliott Hughesadb460d2011-10-05 17:02:34 -07001801void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001802 MemberOffset reference_queue_offset,
1803 MemberOffset reference_queueNext_offset,
1804 MemberOffset reference_pendingNext_offset,
1805 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001806 reference_referent_offset_ = reference_referent_offset;
1807 reference_queue_offset_ = reference_queue_offset;
1808 reference_queueNext_offset_ = reference_queueNext_offset;
1809 reference_pendingNext_offset_ = reference_pendingNext_offset;
1810 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1811 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1812 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1813 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1814 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1815 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1816}
1817
1818Object* Heap::GetReferenceReferent(Object* reference) {
1819 DCHECK(reference != NULL);
1820 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1821 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1822}
1823
1824void Heap::ClearReferenceReferent(Object* reference) {
1825 DCHECK(reference != NULL);
1826 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1827 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1828}
1829
1830// Returns true if the reference object has not yet been enqueued.
1831bool Heap::IsEnqueuable(const Object* ref) {
1832 DCHECK(ref != NULL);
1833 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1834 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1835 return (queue != NULL) && (queue_next == NULL);
1836}
1837
1838void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1839 DCHECK(ref != NULL);
1840 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1841 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1842 EnqueuePendingReference(ref, cleared_reference_list);
1843}
1844
1845void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1846 DCHECK(ref != NULL);
1847 DCHECK(list != NULL);
1848
1849 if (*list == NULL) {
1850 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1851 *list = ref;
1852 } else {
1853 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1854 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1855 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1856 }
1857}
1858
1859Object* Heap::DequeuePendingReference(Object** list) {
1860 DCHECK(list != NULL);
1861 DCHECK(*list != NULL);
1862 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1863 Object* ref;
1864 if (*list == head) {
1865 ref = *list;
1866 *list = NULL;
1867 } else {
1868 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1869 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1870 ref = head;
1871 }
1872 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1873 return ref;
1874}
1875
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001876void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001877 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001878 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001879 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001880 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1881 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001882}
1883
1884size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001885 return num_bytes_allocated_;
1886}
1887
1888size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001889 size_t total = 0;
1890 // TODO: C++0x
1891 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1892 Space* space = *it;
1893 if (space->IsAllocSpace()) {
1894 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1895 }
1896 }
1897 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898}
1899
1900size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001901 return concurrent_start_size_;
1902}
1903
1904size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001905 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001906}
1907
1908void Heap::EnqueueClearedReferences(Object** cleared) {
1909 DCHECK(cleared != NULL);
1910 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001911 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001912 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001913 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001914 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1915 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001916 *cleared = NULL;
1917 }
1918}
1919
Ian Rogers1f539342012-10-03 21:09:42 -07001920void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001921 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001922 Runtime* runtime = Runtime::Current();
1923 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1924 !runtime->IsConcurrentGcEnabled()) {
1925 return;
1926 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001927 {
1928 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1929 if (runtime->IsShuttingDown()) {
1930 return;
1931 }
1932 }
1933 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001934 return;
1935 }
1936
1937 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001938 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001939 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1940 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001941 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1942 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001943 CHECK(!env->ExceptionCheck());
1944 requesting_gc_ = false;
1945}
1946
Ian Rogers81d425b2012-09-27 16:03:43 -07001947void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001948 {
1949 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1950 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
1951 return;
1952 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001953 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001954
Ian Rogers81d425b2012-09-27 16:03:43 -07001955 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001956 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07001957 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001958 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001959 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001960 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001961 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001962 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001963 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001964}
1965
Ian Rogers81d425b2012-09-27 16:03:43 -07001966void Heap::Trim(Thread* self) {
1967 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001968 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001969}
1970
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001971void Heap::RequestHeapTrim() {
1972 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1973 // because that only marks object heads, so a large array looks like lots of empty space. We
1974 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1975 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1976 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1977 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001978 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001979 float utilization =
1980 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1981 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1982 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1983 // heap trim occurred in the last two seconds.
1984 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001985 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001986
1987 Thread* self = Thread::Current();
1988 {
1989 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1990 Runtime* runtime = Runtime::Current();
1991 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1992 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1993 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1994 // as we don't hold the lock while requesting the trim).
1995 return;
1996 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001997 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001998 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001999 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002000 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2001 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002002 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2003 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002004 CHECK(!env->ExceptionCheck());
2005}
2006
Carl Shapiro69759ea2011-07-21 18:13:35 -07002007} // namespace art