blob: 3ab6419f6a91668a7176d4a790bd731b76a825fa [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"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070037#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070038#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070039#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070040#include "timing_logger.h"
41#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070042#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070043
44namespace art {
45
Elliott Hughesae80b492012-04-24 10:43:17 -070046static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080047 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080048 std::vector<std::string> boot_class_path;
49 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070050 if (boot_class_path.empty()) {
51 LOG(FATAL) << "Failed to generate image because no boot class path specified";
52 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080053
54 std::vector<char*> arg_vector;
55
56 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070057 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080058 const char* dex2oat = dex2oat_string.c_str();
59 arg_vector.push_back(strdup(dex2oat));
60
61 std::string image_option_string("--image=");
62 image_option_string += image_file_name;
63 const char* image_option = image_option_string.c_str();
64 arg_vector.push_back(strdup(image_option));
65
66 arg_vector.push_back(strdup("--runtime-arg"));
67 arg_vector.push_back(strdup("-Xms64m"));
68
69 arg_vector.push_back(strdup("--runtime-arg"));
70 arg_vector.push_back(strdup("-Xmx64m"));
71
72 for (size_t i = 0; i < boot_class_path.size(); i++) {
73 std::string dex_file_option_string("--dex-file=");
74 dex_file_option_string += boot_class_path[i];
75 const char* dex_file_option = dex_file_option_string.c_str();
76 arg_vector.push_back(strdup(dex_file_option));
77 }
78
79 std::string oat_file_option_string("--oat-file=");
80 oat_file_option_string += image_file_name;
81 oat_file_option_string.erase(oat_file_option_string.size() - 3);
82 oat_file_option_string += "oat";
83 const char* oat_file_option = oat_file_option_string.c_str();
84 arg_vector.push_back(strdup(oat_file_option));
85
86 arg_vector.push_back(strdup("--base=0x60000000"));
87
Elliott Hughes48436bb2012-02-07 15:23:28 -080088 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080089 LOG(INFO) << command_line;
90
Elliott Hughes48436bb2012-02-07 15:23:28 -080091 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -080092 char** argv = &arg_vector[0];
93
94 // fork and exec dex2oat
95 pid_t pid = fork();
96 if (pid == 0) {
97 // no allocation allowed between fork and exec
98
99 // change process groups, so we don't get reaped by ProcessManager
100 setpgid(0, 0);
101
102 execv(dex2oat, argv);
103
104 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
105 return false;
106 } else {
107 STLDeleteElements(&arg_vector);
108
109 // wait for dex2oat to finish
110 int status;
111 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
112 if (got_pid != pid) {
113 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
114 return false;
115 }
116 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
117 LOG(ERROR) << dex2oat << " failed: " << command_line;
118 return false;
119 }
120 }
121 return true;
122}
123
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800124Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700125 const std::string& original_image_file_name, bool concurrent_gc)
126 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800127 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700128 concurrent_gc_(concurrent_gc),
129 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800130 card_marking_disabled_(false),
131 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700132 last_gc_type_(kGcTypeNone),
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700133 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700134 concurrent_start_size_(128 * KB),
135 concurrent_min_free_(256 * KB),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700136 bytes_since_last_gc_(0),
137 concurrent_gc_start_rate_(3 * MB / 2),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700138 sticky_gc_count_(0),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700139 large_object_threshold_(12 * KB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800140 num_bytes_allocated_(0),
141 num_objects_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700142 verify_missing_card_marks_(false),
143 verify_system_weaks_(false),
144 verify_pre_gc_heap_(false),
145 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700146 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700147 partial_gc_frequency_(10),
148 min_alloc_space_size_for_sticky_gc_(4 * MB),
149 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700150 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700151 try_running_gc_(false),
152 requesting_gc_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800153 reference_referent_offset_(0),
154 reference_queue_offset_(0),
155 reference_queueNext_offset_(0),
156 reference_pendingNext_offset_(0),
157 finalizer_reference_zombie_offset_(0),
158 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700159 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800160 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800161 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700162 }
163
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700164 live_bitmap_.reset(new HeapBitmap(this));
165 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700166
Ian Rogers30fab402012-01-23 15:43:46 -0800167 // Requested begin for the alloc space, to follow the mapped image and oat files
168 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800169 std::string image_file_name(original_image_file_name);
170 if (!image_file_name.empty()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700171 Space* image_space = NULL;
172
Brian Carlstrom5643b782012-02-05 12:32:53 -0800173 if (OS::FileExists(image_file_name.c_str())) {
174 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700175 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800176 } else {
177 // If the /system file didn't exist, we need to use one from the art-cache.
178 // If the cache file exists, try to open, but if it fails, regenerate.
179 // If it does not exist, generate.
180 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
181 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700182 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800183 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700184 if (image_space == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800185 if (!GenerateImage(image_file_name)) {
186 LOG(FATAL) << "Failed to generate image: " << image_file_name;
187 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700188 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800189 }
190 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700191 if (image_space == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800192 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700193 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800194
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700195 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800196 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
197 // isn't going to get in the middle
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700198 byte* oat_end_addr = GetImageSpace()->GetImageHeader().GetOatEnd();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700199 CHECK_GT(oat_end_addr, GetImageSpace()->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800200 if (oat_end_addr > requested_begin) {
201 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700202 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700203 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700204 }
205
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700206 UniquePtr<AllocSpace> alloc_space(Space::CreateAllocSpace(
207 "alloc space", initial_size, growth_limit, capacity, requested_begin));
208 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700209 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700210 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700211
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700212 // Spaces are sorted in order of Begin().
213 byte* heap_begin = spaces_.front()->Begin();
214 size_t heap_capacity = (spaces_.back()->Begin() - spaces_.front()->Begin()) + spaces_.back()->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700215
Ian Rogers30fab402012-01-23 15:43:46 -0800216 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800217 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800218 Space* space = spaces_[i];
219 if (space->IsImageSpace()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700220 space->AsImageSpace()->RecordImageAllocations(space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800221 }
222 }
223
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700224 // Allocate the large object space.
225 large_object_space_.reset(Space::CreateLargeObjectSpace("large object space"));
226 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
227 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
228
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800229 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700230 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
231 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700232
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700233 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
234 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700235
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700236 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
237 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700238
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700239 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700240 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700241 num_objects_allocated_ = 0;
242
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700243 // Max stack size in bytes.
244 static const size_t max_stack_size = capacity / SpaceBitmap::kAlignment * kWordSize;
245
246 // TODO: Rename MarkStack to a more generic name?
247 mark_stack_.reset(MarkStack::Create("dalvik-mark-stack", max_stack_size));
248 allocation_stack_.reset(MarkStack::Create("dalvik-allocation-stack", max_stack_size));
249 live_stack_.reset(MarkStack::Create("dalvik-live-stack", max_stack_size));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700250
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800251 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700252 // but we can create the heap lock now. We don't create it earlier to
253 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700254 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700255 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700256
Mathieu Chartier0325e622012-09-05 14:22:51 -0700257 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700258 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
259 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700260 std::ostringstream name;
261 name << static_cast<GcType>(i);
262 cumulative_timings_.Put(static_cast<GcType>(i),
263 new CumulativeLogger(name.str().c_str(), true));
264 }
265
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800266 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800267 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700268 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700269}
270
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700271// Sort spaces based on begin address
272class SpaceSorter {
273 public:
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700274 bool operator ()(const Space* a, const Space* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700275 return a->Begin() < b->Begin();
276 }
277};
278
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800279void Heap::AddSpace(Space* space) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700280 WriterMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700281 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700282 DCHECK(space->GetLiveBitmap() != NULL);
283 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700284 DCHECK(space->GetMarkBitmap() != NULL);
285 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800286 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700287 if (space->IsAllocSpace()) {
288 alloc_space_ = space->AsAllocSpace();
289 }
290
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700291 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
292 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700293
294 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
295 // avoid redundant marking.
296 bool seen_zygote = false, seen_alloc = false;
297 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
298 Space* space = *it;
299 if (space->IsImageSpace()) {
300 DCHECK(!seen_zygote);
301 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700302 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700303 DCHECK(!seen_alloc);
304 seen_zygote = true;
305 } else if (space->IsAllocSpace()) {
306 seen_alloc = true;
307 }
308 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800309}
310
311Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700312 // If we don't reset then the mark stack complains in it's destructor.
313 allocation_stack_->Reset();
314 live_stack_->Reset();
315
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800316 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800317 // We can't take the heap lock here because there might be a daemon thread suspended with the
318 // heap lock held. We know though that no non-daemon threads are executing, and we know that
319 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
320 // 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 -0700321 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700322 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700323 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700324}
325
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700326Space* Heap::FindSpaceFromObject(const Object* obj) const {
327 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700328 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
329 if ((*it)->Contains(obj)) {
330 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700331 }
332 }
333 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
334 return NULL;
335}
336
337ImageSpace* Heap::GetImageSpace() {
338 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700339 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
340 if ((*it)->IsImageSpace()) {
341 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700342 }
343 }
344 return NULL;
345}
346
347AllocSpace* Heap::GetAllocSpace() {
348 return alloc_space_;
349}
350
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700351static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
352 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
353
354 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
355 size_t chunk_free_bytes = 0;
356 if (used_bytes < chunk_size) {
357 chunk_free_bytes = chunk_size - used_bytes;
358 }
359
360 if (chunk_free_bytes > max_contiguous_allocation) {
361 max_contiguous_allocation = chunk_free_bytes;
362 }
363}
364
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700365bool Heap::CanAllocateBytes(size_t bytes) const {
366 return num_bytes_allocated_ + large_object_space_->GetNumBytesAllocated() + bytes <=
367 alloc_space_->Capacity();
368}
369
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700370Object* Heap::AllocObject(Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700371 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
372 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
373 strlen(ClassHelper(c).GetDescriptor()) == 0);
374 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700375
376 Object* obj = NULL;
377 size_t size = 0;
378
379 // We need to have a zygote space or else our newly allocated large object can end up in the
380 // Zygote resulting in it being prematurely freed.
381 // We can only do this for primive objects since large objects will not be within the card table
382 // range. This also means that we rely on SetClass not dirtying the object's card.
383 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
384 obj = Allocate(NULL, RoundUp(byte_count, kPageSize));
385 size = 0;
386
387 if (obj != NULL) {
388 // Make sure that our large object didn't get placed anywhere within the space interval or else
389 // it breaks the immune range.
390 DCHECK(reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
391 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
392 }
393 } else {
394 obj = Allocate(alloc_space_, byte_count);
395 size = alloc_space_->AllocationSize(obj);
396
397 if (obj != NULL) {
398 // Additional verification to ensure that we did not allocate into a zygote space.
399 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
400 }
401 }
402
Mathieu Chartier037813d2012-08-23 16:44:59 -0700403 if (LIKELY(obj != NULL)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700404 android_atomic_add(byte_count, reinterpret_cast<volatile int32_t*>(
405 reinterpret_cast<size_t>(&bytes_since_last_gc_)));
406
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700407 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700408
409 // Record allocation after since we want to use the atomic add for the atomic fence to guard
410 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700411 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700412
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700413 if (Dbg::IsAllocTrackingEnabled()) {
414 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700415 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700416 if (bytes_since_last_gc_ >= concurrent_gc_start_rate_ ||
417 num_bytes_allocated_ >= concurrent_start_bytes_) {
418 // We already have a request pending, no reason to start more until we update
419 // concurrent_start_bytes_.
420 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
421 bytes_since_last_gc_ = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700422 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
423 SirtRef<Object> ref(obj);
424 RequestConcurrentGC();
425 }
426 VerifyObject(obj);
427
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700428 return obj;
429 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700430 int64_t total_bytes_free = GetFreeMemory();
431 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700432 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700433 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
434 if ((*it)->IsAllocSpace()) {
435 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700436 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700437 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700438
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700439 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 -0700440 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700441 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700442 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700443}
444
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700445bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700446 // Note: we deliberately don't take the lock here, and mustn't test anything that would
447 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700448 if (obj == NULL) {
449 return true;
450 }
451 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700452 return false;
453 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800454 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800455 if (spaces_[i]->Contains(obj)) {
456 return true;
457 }
458 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700459 // TODO: Find a way to check large object space without using a lock.
460 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700461}
462
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700463bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700464 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700465 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700466}
467
Elliott Hughes3e465b12011-09-02 18:26:12 -0700468#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700469void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700470 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700471 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700472 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700473 return;
474 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700475 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700476}
477#endif
478
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700479void Heap::DumpSpaces() {
480 // TODO: C++0x auto
481 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700482 Space* space = *it;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700483 LOG(INFO) << *space << "\n"
484 << *space->GetLiveBitmap() << "\n"
485 << *space->GetMarkBitmap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700486 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700487 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700488}
489
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700490void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700491 if (!IsAligned<kObjectAlignment>(obj)) {
492 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700493 }
494
Mathieu Chartier0325e622012-09-05 14:22:51 -0700495 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700496 // Check the allocation stack / live stack.
497 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
498 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
499 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700500 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
501 if (large_object_space_->GetLiveObjects()->Test(obj)) {
502 DumpSpaces();
503 LOG(FATAL) << "Object is dead: " << obj;
504 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700505 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700506 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700507
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700508 // Ignore early dawn of the universe verifications
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700509 if (!VERIFY_OBJECT_FAST && num_objects_allocated_ > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700510 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
511 Object::ClassOffset().Int32Value();
512 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
513 if (c == NULL) {
514 LOG(FATAL) << "Null class in object: " << obj;
515 } else if (!IsAligned<kObjectAlignment>(c)) {
516 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
517 } else if (!GetLiveBitmap()->Test(c)) {
518 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
519 }
520 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
521 // Note: we don't use the accessors here as they have internal sanity checks
522 // that we don't want to run
523 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
524 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
525 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
526 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
527 CHECK_EQ(c_c, c_c_c);
528 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529}
530
Brian Carlstrom78128a62011-09-15 17:21:19 -0700531void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700532 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700533 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700534}
535
536void Heap::VerifyHeap() {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700537 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700538 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700539}
540
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700541void Heap::RecordAllocation(size_t size, const Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700542 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700543 DCHECK_GT(size, 0u);
544 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
545 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700546 android_atomic_add(size, reinterpret_cast<volatile int32_t*>(
547 reinterpret_cast<size_t>(&num_bytes_allocated_)));
548 android_atomic_add(1, reinterpret_cast<volatile int32_t*>(
549 reinterpret_cast<size_t>(&num_objects_allocated_)));
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700550
551 if (Runtime::Current()->HasStatsEnabled()) {
552 RuntimeStats* global_stats = Runtime::Current()->GetStats();
553 RuntimeStats* thread_stats = Thread::Current()->GetStats();
554 ++global_stats->allocated_objects;
555 ++thread_stats->allocated_objects;
556 global_stats->allocated_bytes += size;
557 thread_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700558 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700559
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700560 allocation_stack_->AtomicPush(obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700561}
562
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700563void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier637e3482012-08-17 10:41:32 -0700564 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
565 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700566 DCHECK_LE(freed_objects, num_objects_allocated_);
Mathieu Chartier637e3482012-08-17 10:41:32 -0700567 android_atomic_add(-static_cast<int32_t>(freed_objects),
Mathieu Chartier556fad32012-08-20 16:13:20 -0700568 reinterpret_cast<volatile int32_t*>(
569 reinterpret_cast<size_t>(&num_objects_allocated_)));
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700570
571 DCHECK_LE(freed_bytes, num_bytes_allocated_);
Mathieu Chartier637e3482012-08-17 10:41:32 -0700572 android_atomic_add(-static_cast<int32_t>(freed_bytes),
Mathieu Chartier556fad32012-08-20 16:13:20 -0700573 reinterpret_cast<volatile int32_t*>(
574 reinterpret_cast<size_t>(&num_bytes_allocated_)));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700575
576 if (Runtime::Current()->HasStatsEnabled()) {
577 RuntimeStats* global_stats = Runtime::Current()->GetStats();
578 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700579 global_stats->freed_objects += freed_objects;
580 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700581 global_stats->freed_bytes += freed_bytes;
582 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700583 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700584}
585
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700586Object* Heap::TryToAllocate(AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier83cf3282012-09-26 17:54:27 -0700587 if (UNLIKELY(space == NULL)) {
588 if (CanAllocateBytes(alloc_size)) {
589 // TODO: This is racy, but is it worth fixing?
590 return large_object_space_->Alloc(alloc_size);
591 } else {
592 // Application ran out of heap space.
593 return NULL;
594 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700595 } else if (grow) {
596 return space->AllocWithGrowth(alloc_size);
597 } else {
598 return space->AllocWithoutGrowth(alloc_size);
599 }
600}
601
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602Object* Heap::Allocate(AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700603 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
604 // done in the runnable state where suspension is expected.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700605#ifndef NDEBUG
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700606 Thread* self = Thread::Current();
Ian Rogers81d425b2012-09-27 16:03:43 -0700607 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608 self->AssertThreadSuspensionIsAllowable();
609#endif
Brian Carlstromb82b6872011-10-26 17:18:07 -0700610
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700611 Object* ptr = TryToAllocate(space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700612 if (ptr != NULL) {
613 return ptr;
614 }
615
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700616 // The allocation failed. If the GC is running, block until it completes, and then retry the
617 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700618#ifdef NDEBUG
619 Thread* self = Thread::Current();
620#endif
621 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700622 if (last_gc != kGcTypeNone) {
623 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700624 ptr = TryToAllocate(space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700625 if (ptr != NULL) {
626 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700627 }
628 }
629
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700630 // Loop through our different Gc types and try to Gc until we get enough free memory.
631 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
632 bool run_gc = false;
633 GcType gc_type = static_cast<GcType>(i);
634 switch (gc_type) {
635 case kGcTypeSticky: {
636 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700637 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
638 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700639 break;
640 }
641 case kGcTypePartial:
642 run_gc = have_zygote_space_;
643 break;
644 case kGcTypeFull:
645 run_gc = true;
646 break;
647 default:
648 break;
649 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700650
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700651 if (run_gc) {
652 if (Runtime::Current()->HasStatsEnabled()) {
653 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
654 ++Thread::Current()->GetStats()->gc_for_alloc_count;
655 }
656 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
657
658 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
659 GcType gc_type_ran = CollectGarbageInternal(gc_type, false);
660 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
661 i = static_cast<size_t>(gc_type_ran);
662 self->TransitionFromSuspendedToRunnable();
663
664 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700665 ptr = TryToAllocate(space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700666 if (ptr != NULL) {
667 return ptr;
668 }
669 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700670 }
671
672 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700673 // Try harder, growing the heap if necessary.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700674 ptr = TryToAllocate(space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700675 if (ptr != NULL) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700676 if (space != NULL) {
677 size_t new_footprint = space->GetFootprintLimit();
678 // OLD-TODO: may want to grow a little bit more so that the amount of
679 // free space is equal to the old free space + the
680 // utilization slop for the new allocation.
681 VLOG(gc) << "Grow alloc space (frag case) to " << PrettySize(new_footprint)
682 << " for a " << PrettySize(alloc_size) << " allocation";
683 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700684 return ptr;
685 }
686
Elliott Hughes81ff3182012-03-23 20:35:56 -0700687 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
688 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
689 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700690
Elliott Hughes418dfe72011-10-06 18:56:27 -0700691 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700692 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
693 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700694
695 if (Runtime::Current()->HasStatsEnabled()) {
696 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
697 ++Thread::Current()->GetStats()->gc_for_alloc_count;
698 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700699 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700700 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700701 CollectGarbageInternal(kGcTypeFull, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700702 self->TransitionFromSuspendedToRunnable();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700703 return TryToAllocate(space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700704}
705
Elliott Hughesbf86d042011-08-31 17:53:14 -0700706int64_t Heap::GetMaxMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700707 size_t total = 0;
708 // TODO: C++0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700709 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
710 Space* space = *it;
711 if (space->IsAllocSpace()) {
712 total += space->AsAllocSpace()->Capacity();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700713 }
714 }
715 return total;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700716}
717
718int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700719 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700720}
721
722int64_t Heap::GetFreeMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700723 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700724}
725
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700726class InstanceCounter {
727 public:
728 InstanceCounter(Class* c, bool count_assignable)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700729 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700730 : class_(c), count_assignable_(count_assignable), count_(0) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700731
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700732 }
733
734 size_t GetCount() {
735 return count_;
736 }
737
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700738 static void Callback(Object* o, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700739 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700740 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
741 }
742
743 private:
Ian Rogersb726dcb2012-09-05 08:57:23 -0700744 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700745 Class* instance_class = o->GetClass();
746 if (count_assignable_) {
747 if (instance_class == class_) {
748 ++count_;
749 }
750 } else {
751 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
752 ++count_;
753 }
754 }
755 }
756
757 Class* class_;
758 bool count_assignable_;
759 size_t count_;
760};
761
762int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700763 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700764 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700765 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700766 return counter.GetCount();
767}
768
Ian Rogers30fab402012-01-23 15:43:46 -0800769void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700770 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
771 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700772 Thread* self = Thread::Current();
773 WaitForConcurrentGcToComplete(self);
774 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700775 CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700776}
777
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700778void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700779 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700780 Thread* self = Thread::Current();
781 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700782
783 // Try to see if we have any Zygote spaces.
784 if (have_zygote_space_) {
785 return;
786 }
787
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700788 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
789
790 {
791 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700792 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700793 FlushAllocStack();
794 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700795
796 // Replace the first alloc space we find with a zygote space.
797 // TODO: C++0x auto
798 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
799 if ((*it)->IsAllocSpace()) {
800 AllocSpace* zygote_space = (*it)->AsAllocSpace();
801
802 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
803 // of the remaining available heap memory.
804 alloc_space_ = zygote_space->CreateZygoteSpace();
805
806 // Change the GC retention policy of the zygote space to only collect when full.
807 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
808 AddSpace(alloc_space_);
809 have_zygote_space_ = true;
810 break;
811 }
812 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700813
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700814 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700815 // TODO: C++0x
816 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
817 it != cumulative_timings_.end(); ++it) {
818 it->second->Reset();
819 }
820
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700821 // Reset this since we now count the ZygoteSpace in the total heap size.
822 num_bytes_allocated_ = 0;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700823}
824
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700825void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700826 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
827 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700828 allocation_stack_->Reset();
829}
830
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700831size_t Heap::GetUsedMemorySize() const {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700832 size_t total = num_bytes_allocated_ + large_object_space_->GetNumBytesAllocated();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700833 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
834 if ((*it)->IsZygoteSpace()) {
835 total += (*it)->AsAllocSpace()->Size();
836 }
837 }
838 return total;
839}
840
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700841void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700842 const size_t count = stack->Size();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700843 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700844 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700845 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700846 if (LIKELY(bitmap->HasAddress(obj))) {
847 bitmap->Set(obj);
848 } else {
849 large_objects->Set(obj);
850 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700851 }
852}
853
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700854void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700855 size_t count = stack->Size();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700856 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700857 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700858 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700859 if (LIKELY(bitmap->HasAddress(obj))) {
860 bitmap->Clear(obj);
861 } else {
862 large_objects->Clear(obj);
863 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700864 }
865}
866
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700867GcType Heap::CollectGarbageInternal(GcType gc_type, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700868 Thread* self = Thread::Current();
869 Locks::mutator_lock_->AssertNotHeld(self);
870 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700871
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700872 // Ensure there is only one GC at a time.
873 bool start_collect = false;
874 while (!start_collect) {
875 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700876 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700877 if (!is_gc_running_) {
878 is_gc_running_ = true;
879 start_collect = true;
880 }
881 }
882 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700883 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700884 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
885 // Not doing at the moment to ensure soft references are cleared.
886 }
887 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700888 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700889
890 // We need to do partial GCs every now and then to avoid the heap growing too much and
891 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700892 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700893 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700894 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700895 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700896 sticky_gc_count_ = 0;
897 }
898
Mathieu Chartier637e3482012-08-17 10:41:32 -0700899 if (concurrent_gc_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700900 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700901 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700902 CollectGarbageMarkSweepPlan(self, gc_type, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700903 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700904 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700905
Ian Rogers15bf2d32012-08-28 17:33:04 -0700906 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700907 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700908 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700909 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700910 // Wake anyone who may have been waiting for the GC to complete.
911 gc_complete_cond_->Broadcast();
912 }
913 // Inform DDMS that a GC completed.
914 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700915 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700916}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700917
Ian Rogers81d425b2012-09-27 16:03:43 -0700918void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700919 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700920
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700921 std::stringstream gc_type_str;
922 gc_type_str << gc_type << " ";
923
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700924 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700925 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700926 ThreadList* thread_list = Runtime::Current()->GetThreadList();
927 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700928 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700929 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700930
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700931 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700932 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700933 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700934 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700935
936 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700937 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700938
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700939 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700940 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700941 if (!VerifyHeapReferences()) {
942 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
943 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700944 timings.AddSplit("VerifyHeapReferencesPreGC");
945 }
946
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700947 // Make sure that the tables have the correct pointer for the mark sweep.
948 mod_union_table_->Init(&mark_sweep);
949 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700950
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700951 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700952 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700953
954 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
955 // TODO: Investigate using a mark stack instead of a vector.
956 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700957 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700958 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
959 card_table_->GetDirtyCards(*it, dirty_cards);
960 }
961 }
962
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700963 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700964 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
965 Space* space = *it;
966 if (space->IsImageSpace()) {
967 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700968 timings.AddSplit("ClearModUnionCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700969 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
970 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700971 timings.AddSplit("ClearZygoteCards");
972 } else {
973 card_table_->ClearSpaceCards(space);
974 timings.AddSplit("ClearCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700975 }
976 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700977
Ian Rogersb726dcb2012-09-05 08:57:23 -0700978 WriterMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700979 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700980 // Copy the mark bits over from the live bits, do this as early as possible or else we can
981 // accidentally un-mark roots.
982 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700983 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700984 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
985 mark_sweep.CopyMarkBits(*it);
986 }
987 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700988 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700989
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700990 // We can assume that everything from the start of the first space to the alloc space is marked.
991 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
992 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700993 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700994 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700995 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
996 mark_sweep.CopyMarkBits(*it);
997 }
998 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700999 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000 timings.AddSplit("CopyMarkBits");
1001
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001002 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
1003 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001004 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001005
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001006 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1007 live_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001008
Mathieu Chartier0325e622012-09-05 14:22:51 -07001009 if (gc_type != kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001010 live_stack_->Reset();
1011 }
1012
Carl Shapiro58551df2011-07-24 03:09:51 -07001013 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001014 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001015
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001016 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -07001017 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -07001018
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001019 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001020
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001021 if (verify_mod_union_table_) {
1022 zygote_mod_union_table_->Update();
1023 zygote_mod_union_table_->Verify();
1024 mod_union_table_->Update();
1025 mod_union_table_->Verify();
1026 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001027
1028 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001029 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001030 live_stack_->Reset();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001031 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001032 } else {
1033 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1034 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001035 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001036
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001037 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001038 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001039 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001040
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001041 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1042 mark_sweep.SweepSystemWeaks(false);
1043 timings.AddSplit("SweepSystemWeaks");
1044
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001045 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001046 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001047 SwapBitmaps(self);
Mathieu Chartier654d3a22012-07-11 17:54:18 -07001048 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001049
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001050#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001051 // Verify that we only reach marked objects from the image space
1052 mark_sweep.VerifyImageRoots();
1053 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001054#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001055
Mathieu Chartier0325e622012-09-05 14:22:51 -07001056 if (gc_type != kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001057 mark_sweep.SweepLargeObjects(swap);
1058 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001059 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001060 } else {
1061 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001062 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001063 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001064
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001065 if (verify_system_weaks_) {
1066 mark_sweep.VerifySystemWeaks();
1067 timings.AddSplit("VerifySystemWeaks");
1068 }
1069
Elliott Hughesadb460d2011-10-05 17:02:34 -07001070 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001071 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001072 }
1073
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001074 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001075 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001076 if (!VerifyHeapReferences()) {
1077 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1078 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001079 timings.AddSplit("VerifyHeapReferencesPostGC");
1080 }
1081
Carl Shapiro58551df2011-07-24 03:09:51 -07001082 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001083 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001084
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001085 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001086 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001087
1088 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001089 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001090 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001091
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092 // If the GC was slow, then print timings in the log.
1093 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1094 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001095 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001096 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001097 const size_t total_memory = GetTotalMemory();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001098 LOG(INFO) << gc_type_str.str() << " "
Mathieu Chartier637e3482012-08-17 10:41:32 -07001099 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001100 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001101 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001102 if (VLOG_IS_ON(heap)) {
1103 timings.Dump();
1104 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001105 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001106
Mathieu Chartier0325e622012-09-05 14:22:51 -07001107 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1108 logger->Start();
1109 logger->AddLogger(timings);
1110 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001111}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001112
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001113void Heap::UpdateAndMarkModUnion(TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001114 if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001115 // Don't need to do anythign for mod union table in this case since we are only scanning dirty
1116 // cards.
1117 return;
1118 }
1119
1120 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001121 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001122 zygote_mod_union_table_->Update();
1123 timings.AddSplit("UpdateZygoteModUnionTable");
1124
1125 zygote_mod_union_table_->MarkReferences();
1126 timings.AddSplit("ZygoteMarkReferences");
1127 }
1128
1129 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1130 mod_union_table_->Update();
1131 timings.AddSplit("UpdateModUnionTable");
1132
1133 // Scans all objects in the mod-union table.
1134 mod_union_table_->MarkReferences();
1135 timings.AddSplit("MarkImageToAllocSpaceReferences");
1136}
1137
1138void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1139 Object* obj = reinterpret_cast<Object*>(arg);
1140 if (root == obj) {
1141 LOG(INFO) << "Object " << obj << " is a root";
1142 }
1143}
1144
1145class ScanVisitor {
1146 public:
1147 void operator ()(const Object* obj) const {
1148 LOG(INFO) << "Would have rescanned object " << obj;
1149 }
1150};
1151
1152class VerifyReferenceVisitor {
1153 public:
1154 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001155 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1156 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001157 : heap_(heap),
1158 failed_(failed) {
1159 }
1160
1161 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1162 // analysis.
1163 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1164 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1165 // Verify that the reference is live.
1166 if (ref != NULL && !IsLive(ref)) {
1167 CardTable* card_table = heap_->GetCardTable();
1168 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1169 MarkStack* live_stack = heap_->live_stack_.get();
1170
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001171 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001172 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " on IsDirty = "
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001173 << (*card_addr == GC_CARD_DIRTY);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001174 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1175 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1176 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001177 void* cover_begin = card_table->AddrFromCard(card_addr);
1178 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1179 GC_CARD_SIZE);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001180 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001181 << "-" << cover_end;
1182 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1183
1184 // Print out how the object is live.
1185 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001186 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1187 }
1188
1189 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1190 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1191 }
1192
1193 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1194 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001195 }
1196
1197 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001198 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001199 }
1200
1201 // Attempt to see if the card table missed the reference.
1202 ScanVisitor scan_visitor;
1203 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1204 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + GC_CARD_SIZE, scan_visitor,
1205 IdentityFunctor());
1206
1207 // Try and see if a mark sweep collector scans the reference.
1208 MarkStack* mark_stack = heap_->mark_stack_.get();
1209 MarkSweep ms(mark_stack);
1210 ms.Init();
1211 mark_stack->Reset();
1212 ms.SetFinger(reinterpret_cast<Object*>(~size_t(0)));
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001213
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001214 // All the references should end up in the mark stack.
1215 ms.ScanRoot(obj);
1216 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001217 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001218 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001219 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001220 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001221 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001222 }
1223 }
1224 mark_stack->Reset();
1225
1226 // Search to see if any of the roots reference our object.
1227 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1228 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1229 *failed_ = true;
1230 }
1231 }
1232
1233 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1234 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1235 if (bitmap != NULL) {
1236 if (bitmap->Test(obj)) {
1237 return true;
1238 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001239 } else if (heap_->GetLargeObjectsSpace()->GetLiveObjects()->Test(obj)) {
1240 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001241 } else {
1242 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001243 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001244 }
1245 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1246 // At this point we need to search the allocation since things in the live stack may get swept.
1247 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1248 return true;
1249 }
1250 // Not either in the live bitmap or allocation stack, so the object must be dead.
1251 return false;
1252 }
1253
1254 private:
1255 Heap* heap_;
1256 bool* failed_;
1257};
1258
1259class VerifyObjectVisitor {
1260 public:
1261 VerifyObjectVisitor(Heap* heap)
1262 : heap_(heap),
1263 failed_(false) {
1264
1265 }
1266
1267 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001268 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001269 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1270 MarkSweep::VisitObjectReferences(obj, visitor);
1271 }
1272
1273 bool Failed() const {
1274 return failed_;
1275 }
1276
1277 private:
1278 Heap* heap_;
1279 bool failed_;
1280};
1281
1282// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001283bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001284 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001285 // Lets sort our allocation stacks so that we can efficiently binary search them.
1286 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1287 std::sort(live_stack_->Begin(), live_stack_->End());
1288 // Perform the verification.
1289 VerifyObjectVisitor visitor(this);
1290 GetLiveBitmap()->Visit(visitor);
1291 // We don't want to verify the objects in the allocation stack since they themselves may be
1292 // pointing to dead objects if they are not reachable.
1293 if (visitor.Failed()) {
1294 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001295 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001296 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001297 return true;
1298}
1299
1300class VerifyReferenceCardVisitor {
1301 public:
1302 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1303 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1304 Locks::heap_bitmap_lock_)
1305 : heap_(heap),
1306 failed_(failed) {
1307 }
1308
1309 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1310 // analysis.
1311 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1312 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
1313 if (ref != NULL) {
1314 CardTable* card_table = heap_->GetCardTable();
1315 // If the object is not dirty and it is referencing something in the live stack other than
1316 // class, then it must be on a dirty card.
1317 if (!card_table->IsDirty(obj)) {
1318 MarkStack* live_stack = heap_->live_stack_.get();
1319 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1320 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1321 LOG(ERROR) << "Object " << obj << " found in live stack";
1322 }
1323 if (heap_->GetLiveBitmap()->Test(obj)) {
1324 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1325 }
1326 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1327 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1328
1329 // Print which field of the object is dead.
1330 if (!obj->IsObjectArray()) {
1331 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1332 CHECK(klass != NULL);
1333 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1334 CHECK(fields != NULL);
1335 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1336 const Field* cur = fields->Get(i);
1337 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1338 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1339 << PrettyField(cur);
1340 break;
1341 }
1342 }
1343 } else {
1344 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1345 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1346 if (object_array->Get(i) == ref) {
1347 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1348 }
1349 }
1350 }
1351
1352 *failed_ = true;
1353 }
1354 }
1355 }
1356 }
1357
1358 private:
1359 Heap* heap_;
1360 bool* failed_;
1361};
1362
1363class VerifyLiveStackReferences {
1364 public:
1365 VerifyLiveStackReferences(Heap* heap)
1366 : heap_(heap),
1367 failed_(false) {
1368
1369 }
1370
1371 void operator ()(const Object* obj) const
1372 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1373 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1374 MarkSweep::VisitObjectReferences(obj, visitor);
1375 }
1376
1377 bool Failed() const {
1378 return failed_;
1379 }
1380
1381 private:
1382 Heap* heap_;
1383 bool failed_;
1384};
1385
1386bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001387 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001388
1389 VerifyLiveStackReferences visitor(this);
1390 GetLiveBitmap()->Visit(visitor);
1391
1392 // We can verify objects in the live stack since none of these should reference dead objects.
1393 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1394 visitor(*it);
1395 }
1396
1397 if (visitor.Failed()) {
1398 DumpSpaces();
1399 return false;
1400 }
1401 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001402}
1403
Ian Rogers81d425b2012-09-27 16:03:43 -07001404void Heap::SwapBitmaps(Thread* self) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001405 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1406 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1407 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
1408 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
Ian Rogers81d425b2012-09-27 16:03:43 -07001409 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001410 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1411 Space* space = *it;
1412 // We never allocate into zygote spaces.
1413 if (space->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1414 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1415 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1416 space->AsAllocSpace()->SwapBitmaps();
1417 }
1418 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001419
1420 large_object_space_->SwapBitmaps();
1421 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1422 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001423}
1424
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001425void Heap::SwapStacks() {
1426 MarkStack* temp = allocation_stack_.release();
1427 allocation_stack_.reset(live_stack_.release());
1428 live_stack_.reset(temp);
1429
1430 // Sort the live stack so that we can quickly binary search it later.
1431 if (VERIFY_OBJECT_ENABLED) {
1432 std::sort(live_stack_->Begin(), live_stack_->End());
1433 }
1434}
1435
Ian Rogers81d425b2012-09-27 16:03:43 -07001436void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001437 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1438 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001439 std::stringstream gc_type_str;
1440 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001441
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001442 // Suspend all threads are get exclusive access to the heap.
1443 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1444 thread_list->SuspendAll();
1445 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001446 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001447
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001448 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001449 Object* cleared_references = NULL;
1450 {
1451 MarkSweep mark_sweep(mark_stack_.get());
1452 timings.AddSplit("ctor");
1453
1454 mark_sweep.Init();
1455 timings.AddSplit("Init");
1456
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001457 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001458 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001459 if (!VerifyHeapReferences()) {
1460 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1461 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001462 timings.AddSplit("VerifyHeapReferencesPreGC");
1463 }
1464
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001465 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1466 SwapStacks();
1467
1468 // Check that all objects which reference things in the live stack are on dirty cards.
1469 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001470 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001471 // Sort the live stack so that we can quickly binary search it later.
1472 std::sort(live_stack_->Begin(), live_stack_->End());
1473 if (!VerifyMissingCardMarks()) {
1474 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1475 }
1476 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001477
1478 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1479 // TODO: Investigate using a mark stack instead of a vector.
1480 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001481 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001482 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1483 card_table_->GetDirtyCards(*it, dirty_cards);
1484 }
1485 }
1486
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001487 // Make sure that the tables have the correct pointer for the mark sweep.
1488 mod_union_table_->Init(&mark_sweep);
1489 zygote_mod_union_table_->Init(&mark_sweep);
1490
1491 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1492 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1493 Space* space = *it;
1494 if (space->IsImageSpace()) {
1495 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001496 timings.AddSplit("ModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001497 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1498 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001499 timings.AddSplit("ZygoteModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001500 } else {
1501 card_table_->ClearSpaceCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001502 timings.AddSplit("ClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001503 }
1504 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001505
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001506 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001507 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001508
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001509 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1510 CHECK(!GetLiveBitmap()->Test(*it));
1511 }
1512
Mathieu Chartier0325e622012-09-05 14:22:51 -07001513 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001514 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1515 // accidentally un-mark roots.
1516 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001517 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001518 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1519 mark_sweep.CopyMarkBits(*it);
1520 }
1521 }
1522 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001523 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1524 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001525 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001526 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001527 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1528 mark_sweep.CopyMarkBits(*it);
1529 }
1530 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001531 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001532 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001533 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1534 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001535 }
1536
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001537 // Marking roots is not necessary for sticky mark bits since we only actually require the
1538 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001539 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001540 mark_sweep.MarkRoots();
1541 timings.AddSplit("MarkRoots");
1542 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001543
1544 if (verify_mod_union_table_) {
1545 zygote_mod_union_table_->Update();
1546 zygote_mod_union_table_->Verify();
1547 mod_union_table_->Update();
1548 mod_union_table_->Verify();
1549 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001550 }
1551
1552 // Roots are marked on the bitmap and the mark_stack is empty.
1553 DCHECK(mark_sweep.IsMarkStackEmpty());
1554
1555 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1556 thread_list->ResumeAll();
1557 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001558 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001559 root_end = NanoTime();
1560 timings.AddSplit("RootEnd");
1561
Ian Rogers81d425b2012-09-27 16:03:43 -07001562 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001563 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001564
1565 // Mark everything as live so that sweeping system weak works correctly for sticky mark bit
1566 // GCs.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001567 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1568 live_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001569 timings.AddSplit("MarkStackAsLive");
1570
Mathieu Chartier0325e622012-09-05 14:22:51 -07001571 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001572 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001573 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001574 } else {
1575 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001576 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001577 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001578 }
1579 // Release share on mutator_lock_ and then get exclusive access.
1580 dirty_begin = NanoTime();
1581 thread_list->SuspendAll();
1582 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001583 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001584
1585 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001586 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001587
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001588 // Re-mark root set.
1589 mark_sweep.ReMarkRoots();
1590 timings.AddSplit("ReMarkRoots");
1591
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001592 if (verify_missing_card_marks_) {
1593 // Since verify missing card marks uses a sweep array to empty the allocation stack, we
1594 // need to make sure that we don't free weaks which wont get swept by SweepSystemWeaks.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001595 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1596 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001597 }
1598
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001599 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001600 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001601 timings.AddSplit("RecursiveMarkDirtyObjects");
1602 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001603
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001604 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001605 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001606
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001607 mark_sweep.ProcessReferences(clear_soft_references);
1608 timings.AddSplit("ProcessReferences");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001609
1610 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1611 mark_sweep.SweepSystemWeaks(false);
1612 timings.AddSplit("SweepSystemWeaks");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001613 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001614
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001615 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1616 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1617 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1618 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001619 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001620 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001621 SwapBitmaps(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001622 }
1623
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001624 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1625 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001626 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001627 mark_sweep.SweepArray(timings, allocation_stack_.get(), swap);
1628 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001629 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001630 // We only sweep over the live stack, and the live stack should not intersect with the
1631 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001632 UnMarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1633 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001634 timings.AddSplit("UnMarkAllocStack");
1635 }
1636
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001637 if (kIsDebugBuild) {
1638 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001639 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001640 mark_sweep.VerifyImageRoots();
1641 timings.AddSplit("VerifyImageRoots");
1642 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001643
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001644 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001645 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001646 if (!VerifyHeapReferences()) {
1647 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
1648 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001649 timings.AddSplit("VerifyHeapReferencesPostGC");
1650 }
1651
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001652 thread_list->ResumeAll();
1653 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001654 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655
1656 {
1657 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Ian Rogers81d425b2012-09-27 16:03:43 -07001658 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001659 if (gc_type != kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001660 mark_sweep.SweepLargeObjects(swap);
1661 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001662 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001663 } else {
1664 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001665 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001666 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001667 live_stack_->Reset();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001668 timings.AddSplit("Sweep");
1669 }
1670
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001671 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001672 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001673 mark_sweep.VerifySystemWeaks();
1674 timings.AddSplit("VerifySystemWeaks");
1675 }
1676
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001677 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001678 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001679 }
1680
1681 GrowForUtilization();
1682 timings.AddSplit("GrowForUtilization");
1683
1684 EnqueueClearedReferences(&cleared_references);
1685 RequestHeapTrim();
1686 timings.AddSplit("Finish");
1687
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001688 // If the GC was slow, then print timings in the log.
1689 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1690 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001691 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001692 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001693 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001694 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001695 const size_t total_memory = GetTotalMemory();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001696 LOG(INFO) << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001697 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001698 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001699 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1700 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001701 if (VLOG_IS_ON(heap)) {
1702 timings.Dump();
1703 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001704 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001705
Mathieu Chartier0325e622012-09-05 14:22:51 -07001706 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1707 logger->Start();
1708 logger->AddLogger(timings);
1709 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001710}
1711
Ian Rogers81d425b2012-09-27 16:03:43 -07001712GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001713 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001714 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001715 bool do_wait;
1716 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001717 {
1718 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001719 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001720 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001721 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001722 if (do_wait) {
1723 // We must wait, change thread state then sleep on gc_complete_cond_;
1724 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1725 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001726 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001727 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001728 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001729 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001730 last_gc_type = last_gc_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001731 }
1732 uint64_t wait_time = NanoTime() - wait_start;
1733 if (wait_time > MsToNs(5)) {
1734 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1735 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001736 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001737 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001738 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001739}
1740
Elliott Hughesc967f782012-04-16 10:23:15 -07001741void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001742 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(num_bytes_allocated_) << "/"
1743 << PrettySize(GetTotalMemory()) << "; " << num_objects_allocated_ << " objects\n";
Mathieu Chartier0325e622012-09-05 14:22:51 -07001744 // Dump cumulative timings.
1745 LOG(INFO) << "Dumping cumulative Gc timings";
1746 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
1747 it != cumulative_timings_.end(); ++it) {
1748 it->second->Dump();
1749 }
Elliott Hughesc967f782012-04-16 10:23:15 -07001750}
1751
1752size_t Heap::GetPercentFree() {
1753 size_t total = GetTotalMemory();
1754 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
1755}
1756
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001757void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001758 AllocSpace* alloc_space = alloc_space_;
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001759 size_t alloc_space_capacity = alloc_space->Capacity();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001760 alloc_space_capacity -= large_object_space_->GetNumBytesAllocated();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001761 if (max_allowed_footprint > alloc_space_capacity) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001762 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
1763 << PrettySize(alloc_space_capacity);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001764 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001765 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001766 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001767}
1768
Ian Rogers3bb17a62012-01-27 23:56:44 -08001769// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001770static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001771// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1772// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001773static const size_t kHeapMinFree = kHeapIdealFree / 4;
1774
Carl Shapiro69759ea2011-07-21 18:13:35 -07001775void Heap::GrowForUtilization() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001776 size_t target_size;
1777 bool use_footprint_limit = false;
1778 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001779 // We know what our utilization is at this moment.
1780 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1781 target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001782
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001783 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1784 target_size = num_bytes_allocated_ + kHeapIdealFree;
1785 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1786 target_size = num_bytes_allocated_ + kHeapMinFree;
1787 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001788
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001789 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001790 if (GetTotalMemory() - GetUsedMemorySize() < concurrent_min_free_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001791 // Not enough free memory to perform concurrent GC.
1792 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1793 } else {
1794 // Compute below to avoid holding both the statistics and the alloc space lock
1795 use_footprint_limit = true;
1796 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001797 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001798
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001799 if (use_footprint_limit) {
1800 size_t foot_print_limit = alloc_space_->GetFootprintLimit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001801 concurrent_start_bytes_ = foot_print_limit - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001802 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001803 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001804}
1805
jeffhaoc1160702011-10-27 15:48:45 -07001806void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001807 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001808 alloc_space_->ClearGrowthLimit();
1809}
1810
Elliott Hughesadb460d2011-10-05 17:02:34 -07001811void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001812 MemberOffset reference_queue_offset,
1813 MemberOffset reference_queueNext_offset,
1814 MemberOffset reference_pendingNext_offset,
1815 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001816 reference_referent_offset_ = reference_referent_offset;
1817 reference_queue_offset_ = reference_queue_offset;
1818 reference_queueNext_offset_ = reference_queueNext_offset;
1819 reference_pendingNext_offset_ = reference_pendingNext_offset;
1820 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1821 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1822 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1823 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1824 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1825 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1826}
1827
1828Object* Heap::GetReferenceReferent(Object* reference) {
1829 DCHECK(reference != NULL);
1830 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1831 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1832}
1833
1834void Heap::ClearReferenceReferent(Object* reference) {
1835 DCHECK(reference != NULL);
1836 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1837 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1838}
1839
1840// Returns true if the reference object has not yet been enqueued.
1841bool Heap::IsEnqueuable(const Object* ref) {
1842 DCHECK(ref != NULL);
1843 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1844 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1845 return (queue != NULL) && (queue_next == NULL);
1846}
1847
1848void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1849 DCHECK(ref != NULL);
1850 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1851 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1852 EnqueuePendingReference(ref, cleared_reference_list);
1853}
1854
1855void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1856 DCHECK(ref != NULL);
1857 DCHECK(list != NULL);
1858
1859 if (*list == NULL) {
1860 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1861 *list = ref;
1862 } else {
1863 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1864 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1865 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1866 }
1867}
1868
1869Object* Heap::DequeuePendingReference(Object** list) {
1870 DCHECK(list != NULL);
1871 DCHECK(*list != NULL);
1872 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1873 Object* ref;
1874 if (*list == head) {
1875 ref = *list;
1876 *list = NULL;
1877 } else {
1878 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1879 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1880 ref = head;
1881 }
1882 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1883 return ref;
1884}
1885
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001886void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001887 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001888 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001889 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001890 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1891 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001892}
1893
1894size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001895 return num_bytes_allocated_;
1896}
1897
1898size_t Heap::GetObjectsAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001899 return num_objects_allocated_;
1900}
1901
1902size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001903 return concurrent_start_size_;
1904}
1905
1906size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001907 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001908}
1909
1910void Heap::EnqueueClearedReferences(Object** cleared) {
1911 DCHECK(cleared != NULL);
1912 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001913 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001914 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001915 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001916 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1917 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001918 *cleared = NULL;
1919 }
1920}
1921
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001922void Heap::RequestConcurrentGC() {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001923 // Make sure that we can do a concurrent GC.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001924 if (requesting_gc_ || !Runtime::Current()->IsFinishedStarting() ||
1925 Runtime::Current()->IsShuttingDown() || !Runtime::Current()->IsConcurrentGcEnabled()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001926 return;
1927 }
1928
1929 requesting_gc_ = true;
1930 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001931 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1932 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001933 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1934 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001935 CHECK(!env->ExceptionCheck());
1936 requesting_gc_ = false;
1937}
1938
Ian Rogers81d425b2012-09-27 16:03:43 -07001939void Heap::ConcurrentGC(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001940 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
Mathieu Chartier2542d662012-06-21 17:14:11 -07001941 return;
1942 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001943
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001944 // TODO: We shouldn't need a WaitForConcurrentGcToComplete here since only
1945 // concurrent GC resumes threads before the GC is completed and this function
1946 // is only called within the GC daemon thread.
Ian Rogers81d425b2012-09-27 16:03:43 -07001947 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001948 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07001949 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001950 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001951 CollectGarbageInternal(kGcTypeSticky, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001952 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001953 CollectGarbageInternal(kGcTypePartial, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001954 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001955 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001956}
1957
Ian Rogers81d425b2012-09-27 16:03:43 -07001958void Heap::Trim(Thread* self) {
1959 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001960 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001961}
1962
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001963void Heap::RequestHeapTrim() {
1964 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1965 // because that only marks object heads, so a large array looks like lots of empty space. We
1966 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1967 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1968 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1969 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001970 uint64_t ms_time = NsToMs(NanoTime());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001971 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001972 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
1973 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1974 // Don't bother trimming the heap if it's more than 75% utilized, or if a
1975 // heap trim occurred in the last two seconds.
1976 return;
1977 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001978 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001979 if (!Runtime::Current()->IsFinishedStarting() || Runtime::Current()->IsShuttingDown()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001980 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
Mathieu Chartiera6399032012-06-11 18:49:50 -07001981 // Also: we do not wish to start a heap trim if the runtime is shutting down.
Ian Rogerse1d490c2012-02-03 09:09:07 -08001982 return;
1983 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001984 last_trim_time_ = ms_time;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001985 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001986 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1987 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001988 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1989 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001990 CHECK(!env->ExceptionCheck());
1991}
1992
Carl Shapiro69759ea2011-07-21 18:13:35 -07001993} // namespace art