blob: fa044c2cbb86742064869d6d059870b9a11ff3ab [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
Ian Rogers5d76c432011-10-31 21:42:49 -070025#include "card_table.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070026#include "debugger.h"
Mathieu Chartiercc236d72012-07-20 10:29:05 -070027#include "heap_bitmap.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070028#include "image.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070029#include "mark_sweep.h"
Mathieu Chartierb43b7d42012-06-19 13:15:09 -070030#include "mod_union_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070031#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080032#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080033#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070034#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070035#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070036#include "sirt_ref.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 Chartier2fde5332012-09-14 14:51:54 -0700133 growth_limit_(growth_limit),
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700134 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700135 concurrent_start_size_(128 * KB),
136 concurrent_min_free_(256 * KB),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700137 concurrent_gc_start_rate_(3 * MB / 2),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700138 sticky_gc_count_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700139 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800140 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700141 verify_missing_card_marks_(false),
142 verify_system_weaks_(false),
143 verify_pre_gc_heap_(false),
144 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700145 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700146 partial_gc_frequency_(10),
147 min_alloc_space_size_for_sticky_gc_(4 * MB),
148 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700149 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700150 try_running_gc_(false),
151 requesting_gc_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800152 reference_referent_offset_(0),
153 reference_queue_offset_(0),
154 reference_queueNext_offset_(0),
155 reference_pendingNext_offset_(0),
156 finalizer_reference_zombie_offset_(0),
157 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700158 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800159 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800160 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700161 }
162
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700163 live_bitmap_.reset(new HeapBitmap(this));
164 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700165
Ian Rogers30fab402012-01-23 15:43:46 -0800166 // Requested begin for the alloc space, to follow the mapped image and oat files
167 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800168 std::string image_file_name(original_image_file_name);
169 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700170 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700171
Brian Carlstrom5643b782012-02-05 12:32:53 -0800172 if (OS::FileExists(image_file_name.c_str())) {
173 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700174 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800175 } else {
176 // If the /system file didn't exist, we need to use one from the art-cache.
177 // If the cache file exists, try to open, but if it fails, regenerate.
178 // If it does not exist, generate.
179 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
180 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700181 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800182 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700183 if (image_space == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800184 if (!GenerateImage(image_file_name)) {
185 LOG(FATAL) << "Failed to generate image: " << image_file_name;
186 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700187 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800188 }
189 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700190 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700191 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800192 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
193 // isn't going to get in the middle
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700194 byte* oat_end_addr = GetImageSpace()->GetImageHeader().GetOatEnd();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700195 CHECK_GT(oat_end_addr, GetImageSpace()->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800196 if (oat_end_addr > requested_begin) {
197 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700198 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700199 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700200 }
201
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700202 // Allocate the large object space (placed after the alloc space).
203 large_object_space_.reset(FreeListSpace::Create("large object space", requested_begin + capacity,
204 capacity));
205 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
206 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
207
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700208 UniquePtr<AllocSpace> alloc_space(AllocSpace::Create("alloc space", initial_size, growth_limit,
209 capacity, requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700210 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700211 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700212 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700213
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700214 // Spaces are sorted in order of Begin().
215 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700216 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
217 if (spaces_.back()->IsAllocSpace()) {
218 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
219 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700220
Ian Rogers30fab402012-01-23 15:43:46 -0800221 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700222 // TODO: C++0x
223 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
224 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800225 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700226 ImageSpace* image_space = space->AsImageSpace();
227 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800228 }
229 }
230
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800231 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700232 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
233 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700234
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700235 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
236 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700237
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700238 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
239 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700240
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700241 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700242 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700243
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700244 // Max stack size in bytes.
245 static const size_t max_stack_size = capacity / SpaceBitmap::kAlignment * kWordSize;
246
247 // TODO: Rename MarkStack to a more generic name?
248 mark_stack_.reset(MarkStack::Create("dalvik-mark-stack", max_stack_size));
249 allocation_stack_.reset(MarkStack::Create("dalvik-allocation-stack", max_stack_size));
250 live_stack_.reset(MarkStack::Create("dalvik-live-stack", max_stack_size));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700251
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800252 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700253 // but we can create the heap lock now. We don't create it earlier to
254 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700255 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700256 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700257
Mathieu Chartier0325e622012-09-05 14:22:51 -0700258 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700259 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
260 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700261 std::ostringstream name;
262 name << static_cast<GcType>(i);
263 cumulative_timings_.Put(static_cast<GcType>(i),
264 new CumulativeLogger(name.str().c_str(), true));
265 }
266
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800267 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800268 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700269 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700270}
271
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700272// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700273struct SpaceSorter {
274 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700275 return a->Begin() < b->Begin();
276 }
277};
278
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700279void Heap::AddSpace(ContinuousSpace* 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 Chartier2fde5332012-09-14 14:51:54 -0700326ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700327 // 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) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700352 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700353 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700354 size_t chunk_free_bytes = chunk_size - used_bytes;
355 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
356 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700357 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700358}
359
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700360Object* Heap::AllocObject(Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700361 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
362 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
363 strlen(ClassHelper(c).GetDescriptor()) == 0);
364 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700365
366 Object* obj = NULL;
367 size_t size = 0;
368
369 // We need to have a zygote space or else our newly allocated large object can end up in the
370 // Zygote resulting in it being prematurely freed.
371 // We can only do this for primive objects since large objects will not be within the card table
372 // range. This also means that we rely on SetClass not dirtying the object's card.
373 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700374 size = RoundUp(byte_count, kPageSize);
375 obj = Allocate(NULL, size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700376
377 if (obj != NULL) {
378 // Make sure that our large object didn't get placed anywhere within the space interval or else
379 // it breaks the immune range.
380 DCHECK(reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
381 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
382 }
383 } else {
384 obj = Allocate(alloc_space_, byte_count);
385 size = alloc_space_->AllocationSize(obj);
386
387 if (obj != NULL) {
388 // Additional verification to ensure that we did not allocate into a zygote space.
389 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
390 }
391 }
392
Mathieu Chartier037813d2012-08-23 16:44:59 -0700393 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700394 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700395
396 // Record allocation after since we want to use the atomic add for the atomic fence to guard
397 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700398 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700399
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700400 if (Dbg::IsAllocTrackingEnabled()) {
401 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700402 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700403 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700404 // We already have a request pending, no reason to start more until we update
405 // concurrent_start_bytes_.
406 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700407 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700408 Thread* self = Thread::Current();
409 SirtRef<Object> ref(self, obj);
410 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700411 }
412 VerifyObject(obj);
413
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700414 return obj;
415 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700416 int64_t total_bytes_free = GetFreeMemory();
417 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700418 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700419 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
420 if ((*it)->IsAllocSpace()) {
421 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700422 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700423 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700424
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700425 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 -0700426 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700427 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700428 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700429}
430
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700431bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700432 // Note: we deliberately don't take the lock here, and mustn't test anything that would
433 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700434 if (obj == NULL) {
435 return true;
436 }
437 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700438 return false;
439 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800440 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800441 if (spaces_[i]->Contains(obj)) {
442 return true;
443 }
444 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700445 // TODO: Find a way to check large object space without using a lock.
446 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700447}
448
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700449bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700450 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700451 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700452}
453
Elliott Hughes3e465b12011-09-02 18:26:12 -0700454#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700456 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700457 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700458 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700459 return;
460 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700461 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700462}
463#endif
464
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700465void Heap::DumpSpaces() {
466 // TODO: C++0x auto
467 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700468 ContinuousSpace* space = *it;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700469 LOG(INFO) << *space << "\n"
470 << *space->GetLiveBitmap() << "\n"
471 << *space->GetMarkBitmap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700472 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700473 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700474}
475
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700476void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700477 if (!IsAligned<kObjectAlignment>(obj)) {
478 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700479 }
480
Mathieu Chartier0325e622012-09-05 14:22:51 -0700481 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700482 // Check the allocation stack / live stack.
483 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
484 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
485 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700486 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
487 if (large_object_space_->GetLiveObjects()->Test(obj)) {
488 DumpSpaces();
489 LOG(FATAL) << "Object is dead: " << obj;
490 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700491 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700492 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700493
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700494 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700495 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700496 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
497 Object::ClassOffset().Int32Value();
498 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
499 if (c == NULL) {
500 LOG(FATAL) << "Null class in object: " << obj;
501 } else if (!IsAligned<kObjectAlignment>(c)) {
502 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
503 } else if (!GetLiveBitmap()->Test(c)) {
504 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
505 }
506 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
507 // Note: we don't use the accessors here as they have internal sanity checks
508 // that we don't want to run
509 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
510 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
511 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
512 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
513 CHECK_EQ(c_c, c_c_c);
514 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700515}
516
Brian Carlstrom78128a62011-09-15 17:21:19 -0700517void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700518 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700519 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700520}
521
522void Heap::VerifyHeap() {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700523 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700524 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525}
526
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700527void Heap::RecordAllocation(size_t size, const Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700528 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700529 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700530 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700531
532 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700533 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700534 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700535 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700536
537 // TODO: Update these atomically.
538 RuntimeStats* global_stats = Runtime::Current()->GetStats();
539 ++global_stats->allocated_objects;
540 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700541 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700542
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700543 allocation_stack_->AtomicPush(obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700544}
545
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700546void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier637e3482012-08-17 10:41:32 -0700547 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
548 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700549 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
550 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700551
552 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700553 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700554 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700555 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700556
557 // TODO: Do this concurrently.
558 RuntimeStats* global_stats = Runtime::Current()->GetStats();
559 global_stats->freed_objects += freed_objects;
560 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700561 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700562}
563
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700564Object* Heap::TryToAllocate(AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700565 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
566 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
567 return NULL;
568 }
569
Mathieu Chartier83cf3282012-09-26 17:54:27 -0700570 if (UNLIKELY(space == NULL)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700571 return large_object_space_->Alloc(alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700572 } else if (grow) {
573 return space->AllocWithGrowth(alloc_size);
574 } else {
575 return space->AllocWithoutGrowth(alloc_size);
576 }
577}
578
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700579Object* Heap::Allocate(AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700580 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
581 // done in the runnable state where suspension is expected.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700582#ifndef NDEBUG
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700583 Thread* self = Thread::Current();
Ian Rogers81d425b2012-09-27 16:03:43 -0700584 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700585 self->AssertThreadSuspensionIsAllowable();
586#endif
Brian Carlstromb82b6872011-10-26 17:18:07 -0700587
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700588 Object* ptr = TryToAllocate(space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700589 if (ptr != NULL) {
590 return ptr;
591 }
592
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700593 // The allocation failed. If the GC is running, block until it completes, and then retry the
594 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700595#ifdef NDEBUG
596 Thread* self = Thread::Current();
597#endif
598 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700599 if (last_gc != kGcTypeNone) {
600 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700601 ptr = TryToAllocate(space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700602 if (ptr != NULL) {
603 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700604 }
605 }
606
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700607 // Loop through our different Gc types and try to Gc until we get enough free memory.
608 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
609 bool run_gc = false;
610 GcType gc_type = static_cast<GcType>(i);
611 switch (gc_type) {
612 case kGcTypeSticky: {
613 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700614 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
615 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700616 break;
617 }
618 case kGcTypePartial:
619 run_gc = have_zygote_space_;
620 break;
621 case kGcTypeFull:
622 run_gc = true;
623 break;
624 default:
625 break;
626 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700627
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700628 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700629 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
630
631 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700632 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700633 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
634 i = static_cast<size_t>(gc_type_ran);
635 self->TransitionFromSuspendedToRunnable();
636
637 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700638 ptr = TryToAllocate(space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700639 if (ptr != NULL) {
640 return ptr;
641 }
642 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700643 }
644
645 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700646 // Try harder, growing the heap if necessary.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700647 ptr = TryToAllocate(space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700648 if (ptr != NULL) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700649 if (space != NULL) {
650 size_t new_footprint = space->GetFootprintLimit();
651 // OLD-TODO: may want to grow a little bit more so that the amount of
652 // free space is equal to the old free space + the
653 // utilization slop for the new allocation.
654 VLOG(gc) << "Grow alloc space (frag case) to " << PrettySize(new_footprint)
655 << " for a " << PrettySize(alloc_size) << " allocation";
656 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700657 return ptr;
658 }
659
Elliott Hughes81ff3182012-03-23 20:35:56 -0700660 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
661 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
662 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700663
Elliott Hughes418dfe72011-10-06 18:56:27 -0700664 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700665 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
666 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700667
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700668 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700669 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700670 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671 self->TransitionFromSuspendedToRunnable();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700672 return TryToAllocate(space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700673}
674
Elliott Hughesbf86d042011-08-31 17:53:14 -0700675int64_t Heap::GetMaxMemory() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700676 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700677}
678
679int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700680 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700681}
682
683int64_t Heap::GetFreeMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700684 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700685}
686
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700687class InstanceCounter {
688 public:
689 InstanceCounter(Class* c, bool count_assignable)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700690 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700691 : class_(c), count_assignable_(count_assignable), count_(0) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700692
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700693 }
694
695 size_t GetCount() {
696 return count_;
697 }
698
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700699 static void Callback(Object* o, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700700 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700701 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
702 }
703
704 private:
Ian Rogersb726dcb2012-09-05 08:57:23 -0700705 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700706 Class* instance_class = o->GetClass();
707 if (count_assignable_) {
708 if (instance_class == class_) {
709 ++count_;
710 }
711 } else {
712 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
713 ++count_;
714 }
715 }
716 }
717
718 Class* class_;
719 bool count_assignable_;
720 size_t count_;
721};
722
723int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700724 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700725 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700726 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700727 return counter.GetCount();
728}
729
Ian Rogers30fab402012-01-23 15:43:46 -0800730void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700731 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
732 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700733 Thread* self = Thread::Current();
734 WaitForConcurrentGcToComplete(self);
735 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700736 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
737 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700738}
739
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700740void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700741 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700742 Thread* self = Thread::Current();
743 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700744
745 // Try to see if we have any Zygote spaces.
746 if (have_zygote_space_) {
747 return;
748 }
749
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700750 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
751
752 {
753 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700754 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700755 FlushAllocStack();
756 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700757
758 // Replace the first alloc space we find with a zygote space.
759 // TODO: C++0x auto
760 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
761 if ((*it)->IsAllocSpace()) {
762 AllocSpace* zygote_space = (*it)->AsAllocSpace();
763
764 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
765 // of the remaining available heap memory.
766 alloc_space_ = zygote_space->CreateZygoteSpace();
767
768 // Change the GC retention policy of the zygote space to only collect when full.
769 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
770 AddSpace(alloc_space_);
771 have_zygote_space_ = true;
772 break;
773 }
774 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700775
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700776 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700777 // TODO: C++0x
778 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
779 it != cumulative_timings_.end(); ++it) {
780 it->second->Reset();
781 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700782}
783
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700784void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700785 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
786 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700787 allocation_stack_->Reset();
788}
789
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700790size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700791 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700792}
793
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700794void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700795 const size_t count = stack->Size();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700796 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700797 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700798 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700799 if (LIKELY(bitmap->HasAddress(obj))) {
800 bitmap->Set(obj);
801 } else {
802 large_objects->Set(obj);
803 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700804 }
805}
806
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700807void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700808 size_t count = stack->Size();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700809 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700810 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700811 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700812 if (LIKELY(bitmap->HasAddress(obj))) {
813 bitmap->Clear(obj);
814 } else {
815 large_objects->Clear(obj);
816 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700817 }
818}
819
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700820GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700821 Thread* self = Thread::Current();
822 Locks::mutator_lock_->AssertNotHeld(self);
823 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700824
Ian Rogers120f1c72012-09-28 17:17:10 -0700825 if (self->IsHandlingStackOverflow()) {
826 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
827 }
828
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700829 // Ensure there is only one GC at a time.
830 bool start_collect = false;
831 while (!start_collect) {
832 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700833 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700834 if (!is_gc_running_) {
835 is_gc_running_ = true;
836 start_collect = true;
837 }
838 }
839 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700840 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700841 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
842 // Not doing at the moment to ensure soft references are cleared.
843 }
844 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700845 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700846
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700847 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
848 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
849 ++Thread::Current()->GetStats()->gc_for_alloc_count;
850 }
851
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700852 // We need to do partial GCs every now and then to avoid the heap growing too much and
853 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700854 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700855 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700856 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700857 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700858 sticky_gc_count_ = 0;
859 }
860
Mathieu Chartier637e3482012-08-17 10:41:32 -0700861 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700862 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700863 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700864 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700865 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700866 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700867
Ian Rogers15bf2d32012-08-28 17:33:04 -0700868 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700869 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700870 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700871 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700872 // Wake anyone who may have been waiting for the GC to complete.
873 gc_complete_cond_->Broadcast();
874 }
875 // Inform DDMS that a GC completed.
876 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700877 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700878}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700879
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700880void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
881 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700882 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700883
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700884 std::stringstream gc_type_str;
885 gc_type_str << gc_type << " ";
886
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700887 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700888 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700889 ThreadList* thread_list = Runtime::Current()->GetThreadList();
890 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700891 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700892 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700893
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700894 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700895 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700896 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700897 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700898
899 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700900 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700901
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700902 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700903 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700904 if (!VerifyHeapReferences()) {
905 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
906 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700907 timings.AddSplit("VerifyHeapReferencesPreGC");
908 }
909
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700910 // Make sure that the tables have the correct pointer for the mark sweep.
911 mod_union_table_->Init(&mark_sweep);
912 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700913
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700914 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700915 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700916
917 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
918 // TODO: Investigate using a mark stack instead of a vector.
919 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700920 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700921 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
922 card_table_->GetDirtyCards(*it, dirty_cards);
923 }
924 }
925
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700926 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700927 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700928 ContinuousSpace* space = *it;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700929 if (space->IsImageSpace()) {
930 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700931 timings.AddSplit("ClearModUnionCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700932 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
933 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700934 timings.AddSplit("ClearZygoteCards");
935 } else {
936 card_table_->ClearSpaceCards(space);
937 timings.AddSplit("ClearCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700938 }
939 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700940
Ian Rogers120f1c72012-09-28 17:17:10 -0700941 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700942 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700943 // Copy the mark bits over from the live bits, do this as early as possible or else we can
944 // accidentally un-mark roots.
945 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700946 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700947 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
948 mark_sweep.CopyMarkBits(*it);
949 }
950 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700951 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700952
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700953 // We can assume that everything from the start of the first space to the alloc space is marked.
954 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
955 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700956 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700957 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700958 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
959 mark_sweep.CopyMarkBits(*it);
960 }
961 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700962 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700963 timings.AddSplit("CopyMarkBits");
964
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700965 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
966 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700967 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700968
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700969 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
970 live_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700971
Mathieu Chartier0325e622012-09-05 14:22:51 -0700972 if (gc_type != kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700973 live_stack_->Reset();
974 }
975
Carl Shapiro58551df2011-07-24 03:09:51 -0700976 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700977 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700978
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700979 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -0700980 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700981
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700982 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700983
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700984 if (verify_mod_union_table_) {
985 zygote_mod_union_table_->Update();
986 zygote_mod_union_table_->Verify();
987 mod_union_table_->Update();
988 mod_union_table_->Verify();
989 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700990
991 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700992 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700993 live_stack_->Reset();
Mathieu Chartier0325e622012-09-05 14:22:51 -0700994 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700995 } else {
996 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
997 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700998 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -0700999
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001000 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001001 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001002 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001003
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001004 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1005 mark_sweep.SweepSystemWeaks(false);
1006 timings.AddSplit("SweepSystemWeaks");
1007
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001008 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001009 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001010 SwapBitmaps(self);
Mathieu Chartier654d3a22012-07-11 17:54:18 -07001011 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001012
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001013#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001014 // Verify that we only reach marked objects from the image space
1015 mark_sweep.VerifyImageRoots();
1016 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001017#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001018
Mathieu Chartier0325e622012-09-05 14:22:51 -07001019 if (gc_type != kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001020 mark_sweep.SweepLargeObjects(swap);
1021 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001022 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001023 } else {
1024 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001025 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001026 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001027
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001028 if (verify_system_weaks_) {
1029 mark_sweep.VerifySystemWeaks();
1030 timings.AddSplit("VerifySystemWeaks");
1031 }
1032
Elliott Hughesadb460d2011-10-05 17:02:34 -07001033 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001034 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001035 }
1036
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001037 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001038 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001039 if (!VerifyHeapReferences()) {
1040 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1041 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001042 timings.AddSplit("VerifyHeapReferencesPostGC");
1043 }
1044
Carl Shapiro58551df2011-07-24 03:09:51 -07001045 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001046 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001047
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001048 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001049 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001050
1051 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001052 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001053 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001054
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001055 // If the GC was slow, then print timings in the log.
1056 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1057 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001058 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001059 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001060 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001061 LOG(INFO) << gc_cause << " " << gc_type_str.str() << " "
Mathieu Chartier637e3482012-08-17 10:41:32 -07001062 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001063 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001064 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001065 if (VLOG_IS_ON(heap)) {
1066 timings.Dump();
1067 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001068 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001069
Mathieu Chartier0325e622012-09-05 14:22:51 -07001070 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1071 logger->Start();
1072 logger->AddLogger(timings);
1073 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001074}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001075
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001076void Heap::UpdateAndMarkModUnion(TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001077 if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001078 // Don't need to do anythign for mod union table in this case since we are only scanning dirty
1079 // cards.
1080 return;
1081 }
1082
1083 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001084 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001085 zygote_mod_union_table_->Update();
1086 timings.AddSplit("UpdateZygoteModUnionTable");
1087
1088 zygote_mod_union_table_->MarkReferences();
1089 timings.AddSplit("ZygoteMarkReferences");
1090 }
1091
1092 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1093 mod_union_table_->Update();
1094 timings.AddSplit("UpdateModUnionTable");
1095
1096 // Scans all objects in the mod-union table.
1097 mod_union_table_->MarkReferences();
1098 timings.AddSplit("MarkImageToAllocSpaceReferences");
1099}
1100
1101void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1102 Object* obj = reinterpret_cast<Object*>(arg);
1103 if (root == obj) {
1104 LOG(INFO) << "Object " << obj << " is a root";
1105 }
1106}
1107
1108class ScanVisitor {
1109 public:
1110 void operator ()(const Object* obj) const {
1111 LOG(INFO) << "Would have rescanned object " << obj;
1112 }
1113};
1114
1115class VerifyReferenceVisitor {
1116 public:
1117 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001118 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1119 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001120 : heap_(heap),
1121 failed_(failed) {
1122 }
1123
1124 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1125 // analysis.
1126 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1127 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1128 // Verify that the reference is live.
1129 if (ref != NULL && !IsLive(ref)) {
1130 CardTable* card_table = heap_->GetCardTable();
1131 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1132 MarkStack* live_stack = heap_->live_stack_.get();
1133
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001134 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001135 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " on IsDirty = "
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001136 << (*card_addr == GC_CARD_DIRTY);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001137 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1138 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1139 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001140 void* cover_begin = card_table->AddrFromCard(card_addr);
1141 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1142 GC_CARD_SIZE);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001143 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001144 << "-" << cover_end;
1145 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1146
1147 // Print out how the object is live.
1148 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001149 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1150 }
1151
1152 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1153 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1154 }
1155
1156 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1157 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001158 }
1159
1160 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001161 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001162 }
1163
1164 // Attempt to see if the card table missed the reference.
1165 ScanVisitor scan_visitor;
1166 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1167 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + GC_CARD_SIZE, scan_visitor,
1168 IdentityFunctor());
1169
1170 // Try and see if a mark sweep collector scans the reference.
1171 MarkStack* mark_stack = heap_->mark_stack_.get();
1172 MarkSweep ms(mark_stack);
1173 ms.Init();
1174 mark_stack->Reset();
1175 ms.SetFinger(reinterpret_cast<Object*>(~size_t(0)));
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001176
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001177 // All the references should end up in the mark stack.
1178 ms.ScanRoot(obj);
1179 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001180 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001181 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001182 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001183 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001184 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001185 }
1186 }
1187 mark_stack->Reset();
1188
1189 // Search to see if any of the roots reference our object.
1190 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1191 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1192 *failed_ = true;
1193 }
1194 }
1195
1196 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1197 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1198 if (bitmap != NULL) {
1199 if (bitmap->Test(obj)) {
1200 return true;
1201 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001202 } else if (heap_->GetLargeObjectsSpace()->GetLiveObjects()->Test(obj)) {
1203 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001204 } else {
1205 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001206 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001207 }
1208 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1209 // At this point we need to search the allocation since things in the live stack may get swept.
1210 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1211 return true;
1212 }
1213 // Not either in the live bitmap or allocation stack, so the object must be dead.
1214 return false;
1215 }
1216
1217 private:
1218 Heap* heap_;
1219 bool* failed_;
1220};
1221
1222class VerifyObjectVisitor {
1223 public:
1224 VerifyObjectVisitor(Heap* heap)
1225 : heap_(heap),
1226 failed_(false) {
1227
1228 }
1229
1230 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001231 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001232 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1233 MarkSweep::VisitObjectReferences(obj, visitor);
1234 }
1235
1236 bool Failed() const {
1237 return failed_;
1238 }
1239
1240 private:
1241 Heap* heap_;
1242 bool failed_;
1243};
1244
1245// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001246bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001247 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001248 // Lets sort our allocation stacks so that we can efficiently binary search them.
1249 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1250 std::sort(live_stack_->Begin(), live_stack_->End());
1251 // Perform the verification.
1252 VerifyObjectVisitor visitor(this);
1253 GetLiveBitmap()->Visit(visitor);
1254 // We don't want to verify the objects in the allocation stack since they themselves may be
1255 // pointing to dead objects if they are not reachable.
1256 if (visitor.Failed()) {
1257 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001258 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001259 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001260 return true;
1261}
1262
1263class VerifyReferenceCardVisitor {
1264 public:
1265 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1266 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1267 Locks::heap_bitmap_lock_)
1268 : heap_(heap),
1269 failed_(failed) {
1270 }
1271
1272 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1273 // analysis.
1274 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1275 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
1276 if (ref != NULL) {
1277 CardTable* card_table = heap_->GetCardTable();
1278 // If the object is not dirty and it is referencing something in the live stack other than
1279 // class, then it must be on a dirty card.
1280 if (!card_table->IsDirty(obj)) {
1281 MarkStack* live_stack = heap_->live_stack_.get();
1282 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1283 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1284 LOG(ERROR) << "Object " << obj << " found in live stack";
1285 }
1286 if (heap_->GetLiveBitmap()->Test(obj)) {
1287 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1288 }
1289 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1290 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1291
1292 // Print which field of the object is dead.
1293 if (!obj->IsObjectArray()) {
1294 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1295 CHECK(klass != NULL);
1296 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1297 CHECK(fields != NULL);
1298 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1299 const Field* cur = fields->Get(i);
1300 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1301 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1302 << PrettyField(cur);
1303 break;
1304 }
1305 }
1306 } else {
1307 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1308 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1309 if (object_array->Get(i) == ref) {
1310 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1311 }
1312 }
1313 }
1314
1315 *failed_ = true;
1316 }
1317 }
1318 }
1319 }
1320
1321 private:
1322 Heap* heap_;
1323 bool* failed_;
1324};
1325
1326class VerifyLiveStackReferences {
1327 public:
1328 VerifyLiveStackReferences(Heap* heap)
1329 : heap_(heap),
1330 failed_(false) {
1331
1332 }
1333
1334 void operator ()(const Object* obj) const
1335 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1336 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1337 MarkSweep::VisitObjectReferences(obj, visitor);
1338 }
1339
1340 bool Failed() const {
1341 return failed_;
1342 }
1343
1344 private:
1345 Heap* heap_;
1346 bool failed_;
1347};
1348
1349bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001350 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001351
1352 VerifyLiveStackReferences visitor(this);
1353 GetLiveBitmap()->Visit(visitor);
1354
1355 // We can verify objects in the live stack since none of these should reference dead objects.
1356 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1357 visitor(*it);
1358 }
1359
1360 if (visitor.Failed()) {
1361 DumpSpaces();
1362 return false;
1363 }
1364 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001365}
1366
Ian Rogers81d425b2012-09-27 16:03:43 -07001367void Heap::SwapBitmaps(Thread* self) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001368 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1369 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1370 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
1371 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
Ian Rogers81d425b2012-09-27 16:03:43 -07001372 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001373 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001374 ContinuousSpace* space = *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001375 // We never allocate into zygote spaces.
1376 if (space->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1377 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1378 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1379 space->AsAllocSpace()->SwapBitmaps();
1380 }
1381 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001382
1383 large_object_space_->SwapBitmaps();
1384 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1385 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001386}
1387
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001388void Heap::SwapStacks() {
1389 MarkStack* temp = allocation_stack_.release();
1390 allocation_stack_.reset(live_stack_.release());
1391 live_stack_.reset(temp);
1392
1393 // Sort the live stack so that we can quickly binary search it later.
1394 if (VERIFY_OBJECT_ENABLED) {
1395 std::sort(live_stack_->Begin(), live_stack_->End());
1396 }
1397}
1398
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001399void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1400 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001401 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1402 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001403 std::stringstream gc_type_str;
1404 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001405
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001406 // Suspend all threads are get exclusive access to the heap.
1407 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1408 thread_list->SuspendAll();
1409 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001410 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001411
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001412 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001413 Object* cleared_references = NULL;
1414 {
1415 MarkSweep mark_sweep(mark_stack_.get());
1416 timings.AddSplit("ctor");
1417
1418 mark_sweep.Init();
1419 timings.AddSplit("Init");
1420
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001421 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001422 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001423 if (!VerifyHeapReferences()) {
1424 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1425 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001426 timings.AddSplit("VerifyHeapReferencesPreGC");
1427 }
1428
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001429 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1430 SwapStacks();
1431
1432 // Check that all objects which reference things in the live stack are on dirty cards.
1433 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001434 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001435 // Sort the live stack so that we can quickly binary search it later.
1436 std::sort(live_stack_->Begin(), live_stack_->End());
1437 if (!VerifyMissingCardMarks()) {
1438 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1439 }
1440 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001441
1442 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1443 // TODO: Investigate using a mark stack instead of a vector.
1444 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001445 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001446 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1447 card_table_->GetDirtyCards(*it, dirty_cards);
1448 }
1449 }
1450
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001451 // Make sure that the tables have the correct pointer for the mark sweep.
1452 mod_union_table_->Init(&mark_sweep);
1453 zygote_mod_union_table_->Init(&mark_sweep);
1454
1455 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1456 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001457 ContinuousSpace* space = *it;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001458 if (space->IsImageSpace()) {
1459 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001460 timings.AddSplit("ModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001461 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1462 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001463 timings.AddSplit("ZygoteModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001464 } else {
1465 card_table_->ClearSpaceCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001466 timings.AddSplit("ClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001467 }
1468 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001469
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001470 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001471 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001472
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001473 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1474 CHECK(!GetLiveBitmap()->Test(*it));
1475 }
1476
Mathieu Chartier0325e622012-09-05 14:22:51 -07001477 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001478 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1479 // accidentally un-mark roots.
1480 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001481 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001482 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1483 mark_sweep.CopyMarkBits(*it);
1484 }
1485 }
1486 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001487 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1488 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001489 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001490 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001491 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1492 mark_sweep.CopyMarkBits(*it);
1493 }
1494 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001495 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001496 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001497 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1498 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001499 }
1500
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001501 // Marking roots is not necessary for sticky mark bits since we only actually require the
1502 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001503 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001504 mark_sweep.MarkRoots();
1505 timings.AddSplit("MarkRoots");
1506 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001507
1508 if (verify_mod_union_table_) {
1509 zygote_mod_union_table_->Update();
1510 zygote_mod_union_table_->Verify();
1511 mod_union_table_->Update();
1512 mod_union_table_->Verify();
1513 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001514 }
1515
1516 // Roots are marked on the bitmap and the mark_stack is empty.
1517 DCHECK(mark_sweep.IsMarkStackEmpty());
1518
1519 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1520 thread_list->ResumeAll();
1521 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001522 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001523 root_end = NanoTime();
1524 timings.AddSplit("RootEnd");
1525
Ian Rogers81d425b2012-09-27 16:03:43 -07001526 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001527 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001528
1529 // Mark everything as live so that sweeping system weak works correctly for sticky mark bit
1530 // GCs.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001531 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1532 live_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001533 timings.AddSplit("MarkStackAsLive");
1534
Mathieu Chartier0325e622012-09-05 14:22:51 -07001535 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001536 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001537 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001538 } else {
1539 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001541 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001542 }
1543 // Release share on mutator_lock_ and then get exclusive access.
1544 dirty_begin = NanoTime();
1545 thread_list->SuspendAll();
1546 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001547 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001548
1549 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001550 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001551
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001552 // Re-mark root set.
1553 mark_sweep.ReMarkRoots();
1554 timings.AddSplit("ReMarkRoots");
1555
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001556 if (verify_missing_card_marks_) {
1557 // Since verify missing card marks uses a sweep array to empty the allocation stack, we
1558 // need to make sure that we don't free weaks which wont get swept by SweepSystemWeaks.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001559 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1560 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001561 }
1562
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001563 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001564 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001565 timings.AddSplit("RecursiveMarkDirtyObjects");
1566 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001567
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001568 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001569 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001570
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001571 mark_sweep.ProcessReferences(clear_soft_references);
1572 timings.AddSplit("ProcessReferences");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001573
1574 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1575 mark_sweep.SweepSystemWeaks(false);
1576 timings.AddSplit("SweepSystemWeaks");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001577 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001578
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001579 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1580 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1581 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1582 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001583 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001584 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001585 SwapBitmaps(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001586 }
1587
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001588 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1589 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001590 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001591 mark_sweep.SweepArray(timings, allocation_stack_.get(), swap);
1592 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001593 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001594 // We only sweep over the live stack, and the live stack should not intersect with the
1595 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001596 UnMarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1597 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001598 timings.AddSplit("UnMarkAllocStack");
1599 }
1600
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001601 if (kIsDebugBuild) {
1602 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001603 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001604 mark_sweep.VerifyImageRoots();
1605 timings.AddSplit("VerifyImageRoots");
1606 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001607
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001608 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001609 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001610 if (!VerifyHeapReferences()) {
1611 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
1612 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001613 timings.AddSplit("VerifyHeapReferencesPostGC");
1614 }
1615
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001616 thread_list->ResumeAll();
1617 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001618 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001619
1620 {
1621 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001622 if (gc_type != kGcTypeSticky) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001623 WriterMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001624 mark_sweep.SweepLargeObjects(swap);
1625 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001626 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001627 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001628 WriterMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001629 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001630 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001631 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001632 live_stack_->Reset();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001633 timings.AddSplit("Sweep");
1634 }
1635
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001636 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001637 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001638 mark_sweep.VerifySystemWeaks();
1639 timings.AddSplit("VerifySystemWeaks");
1640 }
1641
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001642 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001643 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001644 }
1645
1646 GrowForUtilization();
1647 timings.AddSplit("GrowForUtilization");
1648
1649 EnqueueClearedReferences(&cleared_references);
1650 RequestHeapTrim();
1651 timings.AddSplit("Finish");
1652
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001653 // If the GC was slow, then print timings in the log.
1654 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1655 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001656 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001657 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001658 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001659 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001660 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001661 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001662 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001663 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001664 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1665 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001666 if (VLOG_IS_ON(heap)) {
1667 timings.Dump();
1668 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001669 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001670
Mathieu Chartier0325e622012-09-05 14:22:51 -07001671 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1672 logger->Start();
1673 logger->AddLogger(timings);
1674 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001675}
1676
Ian Rogers81d425b2012-09-27 16:03:43 -07001677GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001678 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001679 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001680 bool do_wait;
1681 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001682 {
1683 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001684 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001685 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001686 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001687 if (do_wait) {
1688 // We must wait, change thread state then sleep on gc_complete_cond_;
1689 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1690 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001691 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001692 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001693 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001694 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001695 last_gc_type = last_gc_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001696 }
1697 uint64_t wait_time = NanoTime() - wait_start;
1698 if (wait_time > MsToNs(5)) {
1699 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1700 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001701 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001702 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001703 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001704}
1705
Elliott Hughesc967f782012-04-16 10:23:15 -07001706void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001707 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1708 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier0325e622012-09-05 14:22:51 -07001709 // Dump cumulative timings.
1710 LOG(INFO) << "Dumping cumulative Gc timings";
1711 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
1712 it != cumulative_timings_.end(); ++it) {
1713 it->second->Dump();
1714 }
Elliott Hughesc967f782012-04-16 10:23:15 -07001715}
1716
1717size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001718 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001719}
1720
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001721void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001722 AllocSpace* alloc_space = alloc_space_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001723 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001724 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001725 << PrettySize(GetMaxMemory());
1726 max_allowed_footprint = GetMaxMemory();
1727 }
1728 // We want to update the footprint for just the alloc space.
1729 max_allowed_footprint -= large_object_space_->GetNumBytesAllocated();
1730 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1731 if ((*it)->IsAllocSpace()) {
1732 AllocSpace* alloc_space = (*it)->AsAllocSpace();
1733 if (alloc_space != alloc_space_) {
1734 max_allowed_footprint -= alloc_space->GetNumBytesAllocated();
1735 }
1736 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001737 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001738 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001739}
1740
Ian Rogers3bb17a62012-01-27 23:56:44 -08001741// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001742static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001743// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1744// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001745static const size_t kHeapMinFree = kHeapIdealFree / 4;
1746
Carl Shapiro69759ea2011-07-21 18:13:35 -07001747void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001748 // We know what our utilization is at this moment.
1749 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1750 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
1751 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1752 target_size = num_bytes_allocated_ + kHeapIdealFree;
1753 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1754 target_size = num_bytes_allocated_ + kHeapMinFree;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001755 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001756
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001757 // Calculate when to perform the next ConcurrentGC.
1758 if (GetFreeMemory() < concurrent_min_free_) {
1759 // Not enough free memory to perform concurrent GC.
1760 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1761 } else {
1762 // Start a concurrent Gc when we get close to the target size.
1763 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001764 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001765
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001766 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001767}
1768
jeffhaoc1160702011-10-27 15:48:45 -07001769void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001770 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001771 alloc_space_->ClearGrowthLimit();
1772}
1773
Elliott Hughesadb460d2011-10-05 17:02:34 -07001774void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001775 MemberOffset reference_queue_offset,
1776 MemberOffset reference_queueNext_offset,
1777 MemberOffset reference_pendingNext_offset,
1778 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001779 reference_referent_offset_ = reference_referent_offset;
1780 reference_queue_offset_ = reference_queue_offset;
1781 reference_queueNext_offset_ = reference_queueNext_offset;
1782 reference_pendingNext_offset_ = reference_pendingNext_offset;
1783 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1784 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1785 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1786 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1787 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1788 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1789}
1790
1791Object* Heap::GetReferenceReferent(Object* reference) {
1792 DCHECK(reference != NULL);
1793 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1794 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1795}
1796
1797void Heap::ClearReferenceReferent(Object* reference) {
1798 DCHECK(reference != NULL);
1799 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1800 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1801}
1802
1803// Returns true if the reference object has not yet been enqueued.
1804bool Heap::IsEnqueuable(const Object* ref) {
1805 DCHECK(ref != NULL);
1806 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1807 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1808 return (queue != NULL) && (queue_next == NULL);
1809}
1810
1811void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1812 DCHECK(ref != NULL);
1813 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1814 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1815 EnqueuePendingReference(ref, cleared_reference_list);
1816}
1817
1818void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1819 DCHECK(ref != NULL);
1820 DCHECK(list != NULL);
1821
1822 if (*list == NULL) {
1823 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1824 *list = ref;
1825 } else {
1826 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1827 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1828 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1829 }
1830}
1831
1832Object* Heap::DequeuePendingReference(Object** list) {
1833 DCHECK(list != NULL);
1834 DCHECK(*list != NULL);
1835 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1836 Object* ref;
1837 if (*list == head) {
1838 ref = *list;
1839 *list = NULL;
1840 } else {
1841 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1842 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1843 ref = head;
1844 }
1845 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1846 return ref;
1847}
1848
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001849void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001850 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001851 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001852 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001853 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1854 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001855}
1856
1857size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001858 return num_bytes_allocated_;
1859}
1860
1861size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001862 size_t total = 0;
1863 // TODO: C++0x
1864 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1865 Space* space = *it;
1866 if (space->IsAllocSpace()) {
1867 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1868 }
1869 }
1870 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001871}
1872
1873size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001874 return concurrent_start_size_;
1875}
1876
1877size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001878 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001879}
1880
1881void Heap::EnqueueClearedReferences(Object** cleared) {
1882 DCHECK(cleared != NULL);
1883 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001884 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001885 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001886 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001887 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1888 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001889 *cleared = NULL;
1890 }
1891}
1892
Ian Rogers1f539342012-10-03 21:09:42 -07001893void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001894 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001895 Runtime* runtime = Runtime::Current();
1896 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1897 !runtime->IsConcurrentGcEnabled()) {
1898 return;
1899 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001900 {
1901 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1902 if (runtime->IsShuttingDown()) {
1903 return;
1904 }
1905 }
1906 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001907 return;
1908 }
1909
1910 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001911 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001912 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1913 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001914 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1915 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001916 CHECK(!env->ExceptionCheck());
1917 requesting_gc_ = false;
1918}
1919
Ian Rogers81d425b2012-09-27 16:03:43 -07001920void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001921 {
1922 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1923 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
1924 return;
1925 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001926 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001927
Ian Rogers81d425b2012-09-27 16:03:43 -07001928 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001929 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07001930 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001931 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001932 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001933 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001934 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001935 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001936 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001937}
1938
Ian Rogers81d425b2012-09-27 16:03:43 -07001939void Heap::Trim(Thread* self) {
1940 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001941 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001942}
1943
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001944void Heap::RequestHeapTrim() {
1945 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1946 // because that only marks object heads, so a large array looks like lots of empty space. We
1947 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1948 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1949 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1950 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001951 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001952 float utilization =
1953 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1954 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1955 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1956 // heap trim occurred in the last two seconds.
1957 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001958 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001959
1960 Thread* self = Thread::Current();
1961 {
1962 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1963 Runtime* runtime = Runtime::Current();
1964 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1965 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1966 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1967 // as we don't hold the lock while requesting the trim).
1968 return;
1969 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001970 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001971 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001972 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001973 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1974 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001975 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1976 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001977 CHECK(!env->ExceptionCheck());
1978}
1979
Carl Shapiro69759ea2011-07-21 18:13:35 -07001980} // namespace art