blob: e2190ec22a47f0a406d2f635dad79496d64e3f40 [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
Mathieu Chartierd8195f12012-10-05 12:21:28 -070025#include "atomic_stack.h"
Ian Rogers5d76c432011-10-31 21:42:49 -070026#include "card_table.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070027#include "debugger.h"
Mathieu Chartiercc236d72012-07-20 10:29:05 -070028#include "heap_bitmap.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070029#include "image.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070030#include "mark_sweep.h"
Mathieu Chartierb43b7d42012-06-19 13:15:09 -070031#include "mod_union_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070032#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080033#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080034#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070035#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070036#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070037#include "sirt_ref.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "space.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),
152 min_alloc_space_size_for_sticky_gc_(4 * MB),
153 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) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800190 if (!GenerateImage(image_file_name)) {
191 LOG(FATAL) << "Failed to generate image: " << image_file_name;
192 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700193 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800194 }
195 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700196
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700197 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700198 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800199 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
200 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700201 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
202 CHECK_GT(oat_end_addr, image_space->End());
203
204 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
205 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
206 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
207 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
208 reinterpret_cast<byte*>(reserve_begin),
209 reserve_end - reserve_begin, PROT_READ));
210
Ian Rogers30fab402012-01-23 15:43:46 -0800211 if (oat_end_addr > requested_begin) {
212 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700213 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700214 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700215 }
216
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700217 // Allocate the large object space.
218 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700219 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
220 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
221
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700222 UniquePtr<AllocSpace> alloc_space(AllocSpace::Create("alloc space", initial_size, growth_limit,
223 capacity, requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700224 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700225 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700226 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700227
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700228 // Spaces are sorted in order of Begin().
229 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700230 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
231 if (spaces_.back()->IsAllocSpace()) {
232 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
233 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700234
Ian Rogers30fab402012-01-23 15:43:46 -0800235 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700236 // TODO: C++0x
237 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
238 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800239 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700240 ImageSpace* image_space = space->AsImageSpace();
241 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800242 }
243 }
244
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800245 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700246 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
247 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700248
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700249 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
250 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700251
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700252 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
253 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700254
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700255 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700256 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700257
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700258 // Max stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700259 static const size_t default_mark_stack_size = 64 * KB;
260 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
261 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
262 max_allocation_stack_size_));
263 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
264 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700265
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800266 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700267 // but we can create the heap lock now. We don't create it earlier to
268 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700269 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700270 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700271
Mathieu Chartier0325e622012-09-05 14:22:51 -0700272 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700273 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
274 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700275 std::ostringstream name;
276 name << static_cast<GcType>(i);
277 cumulative_timings_.Put(static_cast<GcType>(i),
278 new CumulativeLogger(name.str().c_str(), true));
279 }
280
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800281 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800282 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700283 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700284}
285
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700286// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700287struct SpaceSorter {
288 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700289 return a->Begin() < b->Begin();
290 }
291};
292
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700293void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700294 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700295 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700296 DCHECK(space->GetLiveBitmap() != NULL);
297 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700298 DCHECK(space->GetMarkBitmap() != NULL);
299 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800300 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700301 if (space->IsAllocSpace()) {
302 alloc_space_ = space->AsAllocSpace();
303 }
304
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700305 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
306 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700307
308 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
309 // avoid redundant marking.
310 bool seen_zygote = false, seen_alloc = false;
311 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
312 Space* space = *it;
313 if (space->IsImageSpace()) {
314 DCHECK(!seen_zygote);
315 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700316 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700317 DCHECK(!seen_alloc);
318 seen_zygote = true;
319 } else if (space->IsAllocSpace()) {
320 seen_alloc = true;
321 }
322 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800323}
324
325Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700326 // If we don't reset then the mark stack complains in it's destructor.
327 allocation_stack_->Reset();
328 live_stack_->Reset();
329
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800330 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800331 // We can't take the heap lock here because there might be a daemon thread suspended with the
332 // heap lock held. We know though that no non-daemon threads are executing, and we know that
333 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
334 // 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 -0700335 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700336 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700337 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700338}
339
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700340ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700341 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700342 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
343 if ((*it)->Contains(obj)) {
344 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700345 }
346 }
347 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
348 return NULL;
349}
350
351ImageSpace* Heap::GetImageSpace() {
352 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700353 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
354 if ((*it)->IsImageSpace()) {
355 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700356 }
357 }
358 return NULL;
359}
360
361AllocSpace* Heap::GetAllocSpace() {
362 return alloc_space_;
363}
364
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700365static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700366 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700367 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700368 size_t chunk_free_bytes = chunk_size - used_bytes;
369 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
370 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700371 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700372}
373
Ian Rogers50b35e22012-10-04 10:09:15 -0700374Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700375 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
376 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
377 strlen(ClassHelper(c).GetDescriptor()) == 0);
378 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700379
380 Object* obj = NULL;
381 size_t size = 0;
382
383 // We need to have a zygote space or else our newly allocated large object can end up in the
384 // Zygote resulting in it being prematurely freed.
385 // We can only do this for primive objects since large objects will not be within the card table
386 // range. This also means that we rely on SetClass not dirtying the object's card.
387 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700388 size = RoundUp(byte_count, kPageSize);
Ian Rogers50b35e22012-10-04 10:09:15 -0700389 obj = Allocate(self, NULL, size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700390
391 if (obj != NULL) {
392 // Make sure that our large object didn't get placed anywhere within the space interval or else
393 // it breaks the immune range.
394 DCHECK(reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
395 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
396 }
397 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700398 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700399 size = alloc_space_->AllocationSize(obj);
400
401 if (obj != NULL) {
402 // Additional verification to ensure that we did not allocate into a zygote space.
403 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
404 }
405 }
406
Mathieu Chartier037813d2012-08-23 16:44:59 -0700407 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700408 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700409
410 // Record allocation after since we want to use the atomic add for the atomic fence to guard
411 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700412 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700413
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700414 if (Dbg::IsAllocTrackingEnabled()) {
415 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700416 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700417 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700418 // We already have a request pending, no reason to start more until we update
419 // concurrent_start_bytes_.
420 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700422 SirtRef<Object> ref(self, obj);
423 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700424 }
425 VerifyObject(obj);
426
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700427 return obj;
428 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700429 int64_t total_bytes_free = GetFreeMemory();
430 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700431 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700432 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
433 if ((*it)->IsAllocSpace()) {
434 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700435 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700436 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700437
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700438 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 -0700439 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700440 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700441 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700442}
443
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700444bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700445 // Note: we deliberately don't take the lock here, and mustn't test anything that would
446 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700447 if (obj == NULL) {
448 return true;
449 }
450 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700451 return false;
452 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800453 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800454 if (spaces_[i]->Contains(obj)) {
455 return true;
456 }
457 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700458 // TODO: Find a way to check large object space without using a lock.
459 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700460}
461
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700462bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700463 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700464 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700465}
466
Elliott Hughes3e465b12011-09-02 18:26:12 -0700467#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700468void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700469 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700470 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700471 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700472 return;
473 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700474 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700475}
476#endif
477
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700478void Heap::DumpSpaces() {
479 // TODO: C++0x auto
480 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700481 ContinuousSpace* space = *it;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700482 LOG(INFO) << *space << "\n"
483 << *space->GetLiveBitmap() << "\n"
484 << *space->GetMarkBitmap();
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:
704 InstanceCounter(Class* c, bool count_assignable)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700705 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700706 : class_(c), count_assignable_(count_assignable), count_(0) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700707
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700708 }
709
710 size_t GetCount() {
711 return count_;
712 }
713
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700714 static void Callback(Object* o, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700715 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700716 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
717 }
718
719 private:
Ian Rogersb726dcb2012-09-05 08:57:23 -0700720 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700721 Class* instance_class = o->GetClass();
722 if (count_assignable_) {
723 if (instance_class == class_) {
724 ++count_;
725 }
726 } else {
727 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
728 ++count_;
729 }
730 }
731 }
732
733 Class* class_;
734 bool count_assignable_;
735 size_t count_;
736};
737
738int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700739 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700740 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700741 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700742 return counter.GetCount();
743}
744
Ian Rogers30fab402012-01-23 15:43:46 -0800745void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700746 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
747 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700748 Thread* self = Thread::Current();
749 WaitForConcurrentGcToComplete(self);
750 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700751 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
752 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700753}
754
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700755void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700756 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700757 Thread* self = Thread::Current();
758 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700759
760 // Try to see if we have any Zygote spaces.
761 if (have_zygote_space_) {
762 return;
763 }
764
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700765 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
766
767 {
768 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700769 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700770 FlushAllocStack();
771 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700772
773 // Replace the first alloc space we find with a zygote space.
774 // TODO: C++0x auto
775 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
776 if ((*it)->IsAllocSpace()) {
777 AllocSpace* zygote_space = (*it)->AsAllocSpace();
778
779 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
780 // of the remaining available heap memory.
781 alloc_space_ = zygote_space->CreateZygoteSpace();
782
783 // Change the GC retention policy of the zygote space to only collect when full.
784 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
785 AddSpace(alloc_space_);
786 have_zygote_space_ = true;
787 break;
788 }
789 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700790
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700791 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700792 // TODO: C++0x
793 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
794 it != cumulative_timings_.end(); ++it) {
795 it->second->Reset();
796 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700797}
798
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700799void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700800 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
801 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700802 allocation_stack_->Reset();
803}
804
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700805size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700806 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700807}
808
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700809void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
810 Object** limit = stack->End();
811 for (Object** it = stack->Begin(); it != limit; ++it) {
812 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700813 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700814 if (LIKELY(bitmap->HasAddress(obj))) {
815 bitmap->Set(obj);
816 } else {
817 large_objects->Set(obj);
818 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700819 }
820}
821
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700822void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
823 Object** limit = stack->End();
824 for (Object** it = stack->Begin(); it != limit; ++it) {
825 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700826 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700827 if (LIKELY(bitmap->HasAddress(obj))) {
828 bitmap->Clear(obj);
829 } else {
830 large_objects->Clear(obj);
831 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700832 }
833}
834
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700835GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700836 Thread* self = Thread::Current();
837 Locks::mutator_lock_->AssertNotHeld(self);
838 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700839
Ian Rogers120f1c72012-09-28 17:17:10 -0700840 if (self->IsHandlingStackOverflow()) {
841 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
842 }
843
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700844 // Ensure there is only one GC at a time.
845 bool start_collect = false;
846 while (!start_collect) {
847 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700848 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700849 if (!is_gc_running_) {
850 is_gc_running_ = true;
851 start_collect = true;
852 }
853 }
854 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700855 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700856 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
857 // Not doing at the moment to ensure soft references are cleared.
858 }
859 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700860 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700861
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700862 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
863 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
864 ++Thread::Current()->GetStats()->gc_for_alloc_count;
865 }
866
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700867 // We need to do partial GCs every now and then to avoid the heap growing too much and
868 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700869 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700870 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700871 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700872 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700873 sticky_gc_count_ = 0;
874 }
875
Mathieu Chartier637e3482012-08-17 10:41:32 -0700876 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700877 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700878 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700879 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700880 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700881 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700882
Ian Rogers15bf2d32012-08-28 17:33:04 -0700883 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700884 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700885 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700886 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700887 // Wake anyone who may have been waiting for the GC to complete.
888 gc_complete_cond_->Broadcast();
889 }
890 // Inform DDMS that a GC completed.
891 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700892 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700893}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700894
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700895void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
896 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700897 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700898
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700899 std::stringstream gc_type_str;
900 gc_type_str << gc_type << " ";
901
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700902 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700903 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700904 ThreadList* thread_list = Runtime::Current()->GetThreadList();
905 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700906 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700907 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700908
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700909 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700910 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700911 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700912 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700913
914 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700915 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700916
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700917 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700918 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700919 if (!VerifyHeapReferences()) {
920 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
921 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700922 timings.AddSplit("VerifyHeapReferencesPreGC");
923 }
924
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700925 // Make sure that the tables have the correct pointer for the mark sweep.
926 mod_union_table_->Init(&mark_sweep);
927 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700928
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700929 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700930 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700931
932 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
933 // TODO: Investigate using a mark stack instead of a vector.
934 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700935 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700936 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
937 card_table_->GetDirtyCards(*it, dirty_cards);
938 }
939 }
940
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700941 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700942 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700943 ContinuousSpace* space = *it;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700944 if (space->IsImageSpace()) {
945 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700946 timings.AddSplit("ClearModUnionCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700947 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
948 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700949 timings.AddSplit("ClearZygoteCards");
950 } else {
951 card_table_->ClearSpaceCards(space);
952 timings.AddSplit("ClearCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700953 }
954 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700955
Ian Rogers120f1c72012-09-28 17:17:10 -0700956 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700957 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700958 // Copy the mark bits over from the live bits, do this as early as possible or else we can
959 // accidentally un-mark roots.
960 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700961 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700962 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
963 mark_sweep.CopyMarkBits(*it);
964 }
965 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700966 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700967
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700968 // We can assume that everything from the start of the first space to the alloc space is marked.
969 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
970 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700971 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700972 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700973 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
974 mark_sweep.CopyMarkBits(*it);
975 }
976 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700977 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700978 timings.AddSplit("CopyMarkBits");
979
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700980 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
981 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700982 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700983
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700984 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
985 live_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700986
Mathieu Chartier0325e622012-09-05 14:22:51 -0700987 if (gc_type != kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700988 live_stack_->Reset();
989 }
990
Carl Shapiro58551df2011-07-24 03:09:51 -0700991 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700992 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700993
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700994 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700995 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700996
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700997 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700998
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700999 if (verify_mod_union_table_) {
1000 zygote_mod_union_table_->Update();
1001 zygote_mod_union_table_->Verify();
1002 mod_union_table_->Update();
1003 mod_union_table_->Verify();
1004 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001005
1006 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001007 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001008 live_stack_->Reset();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001009 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001010 } else {
1011 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1012 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001013 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001014
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001015 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001016 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001017 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001018
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001019 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1020 mark_sweep.SweepSystemWeaks(false);
1021 timings.AddSplit("SweepSystemWeaks");
1022
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001023 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001024 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001025 SwapBitmaps(self);
Mathieu Chartier654d3a22012-07-11 17:54:18 -07001026 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001027
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001028#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001029 // Verify that we only reach marked objects from the image space
1030 mark_sweep.VerifyImageRoots();
1031 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001032#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001033
Mathieu Chartier0325e622012-09-05 14:22:51 -07001034 if (gc_type != kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001035 mark_sweep.SweepLargeObjects(swap);
1036 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001037 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001038 } else {
1039 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001040 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001041 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001042
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001043 if (verify_system_weaks_) {
1044 mark_sweep.VerifySystemWeaks();
1045 timings.AddSplit("VerifySystemWeaks");
1046 }
1047
Elliott Hughesadb460d2011-10-05 17:02:34 -07001048 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001049 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001050 }
1051
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001052 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001053 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001054 if (!VerifyHeapReferences()) {
1055 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1056 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001057 timings.AddSplit("VerifyHeapReferencesPostGC");
1058 }
1059
Carl Shapiro58551df2011-07-24 03:09:51 -07001060 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001061 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001062
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001063 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001064 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001065
1066 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001067 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001068 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001069
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001070 // If the GC was slow, then print timings in the log.
1071 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1072 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001073 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001074 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001075 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001076 LOG(INFO) << gc_cause << " " << gc_type_str.str() << " "
Mathieu Chartier637e3482012-08-17 10:41:32 -07001077 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001078 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001079 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001080 if (VLOG_IS_ON(heap)) {
1081 timings.Dump();
1082 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001083 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001084
Mathieu Chartier0325e622012-09-05 14:22:51 -07001085 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1086 logger->Start();
1087 logger->AddLogger(timings);
1088 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001089}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001090
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001091void Heap::UpdateAndMarkModUnion(TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001092 if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001093 // Don't need to do anythign for mod union table in this case since we are only scanning dirty
1094 // cards.
1095 return;
1096 }
1097
1098 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001099 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001100 zygote_mod_union_table_->Update();
1101 timings.AddSplit("UpdateZygoteModUnionTable");
1102
1103 zygote_mod_union_table_->MarkReferences();
1104 timings.AddSplit("ZygoteMarkReferences");
1105 }
1106
1107 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1108 mod_union_table_->Update();
1109 timings.AddSplit("UpdateModUnionTable");
1110
1111 // Scans all objects in the mod-union table.
1112 mod_union_table_->MarkReferences();
1113 timings.AddSplit("MarkImageToAllocSpaceReferences");
1114}
1115
1116void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1117 Object* obj = reinterpret_cast<Object*>(arg);
1118 if (root == obj) {
1119 LOG(INFO) << "Object " << obj << " is a root";
1120 }
1121}
1122
1123class ScanVisitor {
1124 public:
1125 void operator ()(const Object* obj) const {
1126 LOG(INFO) << "Would have rescanned object " << obj;
1127 }
1128};
1129
1130class VerifyReferenceVisitor {
1131 public:
1132 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1134 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001135 : heap_(heap),
1136 failed_(failed) {
1137 }
1138
1139 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1140 // analysis.
1141 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1142 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1143 // Verify that the reference is live.
1144 if (ref != NULL && !IsLive(ref)) {
1145 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001146 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1147 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001148
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001149 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001150 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " on IsDirty = "
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001151 << (*card_addr == GC_CARD_DIRTY);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001152 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1153 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1154 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001155 void* cover_begin = card_table->AddrFromCard(card_addr);
1156 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1157 GC_CARD_SIZE);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001158 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001159 << "-" << cover_end;
1160 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1161
1162 // Print out how the object is live.
1163 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001164 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1165 }
1166
1167 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1168 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1169 }
1170
1171 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1172 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001173 }
1174
1175 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001176 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001177 }
1178
1179 // Attempt to see if the card table missed the reference.
1180 ScanVisitor scan_visitor;
1181 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1182 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + GC_CARD_SIZE, scan_visitor,
1183 IdentityFunctor());
1184
1185 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001186 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001187 MarkSweep ms(mark_stack);
1188 ms.Init();
1189 mark_stack->Reset();
1190 ms.SetFinger(reinterpret_cast<Object*>(~size_t(0)));
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001191
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001192 // All the references should end up in the mark stack.
1193 ms.ScanRoot(obj);
1194 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001195 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001196 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001197 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001198 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001199 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001200 }
1201 }
1202 mark_stack->Reset();
1203
1204 // Search to see if any of the roots reference our object.
1205 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1206 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1207 *failed_ = true;
1208 }
1209 }
1210
1211 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1212 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1213 if (bitmap != NULL) {
1214 if (bitmap->Test(obj)) {
1215 return true;
1216 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001217 } else if (heap_->GetLargeObjectsSpace()->GetLiveObjects()->Test(obj)) {
1218 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001219 } else {
1220 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001221 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001222 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001223 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001224 // At this point we need to search the allocation since things in the live stack may get swept.
1225 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1226 return true;
1227 }
1228 // Not either in the live bitmap or allocation stack, so the object must be dead.
1229 return false;
1230 }
1231
1232 private:
1233 Heap* heap_;
1234 bool* failed_;
1235};
1236
1237class VerifyObjectVisitor {
1238 public:
1239 VerifyObjectVisitor(Heap* heap)
1240 : heap_(heap),
1241 failed_(false) {
1242
1243 }
1244
1245 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001246 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001247 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1248 MarkSweep::VisitObjectReferences(obj, visitor);
1249 }
1250
1251 bool Failed() const {
1252 return failed_;
1253 }
1254
1255 private:
1256 Heap* heap_;
1257 bool failed_;
1258};
1259
1260// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001261bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001262 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001263 // Lets sort our allocation stacks so that we can efficiently binary search them.
1264 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1265 std::sort(live_stack_->Begin(), live_stack_->End());
1266 // Perform the verification.
1267 VerifyObjectVisitor visitor(this);
1268 GetLiveBitmap()->Visit(visitor);
1269 // We don't want to verify the objects in the allocation stack since they themselves may be
1270 // pointing to dead objects if they are not reachable.
1271 if (visitor.Failed()) {
1272 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001273 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001274 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001275 return true;
1276}
1277
1278class VerifyReferenceCardVisitor {
1279 public:
1280 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1281 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1282 Locks::heap_bitmap_lock_)
1283 : heap_(heap),
1284 failed_(failed) {
1285 }
1286
1287 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1288 // analysis.
1289 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1290 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
1291 if (ref != NULL) {
1292 CardTable* card_table = heap_->GetCardTable();
1293 // If the object is not dirty and it is referencing something in the live stack other than
1294 // class, then it must be on a dirty card.
1295 if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001296 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001297 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1298 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1299 LOG(ERROR) << "Object " << obj << " found in live stack";
1300 }
1301 if (heap_->GetLiveBitmap()->Test(obj)) {
1302 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1303 }
1304 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1305 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1306
1307 // Print which field of the object is dead.
1308 if (!obj->IsObjectArray()) {
1309 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1310 CHECK(klass != NULL);
1311 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1312 CHECK(fields != NULL);
1313 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1314 const Field* cur = fields->Get(i);
1315 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1316 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1317 << PrettyField(cur);
1318 break;
1319 }
1320 }
1321 } else {
1322 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1323 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1324 if (object_array->Get(i) == ref) {
1325 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1326 }
1327 }
1328 }
1329
1330 *failed_ = true;
1331 }
1332 }
1333 }
1334 }
1335
1336 private:
1337 Heap* heap_;
1338 bool* failed_;
1339};
1340
1341class VerifyLiveStackReferences {
1342 public:
1343 VerifyLiveStackReferences(Heap* heap)
1344 : heap_(heap),
1345 failed_(false) {
1346
1347 }
1348
1349 void operator ()(const Object* obj) const
1350 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1351 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1352 MarkSweep::VisitObjectReferences(obj, visitor);
1353 }
1354
1355 bool Failed() const {
1356 return failed_;
1357 }
1358
1359 private:
1360 Heap* heap_;
1361 bool failed_;
1362};
1363
1364bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001365 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001366
1367 VerifyLiveStackReferences visitor(this);
1368 GetLiveBitmap()->Visit(visitor);
1369
1370 // We can verify objects in the live stack since none of these should reference dead objects.
1371 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1372 visitor(*it);
1373 }
1374
1375 if (visitor.Failed()) {
1376 DumpSpaces();
1377 return false;
1378 }
1379 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001380}
1381
Ian Rogers81d425b2012-09-27 16:03:43 -07001382void Heap::SwapBitmaps(Thread* self) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001383 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1384 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1385 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
1386 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
Ian Rogers81d425b2012-09-27 16:03:43 -07001387 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001388 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001389 ContinuousSpace* space = *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001390 // We never allocate into zygote spaces.
1391 if (space->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1392 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1393 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1394 space->AsAllocSpace()->SwapBitmaps();
1395 }
1396 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001397
1398 large_object_space_->SwapBitmaps();
1399 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1400 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001401}
1402
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001403void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001404 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001405 allocation_stack_.reset(live_stack_.release());
1406 live_stack_.reset(temp);
1407
1408 // Sort the live stack so that we can quickly binary search it later.
1409 if (VERIFY_OBJECT_ENABLED) {
1410 std::sort(live_stack_->Begin(), live_stack_->End());
1411 }
1412}
1413
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001414void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1415 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001416 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1417 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001418 std::stringstream gc_type_str;
1419 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001420
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001421 // Suspend all threads are get exclusive access to the heap.
1422 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1423 thread_list->SuspendAll();
1424 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001425 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001426
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001427 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001428 Object* cleared_references = NULL;
1429 {
1430 MarkSweep mark_sweep(mark_stack_.get());
1431 timings.AddSplit("ctor");
1432
1433 mark_sweep.Init();
1434 timings.AddSplit("Init");
1435
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001436 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001437 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001438 if (!VerifyHeapReferences()) {
1439 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1440 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001441 timings.AddSplit("VerifyHeapReferencesPreGC");
1442 }
1443
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001444 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1445 SwapStacks();
1446
1447 // Check that all objects which reference things in the live stack are on dirty cards.
1448 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001449 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001450 // Sort the live stack so that we can quickly binary search it later.
1451 std::sort(live_stack_->Begin(), live_stack_->End());
1452 if (!VerifyMissingCardMarks()) {
1453 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1454 }
1455 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001456
1457 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1458 // TODO: Investigate using a mark stack instead of a vector.
1459 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001460 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001461 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1462 card_table_->GetDirtyCards(*it, dirty_cards);
1463 }
1464 }
1465
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001466 // Make sure that the tables have the correct pointer for the mark sweep.
1467 mod_union_table_->Init(&mark_sweep);
1468 zygote_mod_union_table_->Init(&mark_sweep);
1469
1470 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1471 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001472 ContinuousSpace* space = *it;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001473 if (space->IsImageSpace()) {
1474 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001475 timings.AddSplit("ModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001476 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1477 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001478 timings.AddSplit("ZygoteModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001479 } else {
1480 card_table_->ClearSpaceCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001481 timings.AddSplit("ClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001482 }
1483 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001484
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001485 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001486 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001487
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001488 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001489 DCHECK(!GetLiveBitmap()->Test(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001490 }
1491
Mathieu Chartier0325e622012-09-05 14:22:51 -07001492 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001493 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1494 // accidentally un-mark roots.
1495 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001496 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001497 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1498 mark_sweep.CopyMarkBits(*it);
1499 }
1500 }
1501 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001502 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1503 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001504 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001505 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001506 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1507 mark_sweep.CopyMarkBits(*it);
1508 }
1509 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001510 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001511 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001512 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1513 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001514 }
1515
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001516 // Marking roots is not necessary for sticky mark bits since we only actually require the
1517 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001518 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001519 mark_sweep.MarkRoots();
1520 timings.AddSplit("MarkRoots");
1521 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001522
1523 if (verify_mod_union_table_) {
1524 zygote_mod_union_table_->Update();
1525 zygote_mod_union_table_->Verify();
1526 mod_union_table_->Update();
1527 mod_union_table_->Verify();
1528 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001529 }
1530
1531 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001532 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001533
1534 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1535 thread_list->ResumeAll();
1536 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001537 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001538 root_end = NanoTime();
1539 timings.AddSplit("RootEnd");
1540
Ian Rogers81d425b2012-09-27 16:03:43 -07001541 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001542 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001543
1544 // Mark everything as live so that sweeping system weak works correctly for sticky mark bit
1545 // GCs.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001546 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1547 live_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001548 timings.AddSplit("MarkStackAsLive");
1549
Mathieu Chartier0325e622012-09-05 14:22:51 -07001550 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001551 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001552 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001553 } else {
1554 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001555 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001556 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557 }
1558 // Release share on mutator_lock_ and then get exclusive access.
1559 dirty_begin = NanoTime();
1560 thread_list->SuspendAll();
1561 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001562 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001563
1564 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001565 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001566
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001567 // Re-mark root set.
1568 mark_sweep.ReMarkRoots();
1569 timings.AddSplit("ReMarkRoots");
1570
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001571 if (verify_missing_card_marks_) {
1572 // Since verify missing card marks uses a sweep array to empty the allocation stack, we
1573 // need to make sure that we don't free weaks which wont get swept by SweepSystemWeaks.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001574 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1575 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001576 }
1577
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001578 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001579 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001580 timings.AddSplit("RecursiveMarkDirtyObjects");
1581 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001582
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001584 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001585
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001586 mark_sweep.ProcessReferences(clear_soft_references);
1587 timings.AddSplit("ProcessReferences");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001588
1589 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1590 mark_sweep.SweepSystemWeaks(false);
1591 timings.AddSplit("SweepSystemWeaks");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001592 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001593
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001594 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1595 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1596 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1597 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001598 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001599 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001600 SwapBitmaps(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001601 }
1602
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001603 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1604 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001605 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001606 mark_sweep.SweepArray(timings, allocation_stack_.get(), swap);
1607 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001608 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001609 // We only sweep over the live stack, and the live stack should not intersect with the
1610 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001611 UnMarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1612 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001613 timings.AddSplit("UnMarkAllocStack");
1614 }
1615
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001616 if (kIsDebugBuild) {
1617 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001618 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001619 mark_sweep.VerifyImageRoots();
1620 timings.AddSplit("VerifyImageRoots");
1621 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001622
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001623 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001624 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001625 if (!VerifyHeapReferences()) {
1626 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
1627 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001628 timings.AddSplit("VerifyHeapReferencesPostGC");
1629 }
1630
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001631 thread_list->ResumeAll();
1632 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001633 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001634
1635 {
1636 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001637 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001638 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001639 mark_sweep.SweepLargeObjects(swap);
1640 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001641 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001642 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001643 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001644 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001645 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001646 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001647 live_stack_->Reset();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648 timings.AddSplit("Sweep");
1649 }
1650
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001651 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001652 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001653 mark_sweep.VerifySystemWeaks();
1654 timings.AddSplit("VerifySystemWeaks");
1655 }
1656
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001657 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001658 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001659 }
1660
1661 GrowForUtilization();
1662 timings.AddSplit("GrowForUtilization");
1663
1664 EnqueueClearedReferences(&cleared_references);
1665 RequestHeapTrim();
1666 timings.AddSplit("Finish");
1667
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001668 // If the GC was slow, then print timings in the log.
1669 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1670 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001671 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001672 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001673 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001674 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001675 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001676 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001677 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001678 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001679 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1680 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001681 if (VLOG_IS_ON(heap)) {
1682 timings.Dump();
1683 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001684 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001685
Mathieu Chartier0325e622012-09-05 14:22:51 -07001686 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1687 logger->Start();
1688 logger->AddLogger(timings);
1689 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001690}
1691
Ian Rogers81d425b2012-09-27 16:03:43 -07001692GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001693 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001694 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001695 bool do_wait;
1696 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001697 {
1698 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001699 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001700 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001701 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001702 if (do_wait) {
1703 // We must wait, change thread state then sleep on gc_complete_cond_;
1704 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1705 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001706 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001708 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001709 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001710 last_gc_type = last_gc_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001711 }
1712 uint64_t wait_time = NanoTime() - wait_start;
1713 if (wait_time > MsToNs(5)) {
1714 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1715 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001716 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001717 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001718 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001719}
1720
Elliott Hughesc967f782012-04-16 10:23:15 -07001721void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001722 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1723 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier0325e622012-09-05 14:22:51 -07001724 // Dump cumulative timings.
1725 LOG(INFO) << "Dumping cumulative Gc timings";
1726 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
1727 it != cumulative_timings_.end(); ++it) {
1728 it->second->Dump();
1729 }
Elliott Hughesc967f782012-04-16 10:23:15 -07001730}
1731
1732size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001733 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001734}
1735
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001736void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001737 AllocSpace* alloc_space = alloc_space_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001738 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001739 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001740 << PrettySize(GetMaxMemory());
1741 max_allowed_footprint = GetMaxMemory();
1742 }
1743 // We want to update the footprint for just the alloc space.
1744 max_allowed_footprint -= large_object_space_->GetNumBytesAllocated();
1745 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1746 if ((*it)->IsAllocSpace()) {
1747 AllocSpace* alloc_space = (*it)->AsAllocSpace();
1748 if (alloc_space != alloc_space_) {
1749 max_allowed_footprint -= alloc_space->GetNumBytesAllocated();
1750 }
1751 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001752 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001753 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001754}
1755
Ian Rogers3bb17a62012-01-27 23:56:44 -08001756// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001757static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001758// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1759// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001760static const size_t kHeapMinFree = kHeapIdealFree / 4;
1761
Carl Shapiro69759ea2011-07-21 18:13:35 -07001762void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001763 // We know what our utilization is at this moment.
1764 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1765 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
1766 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1767 target_size = num_bytes_allocated_ + kHeapIdealFree;
1768 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1769 target_size = num_bytes_allocated_ + kHeapMinFree;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001770 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001771
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001772 // Calculate when to perform the next ConcurrentGC.
1773 if (GetFreeMemory() < concurrent_min_free_) {
1774 // Not enough free memory to perform concurrent GC.
1775 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1776 } else {
1777 // Start a concurrent Gc when we get close to the target size.
1778 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001779 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001780
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001781 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001782}
1783
jeffhaoc1160702011-10-27 15:48:45 -07001784void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001785 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001786 alloc_space_->ClearGrowthLimit();
1787}
1788
Elliott Hughesadb460d2011-10-05 17:02:34 -07001789void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001790 MemberOffset reference_queue_offset,
1791 MemberOffset reference_queueNext_offset,
1792 MemberOffset reference_pendingNext_offset,
1793 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001794 reference_referent_offset_ = reference_referent_offset;
1795 reference_queue_offset_ = reference_queue_offset;
1796 reference_queueNext_offset_ = reference_queueNext_offset;
1797 reference_pendingNext_offset_ = reference_pendingNext_offset;
1798 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1799 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1800 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1801 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1802 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1803 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1804}
1805
1806Object* Heap::GetReferenceReferent(Object* reference) {
1807 DCHECK(reference != NULL);
1808 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1809 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1810}
1811
1812void Heap::ClearReferenceReferent(Object* reference) {
1813 DCHECK(reference != NULL);
1814 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1815 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1816}
1817
1818// Returns true if the reference object has not yet been enqueued.
1819bool Heap::IsEnqueuable(const Object* ref) {
1820 DCHECK(ref != NULL);
1821 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1822 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1823 return (queue != NULL) && (queue_next == NULL);
1824}
1825
1826void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1827 DCHECK(ref != NULL);
1828 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1829 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1830 EnqueuePendingReference(ref, cleared_reference_list);
1831}
1832
1833void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1834 DCHECK(ref != NULL);
1835 DCHECK(list != NULL);
1836
1837 if (*list == NULL) {
1838 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1839 *list = ref;
1840 } else {
1841 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1842 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1843 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1844 }
1845}
1846
1847Object* Heap::DequeuePendingReference(Object** list) {
1848 DCHECK(list != NULL);
1849 DCHECK(*list != NULL);
1850 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1851 Object* ref;
1852 if (*list == head) {
1853 ref = *list;
1854 *list = NULL;
1855 } else {
1856 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1857 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1858 ref = head;
1859 }
1860 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1861 return ref;
1862}
1863
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001864void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001865 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001866 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001867 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001868 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1869 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001870}
1871
1872size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001873 return num_bytes_allocated_;
1874}
1875
1876size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001877 size_t total = 0;
1878 // TODO: C++0x
1879 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1880 Space* space = *it;
1881 if (space->IsAllocSpace()) {
1882 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1883 }
1884 }
1885 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001886}
1887
1888size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001889 return concurrent_start_size_;
1890}
1891
1892size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001893 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001894}
1895
1896void Heap::EnqueueClearedReferences(Object** cleared) {
1897 DCHECK(cleared != NULL);
1898 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001899 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001900 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001901 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001902 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1903 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001904 *cleared = NULL;
1905 }
1906}
1907
Ian Rogers1f539342012-10-03 21:09:42 -07001908void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001909 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001910 Runtime* runtime = Runtime::Current();
1911 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1912 !runtime->IsConcurrentGcEnabled()) {
1913 return;
1914 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001915 {
1916 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1917 if (runtime->IsShuttingDown()) {
1918 return;
1919 }
1920 }
1921 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001922 return;
1923 }
1924
1925 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001926 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001927 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1928 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001929 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1930 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001931 CHECK(!env->ExceptionCheck());
1932 requesting_gc_ = false;
1933}
1934
Ian Rogers81d425b2012-09-27 16:03:43 -07001935void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001936 {
1937 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1938 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
1939 return;
1940 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001941 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001942
Ian Rogers81d425b2012-09-27 16:03:43 -07001943 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001944 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07001945 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001946 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001947 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001948 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001949 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001950 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001951 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001952}
1953
Ian Rogers81d425b2012-09-27 16:03:43 -07001954void Heap::Trim(Thread* self) {
1955 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001956 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001957}
1958
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001959void Heap::RequestHeapTrim() {
1960 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1961 // because that only marks object heads, so a large array looks like lots of empty space. We
1962 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1963 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1964 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1965 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001966 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001967 float utilization =
1968 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1969 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1970 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1971 // heap trim occurred in the last two seconds.
1972 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001973 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001974
1975 Thread* self = Thread::Current();
1976 {
1977 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1978 Runtime* runtime = Runtime::Current();
1979 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1980 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1981 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1982 // as we don't hold the lock while requesting the trim).
1983 return;
1984 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001985 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001986 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001987 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001988 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1989 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001990 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1991 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001992 CHECK(!env->ExceptionCheck());
1993}
1994
Carl Shapiro69759ea2011-07-21 18:13:35 -07001995} // namespace art