blob: 5c6a606c188d91d1d8abe5351acbb841ebc2481d [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 Chartier637e3482012-08-17 10:41:32 -070025#include "atomic.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
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800125Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700126 const std::string& original_image_file_name, bool concurrent_gc)
127 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800128 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700129 concurrent_gc_(concurrent_gc),
130 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800131 card_marking_disabled_(false),
132 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700133 last_gc_type_(kGcTypeNone),
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700134 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700135 concurrent_start_size_(128 * KB),
136 concurrent_min_free_(256 * KB),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700137 bytes_since_last_gc_(0),
138 concurrent_gc_start_rate_(3 * MB / 2),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700139 sticky_gc_count_(0),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700140 large_object_threshold_(12 * KB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800141 num_bytes_allocated_(0),
142 num_objects_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700143 verify_missing_card_marks_(false),
144 verify_system_weaks_(false),
145 verify_pre_gc_heap_(false),
146 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700147 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700148 partial_gc_frequency_(10),
149 min_alloc_space_size_for_sticky_gc_(4 * MB),
150 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700151 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700152 try_running_gc_(false),
153 requesting_gc_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800154 reference_referent_offset_(0),
155 reference_queue_offset_(0),
156 reference_queueNext_offset_(0),
157 reference_pendingNext_offset_(0),
158 finalizer_reference_zombie_offset_(0),
159 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700160 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800161 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800162 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700163 }
164
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700165 live_bitmap_.reset(new HeapBitmap(this));
166 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700167
Ian Rogers30fab402012-01-23 15:43:46 -0800168 // Requested begin for the alloc space, to follow the mapped image and oat files
169 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800170 std::string image_file_name(original_image_file_name);
171 if (!image_file_name.empty()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700172 Space* image_space = NULL;
173
Brian Carlstrom5643b782012-02-05 12:32:53 -0800174 if (OS::FileExists(image_file_name.c_str())) {
175 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700176 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800177 } else {
178 // If the /system file didn't exist, we need to use one from the art-cache.
179 // If the cache file exists, try to open, but if it fails, regenerate.
180 // If it does not exist, generate.
181 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
182 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700183 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800184 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700185 if (image_space == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800186 if (!GenerateImage(image_file_name)) {
187 LOG(FATAL) << "Failed to generate image: " << image_file_name;
188 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700189 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800190 }
191 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700192 if (image_space == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800193 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700194 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800195
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700196 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800197 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
198 // isn't going to get in the middle
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700199 byte* oat_end_addr = GetImageSpace()->GetImageHeader().GetOatEnd();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700200 CHECK_GT(oat_end_addr, GetImageSpace()->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800201 if (oat_end_addr > requested_begin) {
202 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700203 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700204 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700205 }
206
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700207 UniquePtr<AllocSpace> alloc_space(Space::CreateAllocSpace(
208 "alloc space", initial_size, growth_limit, capacity, requested_begin));
209 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700210 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700211 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700212
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700213 // Spaces are sorted in order of Begin().
214 byte* heap_begin = spaces_.front()->Begin();
215 size_t heap_capacity = (spaces_.back()->Begin() - spaces_.front()->Begin()) + spaces_.back()->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700216
Ian Rogers30fab402012-01-23 15:43:46 -0800217 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800218 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800219 Space* space = spaces_[i];
220 if (space->IsImageSpace()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700221 space->AsImageSpace()->RecordImageAllocations(space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800222 }
223 }
224
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700225 // Allocate the large object space.
226 large_object_space_.reset(Space::CreateLargeObjectSpace("large object space"));
227 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
228 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
229
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800230 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700231 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
232 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700233
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700234 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
235 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700236
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700237 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
238 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700239
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700240 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700241 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 num_objects_allocated_ = 0;
243
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700244 // Max stack size in bytes.
245 static const size_t max_stack_size = capacity / SpaceBitmap::kAlignment * kWordSize;
246
247 // TODO: Rename MarkStack to a more generic name?
248 mark_stack_.reset(MarkStack::Create("dalvik-mark-stack", max_stack_size));
249 allocation_stack_.reset(MarkStack::Create("dalvik-allocation-stack", max_stack_size));
250 live_stack_.reset(MarkStack::Create("dalvik-live-stack", max_stack_size));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700251
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800252 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700253 // but we can create the heap lock now. We don't create it earlier to
254 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700255 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700256 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700257
Mathieu Chartier0325e622012-09-05 14:22:51 -0700258 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700259 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
260 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700261 std::ostringstream name;
262 name << static_cast<GcType>(i);
263 cumulative_timings_.Put(static_cast<GcType>(i),
264 new CumulativeLogger(name.str().c_str(), true));
265 }
266
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800267 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800268 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700269 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700270}
271
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700272// Sort spaces based on begin address
273class SpaceSorter {
274 public:
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700275 bool operator ()(const Space* a, const Space* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700276 return a->Begin() < b->Begin();
277 }
278};
279
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800280void Heap::AddSpace(Space* space) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700281 WriterMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700282 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700283 DCHECK(space->GetLiveBitmap() != NULL);
284 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700285 DCHECK(space->GetMarkBitmap() != NULL);
286 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800287 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700288 if (space->IsAllocSpace()) {
289 alloc_space_ = space->AsAllocSpace();
290 }
291
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700292 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
293 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700294
295 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
296 // avoid redundant marking.
297 bool seen_zygote = false, seen_alloc = false;
298 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
299 Space* space = *it;
300 if (space->IsImageSpace()) {
301 DCHECK(!seen_zygote);
302 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700303 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700304 DCHECK(!seen_alloc);
305 seen_zygote = true;
306 } else if (space->IsAllocSpace()) {
307 seen_alloc = true;
308 }
309 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800310}
311
312Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700313 // If we don't reset then the mark stack complains in it's destructor.
314 allocation_stack_->Reset();
315 live_stack_->Reset();
316
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800317 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800318 // We can't take the heap lock here because there might be a daemon thread suspended with the
319 // heap lock held. We know though that no non-daemon threads are executing, and we know that
320 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
321 // 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 -0700322 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700323 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700324 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700325}
326
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700327Space* Heap::FindSpaceFromObject(const Object* obj) const {
328 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700329 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
330 if ((*it)->Contains(obj)) {
331 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700332 }
333 }
334 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
335 return NULL;
336}
337
338ImageSpace* Heap::GetImageSpace() {
339 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700340 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
341 if ((*it)->IsImageSpace()) {
342 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700343 }
344 }
345 return NULL;
346}
347
348AllocSpace* Heap::GetAllocSpace() {
349 return alloc_space_;
350}
351
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700352static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
353 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
354
355 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
356 size_t chunk_free_bytes = 0;
357 if (used_bytes < chunk_size) {
358 chunk_free_bytes = chunk_size - used_bytes;
359 }
360
361 if (chunk_free_bytes > max_contiguous_allocation) {
362 max_contiguous_allocation = chunk_free_bytes;
363 }
364}
365
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700366bool Heap::CanAllocateBytes(size_t bytes) const {
367 return num_bytes_allocated_ + large_object_space_->GetNumBytesAllocated() + bytes <=
368 alloc_space_->Capacity();
369}
370
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700371Object* Heap::AllocObject(Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700372 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
373 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
374 strlen(ClassHelper(c).GetDescriptor()) == 0);
375 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700376
377 Object* obj = NULL;
378 size_t size = 0;
379
380 // We need to have a zygote space or else our newly allocated large object can end up in the
381 // Zygote resulting in it being prematurely freed.
382 // We can only do this for primive objects since large objects will not be within the card table
383 // range. This also means that we rely on SetClass not dirtying the object's card.
384 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
385 obj = Allocate(NULL, RoundUp(byte_count, kPageSize));
386 size = 0;
387
388 if (obj != NULL) {
389 // Make sure that our large object didn't get placed anywhere within the space interval or else
390 // it breaks the immune range.
391 DCHECK(reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
392 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
393 }
394 } else {
395 obj = Allocate(alloc_space_, byte_count);
396 size = alloc_space_->AllocationSize(obj);
397
398 if (obj != NULL) {
399 // Additional verification to ensure that we did not allocate into a zygote space.
400 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
401 }
402 }
403
Mathieu Chartier037813d2012-08-23 16:44:59 -0700404 if (LIKELY(obj != NULL)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700405 android_atomic_add(byte_count, reinterpret_cast<volatile int32_t*>(
406 reinterpret_cast<size_t>(&bytes_since_last_gc_)));
407
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 Chartiere0f0cb32012-08-28 11:26:00 -0700417 if (bytes_since_last_gc_ >= concurrent_gc_start_rate_ ||
418 num_bytes_allocated_ >= concurrent_start_bytes_) {
419 // We already have a request pending, no reason to start more until we update
420 // concurrent_start_bytes_.
421 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
422 bytes_since_last_gc_ = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700423 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700424 Thread* self = Thread::Current();
425 SirtRef<Object> ref(self, obj);
426 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700427 }
428 VerifyObject(obj);
429
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700430 return obj;
431 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700432 int64_t total_bytes_free = GetFreeMemory();
433 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700434 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700435 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
436 if ((*it)->IsAllocSpace()) {
437 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700438 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700439 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700440
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700441 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 -0700442 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700443 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700444 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700445}
446
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700447bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700448 // Note: we deliberately don't take the lock here, and mustn't test anything that would
449 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700450 if (obj == NULL) {
451 return true;
452 }
453 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700454 return false;
455 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800456 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800457 if (spaces_[i]->Contains(obj)) {
458 return true;
459 }
460 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700461 // TODO: Find a way to check large object space without using a lock.
462 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700463}
464
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700465bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700466 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700467 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700468}
469
Elliott Hughes3e465b12011-09-02 18:26:12 -0700470#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700472 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700473 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700474 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700475 return;
476 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700477 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700478}
479#endif
480
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700481void Heap::DumpSpaces() {
482 // TODO: C++0x auto
483 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700484 Space* space = *it;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700485 LOG(INFO) << *space << "\n"
486 << *space->GetLiveBitmap() << "\n"
487 << *space->GetMarkBitmap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700488 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700489 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700490}
491
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700492void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700493 if (!IsAligned<kObjectAlignment>(obj)) {
494 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700495 }
496
Mathieu Chartier0325e622012-09-05 14:22:51 -0700497 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700498 // Check the allocation stack / live stack.
499 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
500 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
501 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700502 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
503 if (large_object_space_->GetLiveObjects()->Test(obj)) {
504 DumpSpaces();
505 LOG(FATAL) << "Object is dead: " << obj;
506 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700507 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700508 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700509
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700510 // Ignore early dawn of the universe verifications
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700511 if (!VERIFY_OBJECT_FAST && num_objects_allocated_ > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700512 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
513 Object::ClassOffset().Int32Value();
514 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
515 if (c == NULL) {
516 LOG(FATAL) << "Null class in object: " << obj;
517 } else if (!IsAligned<kObjectAlignment>(c)) {
518 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
519 } else if (!GetLiveBitmap()->Test(c)) {
520 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
521 }
522 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
523 // Note: we don't use the accessors here as they have internal sanity checks
524 // that we don't want to run
525 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
526 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
527 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
528 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
529 CHECK_EQ(c_c, c_c_c);
530 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700531}
532
Brian Carlstrom78128a62011-09-15 17:21:19 -0700533void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700534 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700535 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700536}
537
538void Heap::VerifyHeap() {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700539 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700540 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700541}
542
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700543void Heap::RecordAllocation(size_t size, const Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700544 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700545 DCHECK_GT(size, 0u);
546 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
547 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700548 android_atomic_add(size, reinterpret_cast<volatile int32_t*>(
549 reinterpret_cast<size_t>(&num_bytes_allocated_)));
550 android_atomic_add(1, reinterpret_cast<volatile int32_t*>(
551 reinterpret_cast<size_t>(&num_objects_allocated_)));
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700552
553 if (Runtime::Current()->HasStatsEnabled()) {
554 RuntimeStats* global_stats = Runtime::Current()->GetStats();
555 RuntimeStats* thread_stats = Thread::Current()->GetStats();
556 ++global_stats->allocated_objects;
557 ++thread_stats->allocated_objects;
558 global_stats->allocated_bytes += size;
559 thread_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700560 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700561
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700562 allocation_stack_->AtomicPush(obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700563}
564
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700565void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier637e3482012-08-17 10:41:32 -0700566 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
567 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700568 DCHECK_LE(freed_objects, num_objects_allocated_);
Mathieu Chartier637e3482012-08-17 10:41:32 -0700569 android_atomic_add(-static_cast<int32_t>(freed_objects),
Mathieu Chartier556fad32012-08-20 16:13:20 -0700570 reinterpret_cast<volatile int32_t*>(
571 reinterpret_cast<size_t>(&num_objects_allocated_)));
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700572
573 DCHECK_LE(freed_bytes, num_bytes_allocated_);
Mathieu Chartier637e3482012-08-17 10:41:32 -0700574 android_atomic_add(-static_cast<int32_t>(freed_bytes),
Mathieu Chartier556fad32012-08-20 16:13:20 -0700575 reinterpret_cast<volatile int32_t*>(
576 reinterpret_cast<size_t>(&num_bytes_allocated_)));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700577
578 if (Runtime::Current()->HasStatsEnabled()) {
579 RuntimeStats* global_stats = Runtime::Current()->GetStats();
580 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700581 global_stats->freed_objects += freed_objects;
582 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700583 global_stats->freed_bytes += freed_bytes;
584 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700585 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700586}
587
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700588Object* Heap::TryToAllocate(AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier83cf3282012-09-26 17:54:27 -0700589 if (UNLIKELY(space == NULL)) {
590 if (CanAllocateBytes(alloc_size)) {
591 // TODO: This is racy, but is it worth fixing?
592 return large_object_space_->Alloc(alloc_size);
593 } else {
594 // Application ran out of heap space.
595 return NULL;
596 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700597 } else if (grow) {
598 return space->AllocWithGrowth(alloc_size);
599 } else {
600 return space->AllocWithoutGrowth(alloc_size);
601 }
602}
603
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700604Object* Heap::Allocate(AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700605 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
606 // done in the runnable state where suspension is expected.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607#ifndef NDEBUG
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700608 Thread* self = Thread::Current();
Ian Rogers81d425b2012-09-27 16:03:43 -0700609 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700610 self->AssertThreadSuspensionIsAllowable();
611#endif
Brian Carlstromb82b6872011-10-26 17:18:07 -0700612
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700613 Object* ptr = TryToAllocate(space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700614 if (ptr != NULL) {
615 return ptr;
616 }
617
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700618 // The allocation failed. If the GC is running, block until it completes, and then retry the
619 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700620#ifdef NDEBUG
621 Thread* self = Thread::Current();
622#endif
623 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700624 if (last_gc != kGcTypeNone) {
625 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700626 ptr = TryToAllocate(space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700627 if (ptr != NULL) {
628 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700629 }
630 }
631
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700632 // Loop through our different Gc types and try to Gc until we get enough free memory.
633 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
634 bool run_gc = false;
635 GcType gc_type = static_cast<GcType>(i);
636 switch (gc_type) {
637 case kGcTypeSticky: {
638 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700639 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
640 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700641 break;
642 }
643 case kGcTypePartial:
644 run_gc = have_zygote_space_;
645 break;
646 case kGcTypeFull:
647 run_gc = true;
648 break;
649 default:
650 break;
651 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700652
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700653 if (run_gc) {
654 if (Runtime::Current()->HasStatsEnabled()) {
655 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
656 ++Thread::Current()->GetStats()->gc_for_alloc_count;
657 }
658 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
659
660 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
661 GcType gc_type_ran = CollectGarbageInternal(gc_type, false);
662 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
663 i = static_cast<size_t>(gc_type_ran);
664 self->TransitionFromSuspendedToRunnable();
665
666 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700667 ptr = TryToAllocate(space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700668 if (ptr != NULL) {
669 return ptr;
670 }
671 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700672 }
673
674 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700675 // Try harder, growing the heap if necessary.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700676 ptr = TryToAllocate(space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700677 if (ptr != NULL) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700678 if (space != NULL) {
679 size_t new_footprint = space->GetFootprintLimit();
680 // OLD-TODO: may want to grow a little bit more so that the amount of
681 // free space is equal to the old free space + the
682 // utilization slop for the new allocation.
683 VLOG(gc) << "Grow alloc space (frag case) to " << PrettySize(new_footprint)
684 << " for a " << PrettySize(alloc_size) << " allocation";
685 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700686 return ptr;
687 }
688
Elliott Hughes81ff3182012-03-23 20:35:56 -0700689 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
690 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
691 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700692
Elliott Hughes418dfe72011-10-06 18:56:27 -0700693 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700694 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
695 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700696
697 if (Runtime::Current()->HasStatsEnabled()) {
698 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
699 ++Thread::Current()->GetStats()->gc_for_alloc_count;
700 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700701 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700702 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700703 CollectGarbageInternal(kGcTypeFull, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700704 self->TransitionFromSuspendedToRunnable();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700705 return TryToAllocate(space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700706}
707
Elliott Hughesbf86d042011-08-31 17:53:14 -0700708int64_t Heap::GetMaxMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700709 size_t total = 0;
710 // TODO: C++0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700711 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
712 Space* space = *it;
713 if (space->IsAllocSpace()) {
714 total += space->AsAllocSpace()->Capacity();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700715 }
716 }
717 return total;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700718}
719
720int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700721 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700722}
723
724int64_t Heap::GetFreeMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700725 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700726}
727
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700728class InstanceCounter {
729 public:
730 InstanceCounter(Class* c, bool count_assignable)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700731 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700732 : class_(c), count_assignable_(count_assignable), count_(0) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700733
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700734 }
735
736 size_t GetCount() {
737 return count_;
738 }
739
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700740 static void Callback(Object* o, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700741 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700742 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
743 }
744
745 private:
Ian Rogersb726dcb2012-09-05 08:57:23 -0700746 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700747 Class* instance_class = o->GetClass();
748 if (count_assignable_) {
749 if (instance_class == class_) {
750 ++count_;
751 }
752 } else {
753 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
754 ++count_;
755 }
756 }
757 }
758
759 Class* class_;
760 bool count_assignable_;
761 size_t count_;
762};
763
764int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700765 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700766 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700767 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700768 return counter.GetCount();
769}
770
Ian Rogers30fab402012-01-23 15:43:46 -0800771void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700772 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
773 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700774 Thread* self = Thread::Current();
775 WaitForConcurrentGcToComplete(self);
776 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700777 CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700778}
779
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700780void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700781 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700782 Thread* self = Thread::Current();
783 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700784
785 // Try to see if we have any Zygote spaces.
786 if (have_zygote_space_) {
787 return;
788 }
789
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700790 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
791
792 {
793 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700794 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700795 FlushAllocStack();
796 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700797
798 // Replace the first alloc space we find with a zygote space.
799 // TODO: C++0x auto
800 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
801 if ((*it)->IsAllocSpace()) {
802 AllocSpace* zygote_space = (*it)->AsAllocSpace();
803
804 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
805 // of the remaining available heap memory.
806 alloc_space_ = zygote_space->CreateZygoteSpace();
807
808 // Change the GC retention policy of the zygote space to only collect when full.
809 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
810 AddSpace(alloc_space_);
811 have_zygote_space_ = true;
812 break;
813 }
814 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700815
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700816 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700817 // TODO: C++0x
818 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
819 it != cumulative_timings_.end(); ++it) {
820 it->second->Reset();
821 }
822
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700823 // Reset this since we now count the ZygoteSpace in the total heap size.
824 num_bytes_allocated_ = 0;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700825}
826
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700827void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700828 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
829 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700830 allocation_stack_->Reset();
831}
832
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700833size_t Heap::GetUsedMemorySize() const {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700834 size_t total = num_bytes_allocated_ + large_object_space_->GetNumBytesAllocated();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700835 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
836 if ((*it)->IsZygoteSpace()) {
837 total += (*it)->AsAllocSpace()->Size();
838 }
839 }
840 return total;
841}
842
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700843void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700844 const size_t count = stack->Size();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700845 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700846 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700847 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700848 if (LIKELY(bitmap->HasAddress(obj))) {
849 bitmap->Set(obj);
850 } else {
851 large_objects->Set(obj);
852 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700853 }
854}
855
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700856void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700857 size_t count = stack->Size();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700858 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700859 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700860 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700861 if (LIKELY(bitmap->HasAddress(obj))) {
862 bitmap->Clear(obj);
863 } else {
864 large_objects->Clear(obj);
865 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700866 }
867}
868
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700869GcType Heap::CollectGarbageInternal(GcType gc_type, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700870 Thread* self = Thread::Current();
871 Locks::mutator_lock_->AssertNotHeld(self);
872 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700873
Ian Rogers120f1c72012-09-28 17:17:10 -0700874 if (self->IsHandlingStackOverflow()) {
875 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
876 }
877
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700878 // Ensure there is only one GC at a time.
879 bool start_collect = false;
880 while (!start_collect) {
881 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700882 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700883 if (!is_gc_running_) {
884 is_gc_running_ = true;
885 start_collect = true;
886 }
887 }
888 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700889 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700890 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
891 // Not doing at the moment to ensure soft references are cleared.
892 }
893 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700894 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700895
896 // We need to do partial GCs every now and then to avoid the heap growing too much and
897 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700898 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700899 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700900 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700901 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700902 sticky_gc_count_ = 0;
903 }
904
Mathieu Chartier637e3482012-08-17 10:41:32 -0700905 if (concurrent_gc_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700906 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700907 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700908 CollectGarbageMarkSweepPlan(self, gc_type, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700909 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700910 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700911
Ian Rogers15bf2d32012-08-28 17:33:04 -0700912 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700913 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700914 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700915 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700916 // Wake anyone who may have been waiting for the GC to complete.
917 gc_complete_cond_->Broadcast();
918 }
919 // Inform DDMS that a GC completed.
920 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700921 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700922}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700923
Ian Rogers81d425b2012-09-27 16:03:43 -0700924void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700925 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700926
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700927 std::stringstream gc_type_str;
928 gc_type_str << gc_type << " ";
929
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700930 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700931 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700932 ThreadList* thread_list = Runtime::Current()->GetThreadList();
933 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700934 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700935 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700936
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700937 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700938 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700939 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700940 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700941
942 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700943 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700944
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700945 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700946 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700947 if (!VerifyHeapReferences()) {
948 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
949 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700950 timings.AddSplit("VerifyHeapReferencesPreGC");
951 }
952
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700953 // Make sure that the tables have the correct pointer for the mark sweep.
954 mod_union_table_->Init(&mark_sweep);
955 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700956
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700957 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700958 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700959
960 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
961 // TODO: Investigate using a mark stack instead of a vector.
962 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700963 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700964 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
965 card_table_->GetDirtyCards(*it, dirty_cards);
966 }
967 }
968
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700969 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700970 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
971 Space* space = *it;
972 if (space->IsImageSpace()) {
973 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700974 timings.AddSplit("ClearModUnionCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700975 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
976 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700977 timings.AddSplit("ClearZygoteCards");
978 } else {
979 card_table_->ClearSpaceCards(space);
980 timings.AddSplit("ClearCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700981 }
982 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700983
Ian Rogers120f1c72012-09-28 17:17:10 -0700984 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700985 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700986 // Copy the mark bits over from the live bits, do this as early as possible or else we can
987 // accidentally un-mark roots.
988 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700989 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700990 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
991 mark_sweep.CopyMarkBits(*it);
992 }
993 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700994 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700995
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700996 // We can assume that everything from the start of the first space to the alloc space is marked.
997 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
998 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700999 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001000 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001001 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1002 mark_sweep.CopyMarkBits(*it);
1003 }
1004 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001005 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001006 timings.AddSplit("CopyMarkBits");
1007
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001008 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1009 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001010 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001011
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001012 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1013 live_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001014
Mathieu Chartier0325e622012-09-05 14:22:51 -07001015 if (gc_type != kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001016 live_stack_->Reset();
1017 }
1018
Carl Shapiro58551df2011-07-24 03:09:51 -07001019 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001020 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001021
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001022 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -07001023 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -07001024
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001025 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001026
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001027 if (verify_mod_union_table_) {
1028 zygote_mod_union_table_->Update();
1029 zygote_mod_union_table_->Verify();
1030 mod_union_table_->Update();
1031 mod_union_table_->Verify();
1032 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001033
1034 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001035 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001036 live_stack_->Reset();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001037 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001038 } else {
1039 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1040 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001041 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001042
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001043 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001044 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001045 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001046
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001047 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1048 mark_sweep.SweepSystemWeaks(false);
1049 timings.AddSplit("SweepSystemWeaks");
1050
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001051 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001052 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001053 SwapBitmaps(self);
Mathieu Chartier654d3a22012-07-11 17:54:18 -07001054 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001055
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001056#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001057 // Verify that we only reach marked objects from the image space
1058 mark_sweep.VerifyImageRoots();
1059 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001060#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001061
Mathieu Chartier0325e622012-09-05 14:22:51 -07001062 if (gc_type != kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001063 mark_sweep.SweepLargeObjects(swap);
1064 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001065 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001066 } else {
1067 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001068 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001069 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001070
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001071 if (verify_system_weaks_) {
1072 mark_sweep.VerifySystemWeaks();
1073 timings.AddSplit("VerifySystemWeaks");
1074 }
1075
Elliott Hughesadb460d2011-10-05 17:02:34 -07001076 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001077 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001078 }
1079
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001080 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001081 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001082 if (!VerifyHeapReferences()) {
1083 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1084 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001085 timings.AddSplit("VerifyHeapReferencesPostGC");
1086 }
1087
Carl Shapiro58551df2011-07-24 03:09:51 -07001088 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001089 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001090
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001091 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001093
1094 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001095 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001096 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001097
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001098 // If the GC was slow, then print timings in the log.
1099 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1100 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001101 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001102 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001103 const size_t total_memory = GetTotalMemory();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001104 LOG(INFO) << gc_type_str.str() << " "
Mathieu Chartier637e3482012-08-17 10:41:32 -07001105 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001106 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001107 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001108 if (VLOG_IS_ON(heap)) {
1109 timings.Dump();
1110 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001111 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001112
Mathieu Chartier0325e622012-09-05 14:22:51 -07001113 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1114 logger->Start();
1115 logger->AddLogger(timings);
1116 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001117}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001118
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001119void Heap::UpdateAndMarkModUnion(TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001120 if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001121 // Don't need to do anythign for mod union table in this case since we are only scanning dirty
1122 // cards.
1123 return;
1124 }
1125
1126 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001127 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001128 zygote_mod_union_table_->Update();
1129 timings.AddSplit("UpdateZygoteModUnionTable");
1130
1131 zygote_mod_union_table_->MarkReferences();
1132 timings.AddSplit("ZygoteMarkReferences");
1133 }
1134
1135 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1136 mod_union_table_->Update();
1137 timings.AddSplit("UpdateModUnionTable");
1138
1139 // Scans all objects in the mod-union table.
1140 mod_union_table_->MarkReferences();
1141 timings.AddSplit("MarkImageToAllocSpaceReferences");
1142}
1143
1144void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1145 Object* obj = reinterpret_cast<Object*>(arg);
1146 if (root == obj) {
1147 LOG(INFO) << "Object " << obj << " is a root";
1148 }
1149}
1150
1151class ScanVisitor {
1152 public:
1153 void operator ()(const Object* obj) const {
1154 LOG(INFO) << "Would have rescanned object " << obj;
1155 }
1156};
1157
1158class VerifyReferenceVisitor {
1159 public:
1160 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001161 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1162 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001163 : heap_(heap),
1164 failed_(failed) {
1165 }
1166
1167 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1168 // analysis.
1169 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1170 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1171 // Verify that the reference is live.
1172 if (ref != NULL && !IsLive(ref)) {
1173 CardTable* card_table = heap_->GetCardTable();
1174 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1175 MarkStack* live_stack = heap_->live_stack_.get();
1176
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001177 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001178 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " on IsDirty = "
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001179 << (*card_addr == GC_CARD_DIRTY);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001180 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1181 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1182 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001183 void* cover_begin = card_table->AddrFromCard(card_addr);
1184 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1185 GC_CARD_SIZE);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001186 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001187 << "-" << cover_end;
1188 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1189
1190 // Print out how the object is live.
1191 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001192 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1193 }
1194
1195 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1196 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1197 }
1198
1199 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1200 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001201 }
1202
1203 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001204 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001205 }
1206
1207 // Attempt to see if the card table missed the reference.
1208 ScanVisitor scan_visitor;
1209 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1210 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + GC_CARD_SIZE, scan_visitor,
1211 IdentityFunctor());
1212
1213 // Try and see if a mark sweep collector scans the reference.
1214 MarkStack* mark_stack = heap_->mark_stack_.get();
1215 MarkSweep ms(mark_stack);
1216 ms.Init();
1217 mark_stack->Reset();
1218 ms.SetFinger(reinterpret_cast<Object*>(~size_t(0)));
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001219
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001220 // All the references should end up in the mark stack.
1221 ms.ScanRoot(obj);
1222 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001223 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001224 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001225 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001226 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001227 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001228 }
1229 }
1230 mark_stack->Reset();
1231
1232 // Search to see if any of the roots reference our object.
1233 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1234 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1235 *failed_ = true;
1236 }
1237 }
1238
1239 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1240 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1241 if (bitmap != NULL) {
1242 if (bitmap->Test(obj)) {
1243 return true;
1244 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001245 } else if (heap_->GetLargeObjectsSpace()->GetLiveObjects()->Test(obj)) {
1246 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001247 } else {
1248 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001249 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001250 }
1251 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1252 // At this point we need to search the allocation since things in the live stack may get swept.
1253 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1254 return true;
1255 }
1256 // Not either in the live bitmap or allocation stack, so the object must be dead.
1257 return false;
1258 }
1259
1260 private:
1261 Heap* heap_;
1262 bool* failed_;
1263};
1264
1265class VerifyObjectVisitor {
1266 public:
1267 VerifyObjectVisitor(Heap* heap)
1268 : heap_(heap),
1269 failed_(false) {
1270
1271 }
1272
1273 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001274 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001275 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1276 MarkSweep::VisitObjectReferences(obj, visitor);
1277 }
1278
1279 bool Failed() const {
1280 return failed_;
1281 }
1282
1283 private:
1284 Heap* heap_;
1285 bool failed_;
1286};
1287
1288// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001289bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001290 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001291 // Lets sort our allocation stacks so that we can efficiently binary search them.
1292 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1293 std::sort(live_stack_->Begin(), live_stack_->End());
1294 // Perform the verification.
1295 VerifyObjectVisitor visitor(this);
1296 GetLiveBitmap()->Visit(visitor);
1297 // We don't want to verify the objects in the allocation stack since they themselves may be
1298 // pointing to dead objects if they are not reachable.
1299 if (visitor.Failed()) {
1300 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001301 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001302 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001303 return true;
1304}
1305
1306class VerifyReferenceCardVisitor {
1307 public:
1308 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1309 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1310 Locks::heap_bitmap_lock_)
1311 : heap_(heap),
1312 failed_(failed) {
1313 }
1314
1315 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1316 // analysis.
1317 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1318 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
1319 if (ref != NULL) {
1320 CardTable* card_table = heap_->GetCardTable();
1321 // If the object is not dirty and it is referencing something in the live stack other than
1322 // class, then it must be on a dirty card.
1323 if (!card_table->IsDirty(obj)) {
1324 MarkStack* live_stack = heap_->live_stack_.get();
1325 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1326 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1327 LOG(ERROR) << "Object " << obj << " found in live stack";
1328 }
1329 if (heap_->GetLiveBitmap()->Test(obj)) {
1330 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1331 }
1332 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1333 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1334
1335 // Print which field of the object is dead.
1336 if (!obj->IsObjectArray()) {
1337 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1338 CHECK(klass != NULL);
1339 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1340 CHECK(fields != NULL);
1341 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1342 const Field* cur = fields->Get(i);
1343 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1344 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1345 << PrettyField(cur);
1346 break;
1347 }
1348 }
1349 } else {
1350 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1351 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1352 if (object_array->Get(i) == ref) {
1353 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1354 }
1355 }
1356 }
1357
1358 *failed_ = true;
1359 }
1360 }
1361 }
1362 }
1363
1364 private:
1365 Heap* heap_;
1366 bool* failed_;
1367};
1368
1369class VerifyLiveStackReferences {
1370 public:
1371 VerifyLiveStackReferences(Heap* heap)
1372 : heap_(heap),
1373 failed_(false) {
1374
1375 }
1376
1377 void operator ()(const Object* obj) const
1378 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1379 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1380 MarkSweep::VisitObjectReferences(obj, visitor);
1381 }
1382
1383 bool Failed() const {
1384 return failed_;
1385 }
1386
1387 private:
1388 Heap* heap_;
1389 bool failed_;
1390};
1391
1392bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001393 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001394
1395 VerifyLiveStackReferences visitor(this);
1396 GetLiveBitmap()->Visit(visitor);
1397
1398 // We can verify objects in the live stack since none of these should reference dead objects.
1399 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1400 visitor(*it);
1401 }
1402
1403 if (visitor.Failed()) {
1404 DumpSpaces();
1405 return false;
1406 }
1407 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001408}
1409
Ian Rogers81d425b2012-09-27 16:03:43 -07001410void Heap::SwapBitmaps(Thread* self) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001411 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1412 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1413 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
1414 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
Ian Rogers81d425b2012-09-27 16:03:43 -07001415 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001416 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1417 Space* space = *it;
1418 // We never allocate into zygote spaces.
1419 if (space->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1420 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1421 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1422 space->AsAllocSpace()->SwapBitmaps();
1423 }
1424 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001425
1426 large_object_space_->SwapBitmaps();
1427 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1428 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001429}
1430
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001431void Heap::SwapStacks() {
1432 MarkStack* temp = allocation_stack_.release();
1433 allocation_stack_.reset(live_stack_.release());
1434 live_stack_.reset(temp);
1435
1436 // Sort the live stack so that we can quickly binary search it later.
1437 if (VERIFY_OBJECT_ENABLED) {
1438 std::sort(live_stack_->Begin(), live_stack_->End());
1439 }
1440}
1441
Ian Rogers81d425b2012-09-27 16:03:43 -07001442void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001443 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1444 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001445 std::stringstream gc_type_str;
1446 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001447
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001448 // Suspend all threads are get exclusive access to the heap.
1449 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1450 thread_list->SuspendAll();
1451 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001452 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001453
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001454 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001455 Object* cleared_references = NULL;
1456 {
1457 MarkSweep mark_sweep(mark_stack_.get());
1458 timings.AddSplit("ctor");
1459
1460 mark_sweep.Init();
1461 timings.AddSplit("Init");
1462
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001463 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001464 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001465 if (!VerifyHeapReferences()) {
1466 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1467 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001468 timings.AddSplit("VerifyHeapReferencesPreGC");
1469 }
1470
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001471 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1472 SwapStacks();
1473
1474 // Check that all objects which reference things in the live stack are on dirty cards.
1475 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001476 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001477 // Sort the live stack so that we can quickly binary search it later.
1478 std::sort(live_stack_->Begin(), live_stack_->End());
1479 if (!VerifyMissingCardMarks()) {
1480 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1481 }
1482 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001483
1484 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1485 // TODO: Investigate using a mark stack instead of a vector.
1486 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001487 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001488 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1489 card_table_->GetDirtyCards(*it, dirty_cards);
1490 }
1491 }
1492
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001493 // Make sure that the tables have the correct pointer for the mark sweep.
1494 mod_union_table_->Init(&mark_sweep);
1495 zygote_mod_union_table_->Init(&mark_sweep);
1496
1497 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1498 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1499 Space* space = *it;
1500 if (space->IsImageSpace()) {
1501 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001502 timings.AddSplit("ModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001503 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1504 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001505 timings.AddSplit("ZygoteModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001506 } else {
1507 card_table_->ClearSpaceCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001508 timings.AddSplit("ClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001509 }
1510 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001511
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001512 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001513 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001514
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001515 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1516 CHECK(!GetLiveBitmap()->Test(*it));
1517 }
1518
Mathieu Chartier0325e622012-09-05 14:22:51 -07001519 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001520 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1521 // accidentally un-mark roots.
1522 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001523 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001524 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1525 mark_sweep.CopyMarkBits(*it);
1526 }
1527 }
1528 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001529 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1530 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001531 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001532 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001533 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1534 mark_sweep.CopyMarkBits(*it);
1535 }
1536 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001537 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001538 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001539 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1540 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001541 }
1542
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001543 // Marking roots is not necessary for sticky mark bits since we only actually require the
1544 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001545 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001546 mark_sweep.MarkRoots();
1547 timings.AddSplit("MarkRoots");
1548 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001549
1550 if (verify_mod_union_table_) {
1551 zygote_mod_union_table_->Update();
1552 zygote_mod_union_table_->Verify();
1553 mod_union_table_->Update();
1554 mod_union_table_->Verify();
1555 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556 }
1557
1558 // Roots are marked on the bitmap and the mark_stack is empty.
1559 DCHECK(mark_sweep.IsMarkStackEmpty());
1560
1561 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1562 thread_list->ResumeAll();
1563 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001564 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001565 root_end = NanoTime();
1566 timings.AddSplit("RootEnd");
1567
Ian Rogers81d425b2012-09-27 16:03:43 -07001568 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001569 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001570
1571 // Mark everything as live so that sweeping system weak works correctly for sticky mark bit
1572 // GCs.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001573 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1574 live_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001575 timings.AddSplit("MarkStackAsLive");
1576
Mathieu Chartier0325e622012-09-05 14:22:51 -07001577 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001578 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001579 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001580 } else {
1581 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001582 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001583 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001584 }
1585 // Release share on mutator_lock_ and then get exclusive access.
1586 dirty_begin = NanoTime();
1587 thread_list->SuspendAll();
1588 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001589 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001590
1591 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001592 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001593
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001594 // Re-mark root set.
1595 mark_sweep.ReMarkRoots();
1596 timings.AddSplit("ReMarkRoots");
1597
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001598 if (verify_missing_card_marks_) {
1599 // Since verify missing card marks uses a sweep array to empty the allocation stack, we
1600 // need to make sure that we don't free weaks which wont get swept by SweepSystemWeaks.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001601 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1602 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001603 }
1604
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001605 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001606 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001607 timings.AddSplit("RecursiveMarkDirtyObjects");
1608 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001609
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001610 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001611 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001612
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001613 mark_sweep.ProcessReferences(clear_soft_references);
1614 timings.AddSplit("ProcessReferences");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001615
1616 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1617 mark_sweep.SweepSystemWeaks(false);
1618 timings.AddSplit("SweepSystemWeaks");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001619 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001620
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001621 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1622 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1623 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1624 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001625 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001626 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001627 SwapBitmaps(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001628 }
1629
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001630 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1631 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001632 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001633 mark_sweep.SweepArray(timings, allocation_stack_.get(), swap);
1634 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001635 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001636 // We only sweep over the live stack, and the live stack should not intersect with the
1637 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001638 UnMarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1639 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001640 timings.AddSplit("UnMarkAllocStack");
1641 }
1642
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001643 if (kIsDebugBuild) {
1644 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001645 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001646 mark_sweep.VerifyImageRoots();
1647 timings.AddSplit("VerifyImageRoots");
1648 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001649
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001650 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001651 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001652 if (!VerifyHeapReferences()) {
1653 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
1654 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001655 timings.AddSplit("VerifyHeapReferencesPostGC");
1656 }
1657
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001658 thread_list->ResumeAll();
1659 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001660 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001661
1662 {
1663 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Ian Rogers81d425b2012-09-27 16:03:43 -07001664 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001665 if (gc_type != kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001666 mark_sweep.SweepLargeObjects(swap);
1667 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001668 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001669 } else {
1670 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001671 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001672 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001673 live_stack_->Reset();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001674 timings.AddSplit("Sweep");
1675 }
1676
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001677 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001678 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001679 mark_sweep.VerifySystemWeaks();
1680 timings.AddSplit("VerifySystemWeaks");
1681 }
1682
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001683 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001684 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001685 }
1686
1687 GrowForUtilization();
1688 timings.AddSplit("GrowForUtilization");
1689
1690 EnqueueClearedReferences(&cleared_references);
1691 RequestHeapTrim();
1692 timings.AddSplit("Finish");
1693
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001694 // If the GC was slow, then print timings in the log.
1695 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1696 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001697 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001698 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001699 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001700 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001701 const size_t total_memory = GetTotalMemory();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001702 LOG(INFO) << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001703 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001704 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001705 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1706 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001707 if (VLOG_IS_ON(heap)) {
1708 timings.Dump();
1709 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001710 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001711
Mathieu Chartier0325e622012-09-05 14:22:51 -07001712 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1713 logger->Start();
1714 logger->AddLogger(timings);
1715 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001716}
1717
Ian Rogers81d425b2012-09-27 16:03:43 -07001718GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001719 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001720 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001721 bool do_wait;
1722 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001723 {
1724 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001725 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001726 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001727 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001728 if (do_wait) {
1729 // We must wait, change thread state then sleep on gc_complete_cond_;
1730 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1731 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001732 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001733 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001734 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001735 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001736 last_gc_type = last_gc_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001737 }
1738 uint64_t wait_time = NanoTime() - wait_start;
1739 if (wait_time > MsToNs(5)) {
1740 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1741 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001742 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001743 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001744 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001745}
1746
Elliott Hughesc967f782012-04-16 10:23:15 -07001747void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001748 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(num_bytes_allocated_) << "/"
1749 << PrettySize(GetTotalMemory()) << "; " << num_objects_allocated_ << " objects\n";
Mathieu Chartier0325e622012-09-05 14:22:51 -07001750 // Dump cumulative timings.
1751 LOG(INFO) << "Dumping cumulative Gc timings";
1752 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
1753 it != cumulative_timings_.end(); ++it) {
1754 it->second->Dump();
1755 }
Elliott Hughesc967f782012-04-16 10:23:15 -07001756}
1757
1758size_t Heap::GetPercentFree() {
1759 size_t total = GetTotalMemory();
1760 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
1761}
1762
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001763void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001764 AllocSpace* alloc_space = alloc_space_;
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001765 size_t alloc_space_capacity = alloc_space->Capacity();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001766 alloc_space_capacity -= large_object_space_->GetNumBytesAllocated();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001767 if (max_allowed_footprint > alloc_space_capacity) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001768 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
1769 << PrettySize(alloc_space_capacity);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001770 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001771 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001772 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001773}
1774
Ian Rogers3bb17a62012-01-27 23:56:44 -08001775// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001776static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001777// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1778// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001779static const size_t kHeapMinFree = kHeapIdealFree / 4;
1780
Carl Shapiro69759ea2011-07-21 18:13:35 -07001781void Heap::GrowForUtilization() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001782 size_t target_size;
1783 bool use_footprint_limit = false;
1784 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001785 // We know what our utilization is at this moment.
1786 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1787 target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001788
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001789 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1790 target_size = num_bytes_allocated_ + kHeapIdealFree;
1791 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1792 target_size = num_bytes_allocated_ + kHeapMinFree;
1793 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001794
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001795 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001796 if (GetTotalMemory() - GetUsedMemorySize() < concurrent_min_free_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001797 // Not enough free memory to perform concurrent GC.
1798 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1799 } else {
1800 // Compute below to avoid holding both the statistics and the alloc space lock
1801 use_footprint_limit = true;
1802 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001803 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001804
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001805 if (use_footprint_limit) {
1806 size_t foot_print_limit = alloc_space_->GetFootprintLimit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001807 concurrent_start_bytes_ = foot_print_limit - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001808 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001809 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001810}
1811
jeffhaoc1160702011-10-27 15:48:45 -07001812void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001813 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001814 alloc_space_->ClearGrowthLimit();
1815}
1816
Elliott Hughesadb460d2011-10-05 17:02:34 -07001817void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001818 MemberOffset reference_queue_offset,
1819 MemberOffset reference_queueNext_offset,
1820 MemberOffset reference_pendingNext_offset,
1821 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001822 reference_referent_offset_ = reference_referent_offset;
1823 reference_queue_offset_ = reference_queue_offset;
1824 reference_queueNext_offset_ = reference_queueNext_offset;
1825 reference_pendingNext_offset_ = reference_pendingNext_offset;
1826 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1827 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1828 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1829 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1830 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1831 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1832}
1833
1834Object* Heap::GetReferenceReferent(Object* reference) {
1835 DCHECK(reference != NULL);
1836 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1837 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1838}
1839
1840void Heap::ClearReferenceReferent(Object* reference) {
1841 DCHECK(reference != NULL);
1842 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1843 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1844}
1845
1846// Returns true if the reference object has not yet been enqueued.
1847bool Heap::IsEnqueuable(const Object* ref) {
1848 DCHECK(ref != NULL);
1849 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1850 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1851 return (queue != NULL) && (queue_next == NULL);
1852}
1853
1854void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1855 DCHECK(ref != NULL);
1856 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1857 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1858 EnqueuePendingReference(ref, cleared_reference_list);
1859}
1860
1861void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1862 DCHECK(ref != NULL);
1863 DCHECK(list != NULL);
1864
1865 if (*list == NULL) {
1866 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1867 *list = ref;
1868 } else {
1869 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1870 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1871 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1872 }
1873}
1874
1875Object* Heap::DequeuePendingReference(Object** list) {
1876 DCHECK(list != NULL);
1877 DCHECK(*list != NULL);
1878 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1879 Object* ref;
1880 if (*list == head) {
1881 ref = *list;
1882 *list = NULL;
1883 } else {
1884 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1885 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1886 ref = head;
1887 }
1888 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1889 return ref;
1890}
1891
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001892void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001893 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001894 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001895 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001896 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1897 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898}
1899
1900size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001901 return num_bytes_allocated_;
1902}
1903
1904size_t Heap::GetObjectsAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001905 return num_objects_allocated_;
1906}
1907
1908size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001909 return concurrent_start_size_;
1910}
1911
1912size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001913 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001914}
1915
1916void Heap::EnqueueClearedReferences(Object** cleared) {
1917 DCHECK(cleared != NULL);
1918 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001919 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001920 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001921 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001922 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1923 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001924 *cleared = NULL;
1925 }
1926}
1927
Ian Rogers1f539342012-10-03 21:09:42 -07001928void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001929 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001930 Runtime* runtime = Runtime::Current();
1931 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1932 !runtime->IsConcurrentGcEnabled()) {
1933 return;
1934 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001935 {
1936 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1937 if (runtime->IsShuttingDown()) {
1938 return;
1939 }
1940 }
1941 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001942 return;
1943 }
1944
1945 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001946 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001947 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1948 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001949 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1950 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001951 CHECK(!env->ExceptionCheck());
1952 requesting_gc_ = false;
1953}
1954
Ian Rogers81d425b2012-09-27 16:03:43 -07001955void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001956 {
1957 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1958 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
1959 return;
1960 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001961 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001962
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001963 // TODO: We shouldn't need a WaitForConcurrentGcToComplete here since only
1964 // concurrent GC resumes threads before the GC is completed and this function
1965 // is only called within the GC daemon thread.
Ian Rogers81d425b2012-09-27 16:03:43 -07001966 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001967 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07001968 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001969 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001970 CollectGarbageInternal(kGcTypeSticky, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001971 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001972 CollectGarbageInternal(kGcTypePartial, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001973 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001974 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001975}
1976
Ian Rogers81d425b2012-09-27 16:03:43 -07001977void Heap::Trim(Thread* self) {
1978 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001979 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001980}
1981
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001982void Heap::RequestHeapTrim() {
1983 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1984 // because that only marks object heads, so a large array looks like lots of empty space. We
1985 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1986 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1987 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1988 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001989 uint64_t ms_time = NsToMs(NanoTime());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001990 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001991 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
1992 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1993 // Don't bother trimming the heap if it's more than 75% utilized, or if a
1994 // heap trim occurred in the last two seconds.
1995 return;
1996 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001997 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001998
1999 Thread* self = Thread::Current();
2000 {
2001 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2002 Runtime* runtime = Runtime::Current();
2003 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2004 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2005 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2006 // as we don't hold the lock while requesting the trim).
2007 return;
2008 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002009 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002010 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002011 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002012 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2013 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002014 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2015 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002016 CHECK(!env->ExceptionCheck());
2017}
2018
Carl Shapiro69759ea2011-07-21 18:13:35 -07002019} // namespace art