blob: f7cb68d05d1e04cd45b26eb60078c52def04c396 [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 Rogers50b35e22012-10-04 10:09:15 -0700280 WriterMutexLock mu(Thread::Current(), *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
Ian Rogers50b35e22012-10-04 10:09:15 -0700360Object* Heap::AllocObject(Thread* self, 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);
Ian Rogers50b35e22012-10-04 10:09:15 -0700375 obj = Allocate(self, 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 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700384 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700385 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 SirtRef<Object> ref(self, obj);
409 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700410 }
411 VerifyObject(obj);
412
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700413 return obj;
414 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700415 int64_t total_bytes_free = GetFreeMemory();
416 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700417 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700418 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
419 if ((*it)->IsAllocSpace()) {
420 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700421 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700422 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700423
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700424 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 -0700425 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700426 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700427 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700428}
429
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700430bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700431 // Note: we deliberately don't take the lock here, and mustn't test anything that would
432 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700433 if (obj == NULL) {
434 return true;
435 }
436 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700437 return false;
438 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800439 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800440 if (spaces_[i]->Contains(obj)) {
441 return true;
442 }
443 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700444 // TODO: Find a way to check large object space without using a lock.
445 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700446}
447
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700448bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700449 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700450 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700451}
452
Elliott Hughes3e465b12011-09-02 18:26:12 -0700453#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700455 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700456 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700457 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700458 return;
459 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700460 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700461}
462#endif
463
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700464void Heap::DumpSpaces() {
465 // TODO: C++0x auto
466 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700467 ContinuousSpace* space = *it;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700468 LOG(INFO) << *space << "\n"
469 << *space->GetLiveBitmap() << "\n"
470 << *space->GetMarkBitmap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700471 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700472 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700473}
474
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700475void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700476 if (!IsAligned<kObjectAlignment>(obj)) {
477 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700478 }
479
Mathieu Chartier0325e622012-09-05 14:22:51 -0700480 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700481 // Check the allocation stack / live stack.
482 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
483 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
484 allocation_stack_->End()) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700485 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700486 if (large_object_space_->GetLiveObjects()->Test(obj)) {
487 DumpSpaces();
488 LOG(FATAL) << "Object is dead: " << obj;
489 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700490 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700491 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700492
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700493 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700494 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700495 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
496 Object::ClassOffset().Int32Value();
497 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
498 if (c == NULL) {
499 LOG(FATAL) << "Null class in object: " << obj;
500 } else if (!IsAligned<kObjectAlignment>(c)) {
501 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
502 } else if (!GetLiveBitmap()->Test(c)) {
503 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
504 }
505 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
506 // Note: we don't use the accessors here as they have internal sanity checks
507 // that we don't want to run
508 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
509 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
510 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
511 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
512 CHECK_EQ(c_c, c_c_c);
513 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700514}
515
Brian Carlstrom78128a62011-09-15 17:21:19 -0700516void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700518 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700519}
520
521void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700522 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700523 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700524}
525
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700526void Heap::RecordAllocation(size_t size, const Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700527 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700528 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700529 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700530
531 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700532 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700533 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700534 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700535
536 // TODO: Update these atomically.
537 RuntimeStats* global_stats = Runtime::Current()->GetStats();
538 ++global_stats->allocated_objects;
539 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700540 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700541
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700542 allocation_stack_->AtomicPush(obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700543}
544
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700545void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier637e3482012-08-17 10:41:32 -0700546 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
547 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700548 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
549 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700550
551 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700552 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700553 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700554 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700555
556 // TODO: Do this concurrently.
557 RuntimeStats* global_stats = Runtime::Current()->GetStats();
558 global_stats->freed_objects += freed_objects;
559 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700560 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700561}
562
Ian Rogers50b35e22012-10-04 10:09:15 -0700563Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700564 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
565 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
566 return NULL;
567 }
568
Mathieu Chartier83cf3282012-09-26 17:54:27 -0700569 if (UNLIKELY(space == NULL)) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700570 return large_object_space_->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700571 } else if (grow) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700572 return space->AllocWithGrowth(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700573 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700574 return space->AllocWithoutGrowth(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700575 }
576}
577
Ian Rogers50b35e22012-10-04 10:09:15 -0700578Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700579 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
580 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700581 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700582 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700583
Ian Rogers50b35e22012-10-04 10:09:15 -0700584 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700585 if (ptr != NULL) {
586 return ptr;
587 }
588
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700589 // The allocation failed. If the GC is running, block until it completes, and then retry the
590 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700591 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700592 if (last_gc != kGcTypeNone) {
593 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700594 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700595 if (ptr != NULL) {
596 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700597 }
598 }
599
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700600 // Loop through our different Gc types and try to Gc until we get enough free memory.
601 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
602 bool run_gc = false;
603 GcType gc_type = static_cast<GcType>(i);
604 switch (gc_type) {
605 case kGcTypeSticky: {
606 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700607 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
608 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700609 break;
610 }
611 case kGcTypePartial:
612 run_gc = have_zygote_space_;
613 break;
614 case kGcTypeFull:
615 run_gc = true;
616 break;
617 default:
618 break;
619 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700620
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700621 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700622 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
623
624 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700625 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700626 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
627 i = static_cast<size_t>(gc_type_ran);
628 self->TransitionFromSuspendedToRunnable();
629
630 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700631 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700632 if (ptr != NULL) {
633 return ptr;
634 }
635 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700636 }
637
638 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700639 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700640 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700641 if (ptr != NULL) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700642 if (space != NULL) {
643 size_t new_footprint = space->GetFootprintLimit();
644 // OLD-TODO: may want to grow a little bit more so that the amount of
645 // free space is equal to the old free space + the
646 // utilization slop for the new allocation.
647 VLOG(gc) << "Grow alloc space (frag case) to " << PrettySize(new_footprint)
648 << " for a " << PrettySize(alloc_size) << " allocation";
649 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700650 return ptr;
651 }
652
Elliott Hughes81ff3182012-03-23 20:35:56 -0700653 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
654 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
655 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700656
Elliott Hughes418dfe72011-10-06 18:56:27 -0700657 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700658 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
659 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700660
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700661 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700662 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700663 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700665 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700666}
667
Elliott Hughesbf86d042011-08-31 17:53:14 -0700668int64_t Heap::GetMaxMemory() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700669 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700670}
671
672int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700673 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700674}
675
676int64_t Heap::GetFreeMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700677 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700678}
679
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700680class InstanceCounter {
681 public:
682 InstanceCounter(Class* c, bool count_assignable)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700683 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700684 : class_(c), count_assignable_(count_assignable), count_(0) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700685
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700686 }
687
688 size_t GetCount() {
689 return count_;
690 }
691
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692 static void Callback(Object* o, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700693 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700694 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
695 }
696
697 private:
Ian Rogersb726dcb2012-09-05 08:57:23 -0700698 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700699 Class* instance_class = o->GetClass();
700 if (count_assignable_) {
701 if (instance_class == class_) {
702 ++count_;
703 }
704 } else {
705 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
706 ++count_;
707 }
708 }
709 }
710
711 Class* class_;
712 bool count_assignable_;
713 size_t count_;
714};
715
716int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700717 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700718 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700719 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700720 return counter.GetCount();
721}
722
Ian Rogers30fab402012-01-23 15:43:46 -0800723void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700724 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
725 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700726 Thread* self = Thread::Current();
727 WaitForConcurrentGcToComplete(self);
728 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700729 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
730 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700731}
732
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700733void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700734 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700735 Thread* self = Thread::Current();
736 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700737
738 // Try to see if we have any Zygote spaces.
739 if (have_zygote_space_) {
740 return;
741 }
742
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700743 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
744
745 {
746 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700747 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700748 FlushAllocStack();
749 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700750
751 // Replace the first alloc space we find with a zygote space.
752 // TODO: C++0x auto
753 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
754 if ((*it)->IsAllocSpace()) {
755 AllocSpace* zygote_space = (*it)->AsAllocSpace();
756
757 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
758 // of the remaining available heap memory.
759 alloc_space_ = zygote_space->CreateZygoteSpace();
760
761 // Change the GC retention policy of the zygote space to only collect when full.
762 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
763 AddSpace(alloc_space_);
764 have_zygote_space_ = true;
765 break;
766 }
767 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700768
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700769 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700770 // TODO: C++0x
771 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
772 it != cumulative_timings_.end(); ++it) {
773 it->second->Reset();
774 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700775}
776
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700777void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700778 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
779 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700780 allocation_stack_->Reset();
781}
782
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700783size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700784 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700785}
786
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700787void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700788 const size_t count = stack->Size();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700789 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700790 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700791 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700792 if (LIKELY(bitmap->HasAddress(obj))) {
793 bitmap->Set(obj);
794 } else {
795 large_objects->Set(obj);
796 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700797 }
798}
799
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700800void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700801 size_t count = stack->Size();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700802 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700803 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700804 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700805 if (LIKELY(bitmap->HasAddress(obj))) {
806 bitmap->Clear(obj);
807 } else {
808 large_objects->Clear(obj);
809 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700810 }
811}
812
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700813GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700814 Thread* self = Thread::Current();
815 Locks::mutator_lock_->AssertNotHeld(self);
816 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700817
Ian Rogers120f1c72012-09-28 17:17:10 -0700818 if (self->IsHandlingStackOverflow()) {
819 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
820 }
821
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700822 // Ensure there is only one GC at a time.
823 bool start_collect = false;
824 while (!start_collect) {
825 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700826 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700827 if (!is_gc_running_) {
828 is_gc_running_ = true;
829 start_collect = true;
830 }
831 }
832 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700833 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700834 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
835 // Not doing at the moment to ensure soft references are cleared.
836 }
837 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700838 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700839
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700840 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
841 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
842 ++Thread::Current()->GetStats()->gc_for_alloc_count;
843 }
844
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700845 // We need to do partial GCs every now and then to avoid the heap growing too much and
846 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700847 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700848 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700849 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700850 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700851 sticky_gc_count_ = 0;
852 }
853
Mathieu Chartier637e3482012-08-17 10:41:32 -0700854 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700855 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700856 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700857 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700858 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700859 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700860
Ian Rogers15bf2d32012-08-28 17:33:04 -0700861 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700862 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700863 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700864 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700865 // Wake anyone who may have been waiting for the GC to complete.
866 gc_complete_cond_->Broadcast();
867 }
868 // Inform DDMS that a GC completed.
869 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700870 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700871}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700872
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700873void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
874 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700875 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700876
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700877 std::stringstream gc_type_str;
878 gc_type_str << gc_type << " ";
879
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700880 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700881 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700882 ThreadList* thread_list = Runtime::Current()->GetThreadList();
883 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700884 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700885 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700886
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700887 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700888 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700889 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700890 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700891
892 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700893 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700894
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700895 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700896 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700897 if (!VerifyHeapReferences()) {
898 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
899 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700900 timings.AddSplit("VerifyHeapReferencesPreGC");
901 }
902
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700903 // Make sure that the tables have the correct pointer for the mark sweep.
904 mod_union_table_->Init(&mark_sweep);
905 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700906
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700907 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700908 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700909
910 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
911 // TODO: Investigate using a mark stack instead of a vector.
912 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700913 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700914 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
915 card_table_->GetDirtyCards(*it, dirty_cards);
916 }
917 }
918
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700919 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700920 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700921 ContinuousSpace* space = *it;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700922 if (space->IsImageSpace()) {
923 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700924 timings.AddSplit("ClearModUnionCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700925 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
926 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700927 timings.AddSplit("ClearZygoteCards");
928 } else {
929 card_table_->ClearSpaceCards(space);
930 timings.AddSplit("ClearCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700931 }
932 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700933
Ian Rogers120f1c72012-09-28 17:17:10 -0700934 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700935 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700936 // Copy the mark bits over from the live bits, do this as early as possible or else we can
937 // accidentally un-mark roots.
938 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700939 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700940 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
941 mark_sweep.CopyMarkBits(*it);
942 }
943 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700944 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700945
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700946 // We can assume that everything from the start of the first space to the alloc space is marked.
947 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
948 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700949 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700950 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700951 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
952 mark_sweep.CopyMarkBits(*it);
953 }
954 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700955 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700956 timings.AddSplit("CopyMarkBits");
957
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700958 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
959 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700960 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700961
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700962 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
963 live_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700964
Mathieu Chartier0325e622012-09-05 14:22:51 -0700965 if (gc_type != kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700966 live_stack_->Reset();
967 }
968
Carl Shapiro58551df2011-07-24 03:09:51 -0700969 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700970 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700971
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700972 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -0700973 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700974
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700975 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700976
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700977 if (verify_mod_union_table_) {
978 zygote_mod_union_table_->Update();
979 zygote_mod_union_table_->Verify();
980 mod_union_table_->Update();
981 mod_union_table_->Verify();
982 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700983
984 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700985 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700986 live_stack_->Reset();
Mathieu Chartier0325e622012-09-05 14:22:51 -0700987 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700988 } else {
989 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
990 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700991 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -0700992
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700993 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -0800994 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700995 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700996
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700997 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
998 mark_sweep.SweepSystemWeaks(false);
999 timings.AddSplit("SweepSystemWeaks");
1000
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001001 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001002 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001003 SwapBitmaps(self);
Mathieu Chartier654d3a22012-07-11 17:54:18 -07001004 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001005
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001006#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001007 // Verify that we only reach marked objects from the image space
1008 mark_sweep.VerifyImageRoots();
1009 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001010#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001011
Mathieu Chartier0325e622012-09-05 14:22:51 -07001012 if (gc_type != kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001013 mark_sweep.SweepLargeObjects(swap);
1014 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001015 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001016 } else {
1017 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001018 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001019 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001020
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001021 if (verify_system_weaks_) {
1022 mark_sweep.VerifySystemWeaks();
1023 timings.AddSplit("VerifySystemWeaks");
1024 }
1025
Elliott Hughesadb460d2011-10-05 17:02:34 -07001026 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001027 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001028 }
1029
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001030 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001031 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001032 if (!VerifyHeapReferences()) {
1033 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1034 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001035 timings.AddSplit("VerifyHeapReferencesPostGC");
1036 }
1037
Carl Shapiro58551df2011-07-24 03:09:51 -07001038 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001039 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001040
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001041 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001042 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001043
1044 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001045 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001046 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001047
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001048 // If the GC was slow, then print timings in the log.
1049 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1050 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001051 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001052 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001053 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001054 LOG(INFO) << gc_cause << " " << gc_type_str.str() << " "
Mathieu Chartier637e3482012-08-17 10:41:32 -07001055 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001056 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001057 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001058 if (VLOG_IS_ON(heap)) {
1059 timings.Dump();
1060 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001061 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001062
Mathieu Chartier0325e622012-09-05 14:22:51 -07001063 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1064 logger->Start();
1065 logger->AddLogger(timings);
1066 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001067}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001068
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001069void Heap::UpdateAndMarkModUnion(TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001070 if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001071 // Don't need to do anythign for mod union table in this case since we are only scanning dirty
1072 // cards.
1073 return;
1074 }
1075
1076 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001077 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001078 zygote_mod_union_table_->Update();
1079 timings.AddSplit("UpdateZygoteModUnionTable");
1080
1081 zygote_mod_union_table_->MarkReferences();
1082 timings.AddSplit("ZygoteMarkReferences");
1083 }
1084
1085 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1086 mod_union_table_->Update();
1087 timings.AddSplit("UpdateModUnionTable");
1088
1089 // Scans all objects in the mod-union table.
1090 mod_union_table_->MarkReferences();
1091 timings.AddSplit("MarkImageToAllocSpaceReferences");
1092}
1093
1094void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1095 Object* obj = reinterpret_cast<Object*>(arg);
1096 if (root == obj) {
1097 LOG(INFO) << "Object " << obj << " is a root";
1098 }
1099}
1100
1101class ScanVisitor {
1102 public:
1103 void operator ()(const Object* obj) const {
1104 LOG(INFO) << "Would have rescanned object " << obj;
1105 }
1106};
1107
1108class VerifyReferenceVisitor {
1109 public:
1110 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001111 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1112 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001113 : heap_(heap),
1114 failed_(failed) {
1115 }
1116
1117 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1118 // analysis.
1119 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1120 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1121 // Verify that the reference is live.
1122 if (ref != NULL && !IsLive(ref)) {
1123 CardTable* card_table = heap_->GetCardTable();
1124 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1125 MarkStack* live_stack = heap_->live_stack_.get();
1126
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001127 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001128 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " on IsDirty = "
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001129 << (*card_addr == GC_CARD_DIRTY);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001130 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1131 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1132 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001133 void* cover_begin = card_table->AddrFromCard(card_addr);
1134 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1135 GC_CARD_SIZE);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001136 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001137 << "-" << cover_end;
1138 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1139
1140 // Print out how the object is live.
1141 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001142 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1143 }
1144
1145 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1146 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1147 }
1148
1149 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1150 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001151 }
1152
1153 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001154 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001155 }
1156
1157 // Attempt to see if the card table missed the reference.
1158 ScanVisitor scan_visitor;
1159 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1160 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + GC_CARD_SIZE, scan_visitor,
1161 IdentityFunctor());
1162
1163 // Try and see if a mark sweep collector scans the reference.
1164 MarkStack* mark_stack = heap_->mark_stack_.get();
1165 MarkSweep ms(mark_stack);
1166 ms.Init();
1167 mark_stack->Reset();
1168 ms.SetFinger(reinterpret_cast<Object*>(~size_t(0)));
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001169
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001170 // All the references should end up in the mark stack.
1171 ms.ScanRoot(obj);
1172 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001173 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001174 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001175 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001176 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001177 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001178 }
1179 }
1180 mark_stack->Reset();
1181
1182 // Search to see if any of the roots reference our object.
1183 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1184 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1185 *failed_ = true;
1186 }
1187 }
1188
1189 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1190 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1191 if (bitmap != NULL) {
1192 if (bitmap->Test(obj)) {
1193 return true;
1194 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001195 } else if (heap_->GetLargeObjectsSpace()->GetLiveObjects()->Test(obj)) {
1196 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001197 } else {
1198 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001199 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001200 }
1201 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1202 // At this point we need to search the allocation since things in the live stack may get swept.
1203 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1204 return true;
1205 }
1206 // Not either in the live bitmap or allocation stack, so the object must be dead.
1207 return false;
1208 }
1209
1210 private:
1211 Heap* heap_;
1212 bool* failed_;
1213};
1214
1215class VerifyObjectVisitor {
1216 public:
1217 VerifyObjectVisitor(Heap* heap)
1218 : heap_(heap),
1219 failed_(false) {
1220
1221 }
1222
1223 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001224 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001225 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1226 MarkSweep::VisitObjectReferences(obj, visitor);
1227 }
1228
1229 bool Failed() const {
1230 return failed_;
1231 }
1232
1233 private:
1234 Heap* heap_;
1235 bool failed_;
1236};
1237
1238// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001239bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001240 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001241 // Lets sort our allocation stacks so that we can efficiently binary search them.
1242 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1243 std::sort(live_stack_->Begin(), live_stack_->End());
1244 // Perform the verification.
1245 VerifyObjectVisitor visitor(this);
1246 GetLiveBitmap()->Visit(visitor);
1247 // We don't want to verify the objects in the allocation stack since they themselves may be
1248 // pointing to dead objects if they are not reachable.
1249 if (visitor.Failed()) {
1250 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001251 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001252 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001253 return true;
1254}
1255
1256class VerifyReferenceCardVisitor {
1257 public:
1258 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1259 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1260 Locks::heap_bitmap_lock_)
1261 : heap_(heap),
1262 failed_(failed) {
1263 }
1264
1265 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1266 // analysis.
1267 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1268 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
1269 if (ref != NULL) {
1270 CardTable* card_table = heap_->GetCardTable();
1271 // If the object is not dirty and it is referencing something in the live stack other than
1272 // class, then it must be on a dirty card.
1273 if (!card_table->IsDirty(obj)) {
1274 MarkStack* live_stack = heap_->live_stack_.get();
1275 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1276 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1277 LOG(ERROR) << "Object " << obj << " found in live stack";
1278 }
1279 if (heap_->GetLiveBitmap()->Test(obj)) {
1280 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1281 }
1282 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1283 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1284
1285 // Print which field of the object is dead.
1286 if (!obj->IsObjectArray()) {
1287 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1288 CHECK(klass != NULL);
1289 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1290 CHECK(fields != NULL);
1291 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1292 const Field* cur = fields->Get(i);
1293 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1294 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1295 << PrettyField(cur);
1296 break;
1297 }
1298 }
1299 } else {
1300 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1301 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1302 if (object_array->Get(i) == ref) {
1303 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1304 }
1305 }
1306 }
1307
1308 *failed_ = true;
1309 }
1310 }
1311 }
1312 }
1313
1314 private:
1315 Heap* heap_;
1316 bool* failed_;
1317};
1318
1319class VerifyLiveStackReferences {
1320 public:
1321 VerifyLiveStackReferences(Heap* heap)
1322 : heap_(heap),
1323 failed_(false) {
1324
1325 }
1326
1327 void operator ()(const Object* obj) const
1328 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1329 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1330 MarkSweep::VisitObjectReferences(obj, visitor);
1331 }
1332
1333 bool Failed() const {
1334 return failed_;
1335 }
1336
1337 private:
1338 Heap* heap_;
1339 bool failed_;
1340};
1341
1342bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001343 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001344
1345 VerifyLiveStackReferences visitor(this);
1346 GetLiveBitmap()->Visit(visitor);
1347
1348 // We can verify objects in the live stack since none of these should reference dead objects.
1349 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1350 visitor(*it);
1351 }
1352
1353 if (visitor.Failed()) {
1354 DumpSpaces();
1355 return false;
1356 }
1357 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001358}
1359
Ian Rogers81d425b2012-09-27 16:03:43 -07001360void Heap::SwapBitmaps(Thread* self) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001361 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1362 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1363 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
1364 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
Ian Rogers81d425b2012-09-27 16:03:43 -07001365 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001366 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001367 ContinuousSpace* space = *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001368 // We never allocate into zygote spaces.
1369 if (space->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1370 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1371 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1372 space->AsAllocSpace()->SwapBitmaps();
1373 }
1374 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001375
1376 large_object_space_->SwapBitmaps();
1377 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1378 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001379}
1380
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001381void Heap::SwapStacks() {
1382 MarkStack* temp = allocation_stack_.release();
1383 allocation_stack_.reset(live_stack_.release());
1384 live_stack_.reset(temp);
1385
1386 // Sort the live stack so that we can quickly binary search it later.
1387 if (VERIFY_OBJECT_ENABLED) {
1388 std::sort(live_stack_->Begin(), live_stack_->End());
1389 }
1390}
1391
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001392void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1393 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001394 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1395 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001396 std::stringstream gc_type_str;
1397 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001398
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001399 // Suspend all threads are get exclusive access to the heap.
1400 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1401 thread_list->SuspendAll();
1402 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001403 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001404
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001405 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001406 Object* cleared_references = NULL;
1407 {
1408 MarkSweep mark_sweep(mark_stack_.get());
1409 timings.AddSplit("ctor");
1410
1411 mark_sweep.Init();
1412 timings.AddSplit("Init");
1413
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001414 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001415 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001416 if (!VerifyHeapReferences()) {
1417 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1418 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001419 timings.AddSplit("VerifyHeapReferencesPreGC");
1420 }
1421
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001422 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1423 SwapStacks();
1424
1425 // Check that all objects which reference things in the live stack are on dirty cards.
1426 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001427 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001428 // Sort the live stack so that we can quickly binary search it later.
1429 std::sort(live_stack_->Begin(), live_stack_->End());
1430 if (!VerifyMissingCardMarks()) {
1431 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1432 }
1433 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001434
1435 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1436 // TODO: Investigate using a mark stack instead of a vector.
1437 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001438 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001439 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1440 card_table_->GetDirtyCards(*it, dirty_cards);
1441 }
1442 }
1443
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001444 // Make sure that the tables have the correct pointer for the mark sweep.
1445 mod_union_table_->Init(&mark_sweep);
1446 zygote_mod_union_table_->Init(&mark_sweep);
1447
1448 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1449 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001450 ContinuousSpace* space = *it;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001451 if (space->IsImageSpace()) {
1452 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001453 timings.AddSplit("ModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001454 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1455 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001456 timings.AddSplit("ZygoteModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001457 } else {
1458 card_table_->ClearSpaceCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001459 timings.AddSplit("ClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001460 }
1461 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001462
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001463 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001464 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001465
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001466 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1467 CHECK(!GetLiveBitmap()->Test(*it));
1468 }
1469
Mathieu Chartier0325e622012-09-05 14:22:51 -07001470 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001471 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1472 // accidentally un-mark roots.
1473 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001474 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001475 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1476 mark_sweep.CopyMarkBits(*it);
1477 }
1478 }
1479 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001480 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1481 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001482 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001483 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001484 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1485 mark_sweep.CopyMarkBits(*it);
1486 }
1487 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001488 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001489 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001490 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1491 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001492 }
1493
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001494 // Marking roots is not necessary for sticky mark bits since we only actually require the
1495 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001496 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001497 mark_sweep.MarkRoots();
1498 timings.AddSplit("MarkRoots");
1499 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001500
1501 if (verify_mod_union_table_) {
1502 zygote_mod_union_table_->Update();
1503 zygote_mod_union_table_->Verify();
1504 mod_union_table_->Update();
1505 mod_union_table_->Verify();
1506 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001507 }
1508
1509 // Roots are marked on the bitmap and the mark_stack is empty.
1510 DCHECK(mark_sweep.IsMarkStackEmpty());
1511
1512 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1513 thread_list->ResumeAll();
1514 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001515 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001516 root_end = NanoTime();
1517 timings.AddSplit("RootEnd");
1518
Ian Rogers81d425b2012-09-27 16:03:43 -07001519 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001520 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001521
1522 // Mark everything as live so that sweeping system weak works correctly for sticky mark bit
1523 // GCs.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001524 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1525 live_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001526 timings.AddSplit("MarkStackAsLive");
1527
Mathieu Chartier0325e622012-09-05 14:22:51 -07001528 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001529 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001530 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001531 } else {
1532 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001533 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001534 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001535 }
1536 // Release share on mutator_lock_ and then get exclusive access.
1537 dirty_begin = NanoTime();
1538 thread_list->SuspendAll();
1539 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001540 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001541
1542 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001543 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001544
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001545 // Re-mark root set.
1546 mark_sweep.ReMarkRoots();
1547 timings.AddSplit("ReMarkRoots");
1548
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001549 if (verify_missing_card_marks_) {
1550 // Since verify missing card marks uses a sweep array to empty the allocation stack, we
1551 // need to make sure that we don't free weaks which wont get swept by SweepSystemWeaks.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001552 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1553 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001554 }
1555
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001557 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001558 timings.AddSplit("RecursiveMarkDirtyObjects");
1559 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001560
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001561 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001562 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001563
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564 mark_sweep.ProcessReferences(clear_soft_references);
1565 timings.AddSplit("ProcessReferences");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001566
1567 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1568 mark_sweep.SweepSystemWeaks(false);
1569 timings.AddSplit("SweepSystemWeaks");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001570 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001571
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001572 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1573 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1574 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1575 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001576 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001577 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001578 SwapBitmaps(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001579 }
1580
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001581 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1582 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001583 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001584 mark_sweep.SweepArray(timings, allocation_stack_.get(), swap);
1585 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001586 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001587 // We only sweep over the live stack, and the live stack should not intersect with the
1588 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001589 UnMarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1590 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001591 timings.AddSplit("UnMarkAllocStack");
1592 }
1593
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001594 if (kIsDebugBuild) {
1595 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001596 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001597 mark_sweep.VerifyImageRoots();
1598 timings.AddSplit("VerifyImageRoots");
1599 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001600
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001601 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001602 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001603 if (!VerifyHeapReferences()) {
1604 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
1605 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001606 timings.AddSplit("VerifyHeapReferencesPostGC");
1607 }
1608
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001609 thread_list->ResumeAll();
1610 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001611 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001612
1613 {
1614 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001615 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001616 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001617 mark_sweep.SweepLargeObjects(swap);
1618 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001619 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001620 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001621 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001622 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001623 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001624 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001625 live_stack_->Reset();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001626 timings.AddSplit("Sweep");
1627 }
1628
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001629 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001630 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001631 mark_sweep.VerifySystemWeaks();
1632 timings.AddSplit("VerifySystemWeaks");
1633 }
1634
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001635 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001636 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001637 }
1638
1639 GrowForUtilization();
1640 timings.AddSplit("GrowForUtilization");
1641
1642 EnqueueClearedReferences(&cleared_references);
1643 RequestHeapTrim();
1644 timings.AddSplit("Finish");
1645
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001646 // If the GC was slow, then print timings in the log.
1647 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1648 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001649 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001650 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001651 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001652 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001653 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001654 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001655 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001656 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001657 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1658 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001659 if (VLOG_IS_ON(heap)) {
1660 timings.Dump();
1661 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001662 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001663
Mathieu Chartier0325e622012-09-05 14:22:51 -07001664 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1665 logger->Start();
1666 logger->AddLogger(timings);
1667 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001668}
1669
Ian Rogers81d425b2012-09-27 16:03:43 -07001670GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001671 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001672 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001673 bool do_wait;
1674 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001675 {
1676 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001677 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001678 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001679 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001680 if (do_wait) {
1681 // We must wait, change thread state then sleep on gc_complete_cond_;
1682 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1683 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001684 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001685 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001686 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001687 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001688 last_gc_type = last_gc_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001689 }
1690 uint64_t wait_time = NanoTime() - wait_start;
1691 if (wait_time > MsToNs(5)) {
1692 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1693 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001694 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001695 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001696 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001697}
1698
Elliott Hughesc967f782012-04-16 10:23:15 -07001699void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001700 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1701 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier0325e622012-09-05 14:22:51 -07001702 // Dump cumulative timings.
1703 LOG(INFO) << "Dumping cumulative Gc timings";
1704 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
1705 it != cumulative_timings_.end(); ++it) {
1706 it->second->Dump();
1707 }
Elliott Hughesc967f782012-04-16 10:23:15 -07001708}
1709
1710size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001711 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001712}
1713
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001714void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001715 AllocSpace* alloc_space = alloc_space_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001716 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001717 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001718 << PrettySize(GetMaxMemory());
1719 max_allowed_footprint = GetMaxMemory();
1720 }
1721 // We want to update the footprint for just the alloc space.
1722 max_allowed_footprint -= large_object_space_->GetNumBytesAllocated();
1723 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1724 if ((*it)->IsAllocSpace()) {
1725 AllocSpace* alloc_space = (*it)->AsAllocSpace();
1726 if (alloc_space != alloc_space_) {
1727 max_allowed_footprint -= alloc_space->GetNumBytesAllocated();
1728 }
1729 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001730 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001731 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001732}
1733
Ian Rogers3bb17a62012-01-27 23:56:44 -08001734// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001735static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001736// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1737// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001738static const size_t kHeapMinFree = kHeapIdealFree / 4;
1739
Carl Shapiro69759ea2011-07-21 18:13:35 -07001740void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001741 // We know what our utilization is at this moment.
1742 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1743 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
1744 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1745 target_size = num_bytes_allocated_ + kHeapIdealFree;
1746 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1747 target_size = num_bytes_allocated_ + kHeapMinFree;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001748 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001749
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001750 // Calculate when to perform the next ConcurrentGC.
1751 if (GetFreeMemory() < concurrent_min_free_) {
1752 // Not enough free memory to perform concurrent GC.
1753 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1754 } else {
1755 // Start a concurrent Gc when we get close to the target size.
1756 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001757 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001758
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001759 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001760}
1761
jeffhaoc1160702011-10-27 15:48:45 -07001762void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001763 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001764 alloc_space_->ClearGrowthLimit();
1765}
1766
Elliott Hughesadb460d2011-10-05 17:02:34 -07001767void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001768 MemberOffset reference_queue_offset,
1769 MemberOffset reference_queueNext_offset,
1770 MemberOffset reference_pendingNext_offset,
1771 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001772 reference_referent_offset_ = reference_referent_offset;
1773 reference_queue_offset_ = reference_queue_offset;
1774 reference_queueNext_offset_ = reference_queueNext_offset;
1775 reference_pendingNext_offset_ = reference_pendingNext_offset;
1776 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1777 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1778 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1779 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1780 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1781 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1782}
1783
1784Object* Heap::GetReferenceReferent(Object* reference) {
1785 DCHECK(reference != NULL);
1786 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1787 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1788}
1789
1790void Heap::ClearReferenceReferent(Object* reference) {
1791 DCHECK(reference != NULL);
1792 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1793 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1794}
1795
1796// Returns true if the reference object has not yet been enqueued.
1797bool Heap::IsEnqueuable(const Object* ref) {
1798 DCHECK(ref != NULL);
1799 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1800 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1801 return (queue != NULL) && (queue_next == NULL);
1802}
1803
1804void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1805 DCHECK(ref != NULL);
1806 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1807 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1808 EnqueuePendingReference(ref, cleared_reference_list);
1809}
1810
1811void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1812 DCHECK(ref != NULL);
1813 DCHECK(list != NULL);
1814
1815 if (*list == NULL) {
1816 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1817 *list = ref;
1818 } else {
1819 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1820 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1821 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1822 }
1823}
1824
1825Object* Heap::DequeuePendingReference(Object** list) {
1826 DCHECK(list != NULL);
1827 DCHECK(*list != NULL);
1828 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1829 Object* ref;
1830 if (*list == head) {
1831 ref = *list;
1832 *list = NULL;
1833 } else {
1834 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1835 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1836 ref = head;
1837 }
1838 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1839 return ref;
1840}
1841
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001842void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001843 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001844 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001845 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001846 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1847 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001848}
1849
1850size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001851 return num_bytes_allocated_;
1852}
1853
1854size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001855 size_t total = 0;
1856 // TODO: C++0x
1857 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1858 Space* space = *it;
1859 if (space->IsAllocSpace()) {
1860 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1861 }
1862 }
1863 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001864}
1865
1866size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001867 return concurrent_start_size_;
1868}
1869
1870size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001871 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001872}
1873
1874void Heap::EnqueueClearedReferences(Object** cleared) {
1875 DCHECK(cleared != NULL);
1876 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001877 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001878 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001879 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001880 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1881 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001882 *cleared = NULL;
1883 }
1884}
1885
Ian Rogers1f539342012-10-03 21:09:42 -07001886void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001887 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001888 Runtime* runtime = Runtime::Current();
1889 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1890 !runtime->IsConcurrentGcEnabled()) {
1891 return;
1892 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001893 {
1894 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1895 if (runtime->IsShuttingDown()) {
1896 return;
1897 }
1898 }
1899 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001900 return;
1901 }
1902
1903 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001904 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001905 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1906 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001907 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1908 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001909 CHECK(!env->ExceptionCheck());
1910 requesting_gc_ = false;
1911}
1912
Ian Rogers81d425b2012-09-27 16:03:43 -07001913void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001914 {
1915 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1916 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
1917 return;
1918 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001919 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001920
Ian Rogers81d425b2012-09-27 16:03:43 -07001921 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001922 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07001923 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001924 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001925 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001926 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001927 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001928 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001929 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001930}
1931
Ian Rogers81d425b2012-09-27 16:03:43 -07001932void Heap::Trim(Thread* self) {
1933 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001934 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001935}
1936
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001937void Heap::RequestHeapTrim() {
1938 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1939 // because that only marks object heads, so a large array looks like lots of empty space. We
1940 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1941 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1942 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1943 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001944 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001945 float utilization =
1946 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1947 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1948 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1949 // heap trim occurred in the last two seconds.
1950 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001951 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001952
1953 Thread* self = Thread::Current();
1954 {
1955 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1956 Runtime* runtime = Runtime::Current();
1957 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1958 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1959 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1960 // as we don't hold the lock while requesting the trim).
1961 return;
1962 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001963 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001964 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001965 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001966 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1967 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001968 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1969 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001970 CHECK(!env->ExceptionCheck());
1971}
1972
Carl Shapiro69759ea2011-07-21 18:13:35 -07001973} // namespace art