blob: eafe2721e1b373029572ae6cbbdc47f03543c1e1 [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 Chartier2fde5332012-09-14 14:51:54 -0700202 UniquePtr<AllocSpace> alloc_space(AllocSpace::Create("alloc space", initial_size, growth_limit,
203 capacity, requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700204 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700205 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700206 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700207
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700208 // Spaces are sorted in order of Begin().
209 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700210 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
211 if (spaces_.back()->IsAllocSpace()) {
212 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
213 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700214
Ian Rogers30fab402012-01-23 15:43:46 -0800215 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700216 // TODO: C++0x
217 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
218 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800219 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700220 ImageSpace* image_space = space->AsImageSpace();
221 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800222 }
223 }
224
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700225 // Allocate the large object space.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700226 large_object_space_.reset(FreeListSpace::Create("large object space", 64 * MB));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700227 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
228 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
229
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800230 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700231 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
232 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700233
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700234 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
235 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700236
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700237 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
238 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700239
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700240 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700241 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700243 // Max stack size in bytes.
244 static const size_t max_stack_size = capacity / SpaceBitmap::kAlignment * kWordSize;
245
246 // TODO: Rename MarkStack to a more generic name?
247 mark_stack_.reset(MarkStack::Create("dalvik-mark-stack", max_stack_size));
248 allocation_stack_.reset(MarkStack::Create("dalvik-allocation-stack", max_stack_size));
249 live_stack_.reset(MarkStack::Create("dalvik-live-stack", max_stack_size));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700250
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800251 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700252 // but we can create the heap lock now. We don't create it earlier to
253 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700254 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700255 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700256
Mathieu Chartier0325e622012-09-05 14:22:51 -0700257 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700258 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
259 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700260 std::ostringstream name;
261 name << static_cast<GcType>(i);
262 cumulative_timings_.Put(static_cast<GcType>(i),
263 new CumulativeLogger(name.str().c_str(), true));
264 }
265
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800266 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800267 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700268 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700269}
270
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700271// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700272struct SpaceSorter {
273 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700274 return a->Begin() < b->Begin();
275 }
276};
277
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700278void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700279 WriterMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700280 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700281 DCHECK(space->GetLiveBitmap() != NULL);
282 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700283 DCHECK(space->GetMarkBitmap() != NULL);
284 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800285 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700286 if (space->IsAllocSpace()) {
287 alloc_space_ = space->AsAllocSpace();
288 }
289
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700290 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
291 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700292
293 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
294 // avoid redundant marking.
295 bool seen_zygote = false, seen_alloc = false;
296 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
297 Space* space = *it;
298 if (space->IsImageSpace()) {
299 DCHECK(!seen_zygote);
300 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700301 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700302 DCHECK(!seen_alloc);
303 seen_zygote = true;
304 } else if (space->IsAllocSpace()) {
305 seen_alloc = true;
306 }
307 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800308}
309
310Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700311 // If we don't reset then the mark stack complains in it's destructor.
312 allocation_stack_->Reset();
313 live_stack_->Reset();
314
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800315 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800316 // We can't take the heap lock here because there might be a daemon thread suspended with the
317 // heap lock held. We know though that no non-daemon threads are executing, and we know that
318 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
319 // 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 -0700320 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700321 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700322 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700323}
324
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700325ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700326 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700327 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
328 if ((*it)->Contains(obj)) {
329 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700330 }
331 }
332 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
333 return NULL;
334}
335
336ImageSpace* Heap::GetImageSpace() {
337 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700338 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
339 if ((*it)->IsImageSpace()) {
340 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700341 }
342 }
343 return NULL;
344}
345
346AllocSpace* Heap::GetAllocSpace() {
347 return alloc_space_;
348}
349
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700350static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700351 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700352 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700353 size_t chunk_free_bytes = chunk_size - used_bytes;
354 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
355 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700356 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700357}
358
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700359Object* Heap::AllocObject(Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700360 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
361 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
362 strlen(ClassHelper(c).GetDescriptor()) == 0);
363 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700364
365 Object* obj = NULL;
366 size_t size = 0;
367
368 // We need to have a zygote space or else our newly allocated large object can end up in the
369 // Zygote resulting in it being prematurely freed.
370 // We can only do this for primive objects since large objects will not be within the card table
371 // range. This also means that we rely on SetClass not dirtying the object's card.
372 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700373 size = RoundUp(byte_count, kPageSize);
374 obj = Allocate(NULL, size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700375
376 if (obj != NULL) {
377 // Make sure that our large object didn't get placed anywhere within the space interval or else
378 // it breaks the immune range.
379 DCHECK(reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
380 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
381 }
382 } else {
383 obj = Allocate(alloc_space_, byte_count);
384 size = alloc_space_->AllocationSize(obj);
385
386 if (obj != NULL) {
387 // Additional verification to ensure that we did not allocate into a zygote space.
388 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
389 }
390 }
391
Mathieu Chartier037813d2012-08-23 16:44:59 -0700392 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700393 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700394
395 // Record allocation after since we want to use the atomic add for the atomic fence to guard
396 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700397 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700398
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700399 if (Dbg::IsAllocTrackingEnabled()) {
400 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700401 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700402 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700403 // We already have a request pending, no reason to start more until we update
404 // concurrent_start_bytes_.
405 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700406 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700407 Thread* self = Thread::Current();
408 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));
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700426 Thread::Current()->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()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700485 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
486 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 Rogersb726dcb2012-09-05 08:57:23 -0700522 ReaderMutexLock mu(*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
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700563Object* Heap::TryToAllocate(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)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700570 return large_object_space_->Alloc(alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700571 } else if (grow) {
572 return space->AllocWithGrowth(alloc_size);
573 } else {
574 return space->AllocWithoutGrowth(alloc_size);
575 }
576}
577
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700578Object* Heap::Allocate(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 Rogers00f7d0e2012-07-19 15:28:27 -0700581#ifndef NDEBUG
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700582 Thread* self = Thread::Current();
Ian Rogers81d425b2012-09-27 16:03:43 -0700583 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700584 self->AssertThreadSuspensionIsAllowable();
585#endif
Brian Carlstromb82b6872011-10-26 17:18:07 -0700586
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700587 Object* ptr = TryToAllocate(space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700588 if (ptr != NULL) {
589 return ptr;
590 }
591
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700592 // The allocation failed. If the GC is running, block until it completes, and then retry the
593 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700594#ifdef NDEBUG
595 Thread* self = Thread::Current();
596#endif
597 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700598 if (last_gc != kGcTypeNone) {
599 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700600 ptr = TryToAllocate(space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700601 if (ptr != NULL) {
602 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700603 }
604 }
605
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700606 // Loop through our different Gc types and try to Gc until we get enough free memory.
607 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
608 bool run_gc = false;
609 GcType gc_type = static_cast<GcType>(i);
610 switch (gc_type) {
611 case kGcTypeSticky: {
612 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700613 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
614 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700615 break;
616 }
617 case kGcTypePartial:
618 run_gc = have_zygote_space_;
619 break;
620 case kGcTypeFull:
621 run_gc = true;
622 break;
623 default:
624 break;
625 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700626
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700627 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700628 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
629
630 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700631 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700632 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
633 i = static_cast<size_t>(gc_type_ran);
634 self->TransitionFromSuspendedToRunnable();
635
636 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700637 ptr = TryToAllocate(space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700638 if (ptr != NULL) {
639 return ptr;
640 }
641 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700642 }
643
644 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700645 // Try harder, growing the heap if necessary.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700646 ptr = TryToAllocate(space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700647 if (ptr != NULL) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700648 if (space != NULL) {
649 size_t new_footprint = space->GetFootprintLimit();
650 // OLD-TODO: may want to grow a little bit more so that the amount of
651 // free space is equal to the old free space + the
652 // utilization slop for the new allocation.
653 VLOG(gc) << "Grow alloc space (frag case) to " << PrettySize(new_footprint)
654 << " for a " << PrettySize(alloc_size) << " allocation";
655 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700656 return ptr;
657 }
658
Elliott Hughes81ff3182012-03-23 20:35:56 -0700659 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
660 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
661 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700662
Elliott Hughes418dfe72011-10-06 18:56:27 -0700663 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700664 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
665 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700666
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700667 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700668 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700669 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700670 self->TransitionFromSuspendedToRunnable();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700671 return TryToAllocate(space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700672}
673
Elliott Hughesbf86d042011-08-31 17:53:14 -0700674int64_t Heap::GetMaxMemory() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700675 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700676}
677
678int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700679 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700680}
681
682int64_t Heap::GetFreeMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700683 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700684}
685
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700686class InstanceCounter {
687 public:
688 InstanceCounter(Class* c, bool count_assignable)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700689 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700690 : class_(c), count_assignable_(count_assignable), count_(0) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700691
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700692 }
693
694 size_t GetCount() {
695 return count_;
696 }
697
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700698 static void Callback(Object* o, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700699 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700700 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
701 }
702
703 private:
Ian Rogersb726dcb2012-09-05 08:57:23 -0700704 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700705 Class* instance_class = o->GetClass();
706 if (count_assignable_) {
707 if (instance_class == class_) {
708 ++count_;
709 }
710 } else {
711 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
712 ++count_;
713 }
714 }
715 }
716
717 Class* class_;
718 bool count_assignable_;
719 size_t count_;
720};
721
722int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700723 ReaderMutexLock mu(*Locks::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700724 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700725 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700726 return counter.GetCount();
727}
728
Ian Rogers30fab402012-01-23 15:43:46 -0800729void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700730 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
731 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700732 Thread* self = Thread::Current();
733 WaitForConcurrentGcToComplete(self);
734 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700735 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
736 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700737}
738
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700739void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700740 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700741 Thread* self = Thread::Current();
742 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700743
744 // Try to see if we have any Zygote spaces.
745 if (have_zygote_space_) {
746 return;
747 }
748
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700749 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
750
751 {
752 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700753 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700754 FlushAllocStack();
755 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700756
757 // Replace the first alloc space we find with a zygote space.
758 // TODO: C++0x auto
759 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
760 if ((*it)->IsAllocSpace()) {
761 AllocSpace* zygote_space = (*it)->AsAllocSpace();
762
763 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
764 // of the remaining available heap memory.
765 alloc_space_ = zygote_space->CreateZygoteSpace();
766
767 // Change the GC retention policy of the zygote space to only collect when full.
768 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
769 AddSpace(alloc_space_);
770 have_zygote_space_ = true;
771 break;
772 }
773 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700774
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700775 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700776 // TODO: C++0x
777 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
778 it != cumulative_timings_.end(); ++it) {
779 it->second->Reset();
780 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700781}
782
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700783void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700784 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
785 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700786 allocation_stack_->Reset();
787}
788
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700789size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700790 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700791}
792
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700793void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700794 const size_t count = stack->Size();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700795 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700796 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700797 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700798 if (LIKELY(bitmap->HasAddress(obj))) {
799 bitmap->Set(obj);
800 } else {
801 large_objects->Set(obj);
802 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700803 }
804}
805
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700806void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, MarkStack* stack) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700807 size_t count = stack->Size();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700808 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700809 const Object* obj = stack->Get(i);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700810 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700811 if (LIKELY(bitmap->HasAddress(obj))) {
812 bitmap->Clear(obj);
813 } else {
814 large_objects->Clear(obj);
815 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700816 }
817}
818
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700819GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700820 Thread* self = Thread::Current();
821 Locks::mutator_lock_->AssertNotHeld(self);
822 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700823
Ian Rogers120f1c72012-09-28 17:17:10 -0700824 if (self->IsHandlingStackOverflow()) {
825 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
826 }
827
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700828 // Ensure there is only one GC at a time.
829 bool start_collect = false;
830 while (!start_collect) {
831 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700832 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700833 if (!is_gc_running_) {
834 is_gc_running_ = true;
835 start_collect = true;
836 }
837 }
838 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700839 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700840 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
841 // Not doing at the moment to ensure soft references are cleared.
842 }
843 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700844 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700845
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700846 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
847 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
848 ++Thread::Current()->GetStats()->gc_for_alloc_count;
849 }
850
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700851 // We need to do partial GCs every now and then to avoid the heap growing too much and
852 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700853 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700854 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700855 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700856 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700857 sticky_gc_count_ = 0;
858 }
859
Mathieu Chartier637e3482012-08-17 10:41:32 -0700860 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700861 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700862 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700863 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700864 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700865 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700866
Ian Rogers15bf2d32012-08-28 17:33:04 -0700867 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700868 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700869 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700870 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700871 // Wake anyone who may have been waiting for the GC to complete.
872 gc_complete_cond_->Broadcast();
873 }
874 // Inform DDMS that a GC completed.
875 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700876 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700877}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700878
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700879void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
880 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700881 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700882
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700883 std::stringstream gc_type_str;
884 gc_type_str << gc_type << " ";
885
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700886 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700887 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700888 ThreadList* thread_list = Runtime::Current()->GetThreadList();
889 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700890 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700891 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700892
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700893 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700894 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700895 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700896 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700897
898 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700899 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700900
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700901 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700902 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700903 if (!VerifyHeapReferences()) {
904 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
905 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700906 timings.AddSplit("VerifyHeapReferencesPreGC");
907 }
908
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700909 // Make sure that the tables have the correct pointer for the mark sweep.
910 mod_union_table_->Init(&mark_sweep);
911 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700912
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700913 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700914 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700915
916 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
917 // TODO: Investigate using a mark stack instead of a vector.
918 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700919 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700920 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
921 card_table_->GetDirtyCards(*it, dirty_cards);
922 }
923 }
924
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700925 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700926 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700927 ContinuousSpace* space = *it;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700928 if (space->IsImageSpace()) {
929 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700930 timings.AddSplit("ClearModUnionCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700931 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
932 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700933 timings.AddSplit("ClearZygoteCards");
934 } else {
935 card_table_->ClearSpaceCards(space);
936 timings.AddSplit("ClearCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700937 }
938 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700939
Ian Rogers120f1c72012-09-28 17:17:10 -0700940 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700941 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700942 // Copy the mark bits over from the live bits, do this as early as possible or else we can
943 // accidentally un-mark roots.
944 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700945 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700946 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
947 mark_sweep.CopyMarkBits(*it);
948 }
949 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700950 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700951
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700952 // We can assume that everything from the start of the first space to the alloc space is marked.
953 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
954 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700955 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700956 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700957 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
958 mark_sweep.CopyMarkBits(*it);
959 }
960 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700961 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700962 timings.AddSplit("CopyMarkBits");
963
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700964 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
965 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700966 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700967
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700968 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
969 live_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700970
Mathieu Chartier0325e622012-09-05 14:22:51 -0700971 if (gc_type != kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700972 live_stack_->Reset();
973 }
974
Carl Shapiro58551df2011-07-24 03:09:51 -0700975 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700976 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700977
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700978 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -0700979 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700980
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700981 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700982
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700983 if (verify_mod_union_table_) {
984 zygote_mod_union_table_->Update();
985 zygote_mod_union_table_->Verify();
986 mod_union_table_->Update();
987 mod_union_table_->Verify();
988 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700989
990 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700991 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700992 live_stack_->Reset();
Mathieu Chartier0325e622012-09-05 14:22:51 -0700993 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700994 } else {
995 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
996 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700997 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -0700998
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700999 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001000 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001001 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001002
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001003 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1004 mark_sweep.SweepSystemWeaks(false);
1005 timings.AddSplit("SweepSystemWeaks");
1006
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001007 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001008 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001009 SwapBitmaps(self);
Mathieu Chartier654d3a22012-07-11 17:54:18 -07001010 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001011
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001012#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001013 // Verify that we only reach marked objects from the image space
1014 mark_sweep.VerifyImageRoots();
1015 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001016#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001017
Mathieu Chartier0325e622012-09-05 14:22:51 -07001018 if (gc_type != kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001019 mark_sweep.SweepLargeObjects(swap);
1020 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001021 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001022 } else {
1023 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001024 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001025 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001026
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001027 if (verify_system_weaks_) {
1028 mark_sweep.VerifySystemWeaks();
1029 timings.AddSplit("VerifySystemWeaks");
1030 }
1031
Elliott Hughesadb460d2011-10-05 17:02:34 -07001032 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001033 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001034 }
1035
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001036 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001037 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001038 if (!VerifyHeapReferences()) {
1039 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1040 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001041 timings.AddSplit("VerifyHeapReferencesPostGC");
1042 }
1043
Carl Shapiro58551df2011-07-24 03:09:51 -07001044 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001045 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001046
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001047 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001048 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001049
1050 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001051 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001052 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001053
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001054 // If the GC was slow, then print timings in the log.
1055 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1056 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001057 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001058 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001059 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001060 LOG(INFO) << gc_cause << " " << gc_type_str.str() << " "
Mathieu Chartier637e3482012-08-17 10:41:32 -07001061 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001062 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001063 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001064 if (VLOG_IS_ON(heap)) {
1065 timings.Dump();
1066 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001067 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001068
Mathieu Chartier0325e622012-09-05 14:22:51 -07001069 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1070 logger->Start();
1071 logger->AddLogger(timings);
1072 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001073}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001074
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001075void Heap::UpdateAndMarkModUnion(TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001076 if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001077 // Don't need to do anythign for mod union table in this case since we are only scanning dirty
1078 // cards.
1079 return;
1080 }
1081
1082 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001083 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001084 zygote_mod_union_table_->Update();
1085 timings.AddSplit("UpdateZygoteModUnionTable");
1086
1087 zygote_mod_union_table_->MarkReferences();
1088 timings.AddSplit("ZygoteMarkReferences");
1089 }
1090
1091 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1092 mod_union_table_->Update();
1093 timings.AddSplit("UpdateModUnionTable");
1094
1095 // Scans all objects in the mod-union table.
1096 mod_union_table_->MarkReferences();
1097 timings.AddSplit("MarkImageToAllocSpaceReferences");
1098}
1099
1100void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1101 Object* obj = reinterpret_cast<Object*>(arg);
1102 if (root == obj) {
1103 LOG(INFO) << "Object " << obj << " is a root";
1104 }
1105}
1106
1107class ScanVisitor {
1108 public:
1109 void operator ()(const Object* obj) const {
1110 LOG(INFO) << "Would have rescanned object " << obj;
1111 }
1112};
1113
1114class VerifyReferenceVisitor {
1115 public:
1116 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001117 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1118 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001119 : heap_(heap),
1120 failed_(failed) {
1121 }
1122
1123 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1124 // analysis.
1125 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1126 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1127 // Verify that the reference is live.
1128 if (ref != NULL && !IsLive(ref)) {
1129 CardTable* card_table = heap_->GetCardTable();
1130 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1131 MarkStack* live_stack = heap_->live_stack_.get();
1132
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001133 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001134 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " on IsDirty = "
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001135 << (*card_addr == GC_CARD_DIRTY);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001136 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1137 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1138 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001139 void* cover_begin = card_table->AddrFromCard(card_addr);
1140 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1141 GC_CARD_SIZE);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001142 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001143 << "-" << cover_end;
1144 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1145
1146 // Print out how the object is live.
1147 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001148 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1149 }
1150
1151 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1152 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1153 }
1154
1155 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1156 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001157 }
1158
1159 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001160 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001161 }
1162
1163 // Attempt to see if the card table missed the reference.
1164 ScanVisitor scan_visitor;
1165 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1166 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + GC_CARD_SIZE, scan_visitor,
1167 IdentityFunctor());
1168
1169 // Try and see if a mark sweep collector scans the reference.
1170 MarkStack* mark_stack = heap_->mark_stack_.get();
1171 MarkSweep ms(mark_stack);
1172 ms.Init();
1173 mark_stack->Reset();
1174 ms.SetFinger(reinterpret_cast<Object*>(~size_t(0)));
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001175
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001176 // All the references should end up in the mark stack.
1177 ms.ScanRoot(obj);
1178 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001179 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001180 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001181 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001182 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001183 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001184 }
1185 }
1186 mark_stack->Reset();
1187
1188 // Search to see if any of the roots reference our object.
1189 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1190 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1191 *failed_ = true;
1192 }
1193 }
1194
1195 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1196 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1197 if (bitmap != NULL) {
1198 if (bitmap->Test(obj)) {
1199 return true;
1200 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001201 } else if (heap_->GetLargeObjectsSpace()->GetLiveObjects()->Test(obj)) {
1202 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001203 } else {
1204 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001205 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001206 }
1207 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1208 // At this point we need to search the allocation since things in the live stack may get swept.
1209 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1210 return true;
1211 }
1212 // Not either in the live bitmap or allocation stack, so the object must be dead.
1213 return false;
1214 }
1215
1216 private:
1217 Heap* heap_;
1218 bool* failed_;
1219};
1220
1221class VerifyObjectVisitor {
1222 public:
1223 VerifyObjectVisitor(Heap* heap)
1224 : heap_(heap),
1225 failed_(false) {
1226
1227 }
1228
1229 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001230 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001231 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1232 MarkSweep::VisitObjectReferences(obj, visitor);
1233 }
1234
1235 bool Failed() const {
1236 return failed_;
1237 }
1238
1239 private:
1240 Heap* heap_;
1241 bool failed_;
1242};
1243
1244// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001245bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001246 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001247 // Lets sort our allocation stacks so that we can efficiently binary search them.
1248 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1249 std::sort(live_stack_->Begin(), live_stack_->End());
1250 // Perform the verification.
1251 VerifyObjectVisitor visitor(this);
1252 GetLiveBitmap()->Visit(visitor);
1253 // We don't want to verify the objects in the allocation stack since they themselves may be
1254 // pointing to dead objects if they are not reachable.
1255 if (visitor.Failed()) {
1256 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001257 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001258 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001259 return true;
1260}
1261
1262class VerifyReferenceCardVisitor {
1263 public:
1264 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1265 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1266 Locks::heap_bitmap_lock_)
1267 : heap_(heap),
1268 failed_(failed) {
1269 }
1270
1271 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1272 // analysis.
1273 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1274 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
1275 if (ref != NULL) {
1276 CardTable* card_table = heap_->GetCardTable();
1277 // If the object is not dirty and it is referencing something in the live stack other than
1278 // class, then it must be on a dirty card.
1279 if (!card_table->IsDirty(obj)) {
1280 MarkStack* live_stack = heap_->live_stack_.get();
1281 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1282 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1283 LOG(ERROR) << "Object " << obj << " found in live stack";
1284 }
1285 if (heap_->GetLiveBitmap()->Test(obj)) {
1286 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1287 }
1288 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1289 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1290
1291 // Print which field of the object is dead.
1292 if (!obj->IsObjectArray()) {
1293 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1294 CHECK(klass != NULL);
1295 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1296 CHECK(fields != NULL);
1297 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1298 const Field* cur = fields->Get(i);
1299 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1300 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1301 << PrettyField(cur);
1302 break;
1303 }
1304 }
1305 } else {
1306 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1307 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1308 if (object_array->Get(i) == ref) {
1309 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1310 }
1311 }
1312 }
1313
1314 *failed_ = true;
1315 }
1316 }
1317 }
1318 }
1319
1320 private:
1321 Heap* heap_;
1322 bool* failed_;
1323};
1324
1325class VerifyLiveStackReferences {
1326 public:
1327 VerifyLiveStackReferences(Heap* heap)
1328 : heap_(heap),
1329 failed_(false) {
1330
1331 }
1332
1333 void operator ()(const Object* obj) const
1334 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1335 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1336 MarkSweep::VisitObjectReferences(obj, visitor);
1337 }
1338
1339 bool Failed() const {
1340 return failed_;
1341 }
1342
1343 private:
1344 Heap* heap_;
1345 bool failed_;
1346};
1347
1348bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001349 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001350
1351 VerifyLiveStackReferences visitor(this);
1352 GetLiveBitmap()->Visit(visitor);
1353
1354 // We can verify objects in the live stack since none of these should reference dead objects.
1355 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1356 visitor(*it);
1357 }
1358
1359 if (visitor.Failed()) {
1360 DumpSpaces();
1361 return false;
1362 }
1363 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001364}
1365
Ian Rogers81d425b2012-09-27 16:03:43 -07001366void Heap::SwapBitmaps(Thread* self) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001367 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1368 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1369 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
1370 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
Ian Rogers81d425b2012-09-27 16:03:43 -07001371 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001372 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001373 ContinuousSpace* space = *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001374 // We never allocate into zygote spaces.
1375 if (space->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1376 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1377 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1378 space->AsAllocSpace()->SwapBitmaps();
1379 }
1380 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001381
1382 large_object_space_->SwapBitmaps();
1383 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1384 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001385}
1386
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001387void Heap::SwapStacks() {
1388 MarkStack* temp = allocation_stack_.release();
1389 allocation_stack_.reset(live_stack_.release());
1390 live_stack_.reset(temp);
1391
1392 // Sort the live stack so that we can quickly binary search it later.
1393 if (VERIFY_OBJECT_ENABLED) {
1394 std::sort(live_stack_->Begin(), live_stack_->End());
1395 }
1396}
1397
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001398void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1399 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001400 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1401 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001402 std::stringstream gc_type_str;
1403 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001404
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001405 // Suspend all threads are get exclusive access to the heap.
1406 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1407 thread_list->SuspendAll();
1408 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001409 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001410
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001411 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001412 Object* cleared_references = NULL;
1413 {
1414 MarkSweep mark_sweep(mark_stack_.get());
1415 timings.AddSplit("ctor");
1416
1417 mark_sweep.Init();
1418 timings.AddSplit("Init");
1419
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001420 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001421 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001422 if (!VerifyHeapReferences()) {
1423 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1424 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001425 timings.AddSplit("VerifyHeapReferencesPreGC");
1426 }
1427
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001428 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1429 SwapStacks();
1430
1431 // Check that all objects which reference things in the live stack are on dirty cards.
1432 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001433 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001434 // Sort the live stack so that we can quickly binary search it later.
1435 std::sort(live_stack_->Begin(), live_stack_->End());
1436 if (!VerifyMissingCardMarks()) {
1437 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1438 }
1439 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001440
1441 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1442 // TODO: Investigate using a mark stack instead of a vector.
1443 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001444 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001445 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1446 card_table_->GetDirtyCards(*it, dirty_cards);
1447 }
1448 }
1449
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001450 // Make sure that the tables have the correct pointer for the mark sweep.
1451 mod_union_table_->Init(&mark_sweep);
1452 zygote_mod_union_table_->Init(&mark_sweep);
1453
1454 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1455 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001456 ContinuousSpace* space = *it;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001457 if (space->IsImageSpace()) {
1458 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001459 timings.AddSplit("ModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001460 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1461 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001462 timings.AddSplit("ZygoteModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001463 } else {
1464 card_table_->ClearSpaceCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001465 timings.AddSplit("ClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001466 }
1467 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001468
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001469 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001470 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001471
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001472 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1473 CHECK(!GetLiveBitmap()->Test(*it));
1474 }
1475
Mathieu Chartier0325e622012-09-05 14:22:51 -07001476 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001477 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1478 // accidentally un-mark roots.
1479 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001480 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001481 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1482 mark_sweep.CopyMarkBits(*it);
1483 }
1484 }
1485 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001486 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1487 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001488 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001489 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001490 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1491 mark_sweep.CopyMarkBits(*it);
1492 }
1493 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001494 large_object_space_->CopyLiveToMarked();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001495 timings.AddSplit("CopyMarkBits");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001496 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1497 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001498 }
1499
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001500 // Marking roots is not necessary for sticky mark bits since we only actually require the
1501 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001502 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001503 mark_sweep.MarkRoots();
1504 timings.AddSplit("MarkRoots");
1505 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001506
1507 if (verify_mod_union_table_) {
1508 zygote_mod_union_table_->Update();
1509 zygote_mod_union_table_->Verify();
1510 mod_union_table_->Update();
1511 mod_union_table_->Verify();
1512 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001513 }
1514
1515 // Roots are marked on the bitmap and the mark_stack is empty.
1516 DCHECK(mark_sweep.IsMarkStackEmpty());
1517
1518 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1519 thread_list->ResumeAll();
1520 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001521 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001522 root_end = NanoTime();
1523 timings.AddSplit("RootEnd");
1524
Ian Rogers81d425b2012-09-27 16:03:43 -07001525 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001526 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001527
1528 // Mark everything as live so that sweeping system weak works correctly for sticky mark bit
1529 // GCs.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001530 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1531 live_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001532 timings.AddSplit("MarkStackAsLive");
1533
Mathieu Chartier0325e622012-09-05 14:22:51 -07001534 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001535 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001536 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001537 } else {
1538 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001539 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001540 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001541 }
1542 // Release share on mutator_lock_ and then get exclusive access.
1543 dirty_begin = NanoTime();
1544 thread_list->SuspendAll();
1545 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001546 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547
1548 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001549 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001550
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001551 // Re-mark root set.
1552 mark_sweep.ReMarkRoots();
1553 timings.AddSplit("ReMarkRoots");
1554
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001555 if (verify_missing_card_marks_) {
1556 // Since verify missing card marks uses a sweep array to empty the allocation stack, we
1557 // need to make sure that we don't free weaks which wont get swept by SweepSystemWeaks.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001558 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1559 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001560 }
1561
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001562 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001563 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564 timings.AddSplit("RecursiveMarkDirtyObjects");
1565 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001566
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001567 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001568 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001569
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001570 mark_sweep.ProcessReferences(clear_soft_references);
1571 timings.AddSplit("ProcessReferences");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001572
1573 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1574 mark_sweep.SweepSystemWeaks(false);
1575 timings.AddSplit("SweepSystemWeaks");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001576 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001577
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001578 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1579 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1580 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1581 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001582 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001583 if (swap) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001584 SwapBitmaps(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001585 }
1586
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001587 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1588 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001589 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001590 mark_sweep.SweepArray(timings, allocation_stack_.get(), swap);
1591 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001592 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001593 // We only sweep over the live stack, and the live stack should not intersect with the
1594 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001595 UnMarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1596 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001597 timings.AddSplit("UnMarkAllocStack");
1598 }
1599
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001600 if (kIsDebugBuild) {
1601 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001602 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001603 mark_sweep.VerifyImageRoots();
1604 timings.AddSplit("VerifyImageRoots");
1605 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001606
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001607 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001608 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001609 if (!VerifyHeapReferences()) {
1610 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
1611 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001612 timings.AddSplit("VerifyHeapReferencesPostGC");
1613 }
1614
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001615 thread_list->ResumeAll();
1616 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001617 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001618
1619 {
1620 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001621 if (gc_type != kGcTypeSticky) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001622 WriterMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001623 mark_sweep.SweepLargeObjects(swap);
1624 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier0325e622012-09-05 14:22:51 -07001625 mark_sweep.Sweep(gc_type == kGcTypePartial, swap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001626 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001627 WriterMutexLock mu(*Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001628 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001629 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001630 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001631 live_stack_->Reset();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001632 timings.AddSplit("Sweep");
1633 }
1634
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001635 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001636 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001637 mark_sweep.VerifySystemWeaks();
1638 timings.AddSplit("VerifySystemWeaks");
1639 }
1640
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001641 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001642 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001643 }
1644
1645 GrowForUtilization();
1646 timings.AddSplit("GrowForUtilization");
1647
1648 EnqueueClearedReferences(&cleared_references);
1649 RequestHeapTrim();
1650 timings.AddSplit("Finish");
1651
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001652 // If the GC was slow, then print timings in the log.
1653 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1654 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001655 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001656 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001657 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001658 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001659 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001660 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001661 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001662 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001663 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1664 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001665 if (VLOG_IS_ON(heap)) {
1666 timings.Dump();
1667 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001668 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001669
Mathieu Chartier0325e622012-09-05 14:22:51 -07001670 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1671 logger->Start();
1672 logger->AddLogger(timings);
1673 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001674}
1675
Ian Rogers81d425b2012-09-27 16:03:43 -07001676GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001677 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001678 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001679 bool do_wait;
1680 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001681 {
1682 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001683 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001684 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001685 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001686 if (do_wait) {
1687 // We must wait, change thread state then sleep on gc_complete_cond_;
1688 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1689 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001690 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001691 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001692 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001693 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001694 last_gc_type = last_gc_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001695 }
1696 uint64_t wait_time = NanoTime() - wait_start;
1697 if (wait_time > MsToNs(5)) {
1698 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1699 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001700 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001701 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001702 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001703}
1704
Elliott Hughesc967f782012-04-16 10:23:15 -07001705void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001706 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1707 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier0325e622012-09-05 14:22:51 -07001708 // Dump cumulative timings.
1709 LOG(INFO) << "Dumping cumulative Gc timings";
1710 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
1711 it != cumulative_timings_.end(); ++it) {
1712 it->second->Dump();
1713 }
Elliott Hughesc967f782012-04-16 10:23:15 -07001714}
1715
1716size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001717 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001718}
1719
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001720void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001721 AllocSpace* alloc_space = alloc_space_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001722 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001723 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001724 << PrettySize(GetMaxMemory());
1725 max_allowed_footprint = GetMaxMemory();
1726 }
1727 // We want to update the footprint for just the alloc space.
1728 max_allowed_footprint -= large_object_space_->GetNumBytesAllocated();
1729 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1730 if ((*it)->IsAllocSpace()) {
1731 AllocSpace* alloc_space = (*it)->AsAllocSpace();
1732 if (alloc_space != alloc_space_) {
1733 max_allowed_footprint -= alloc_space->GetNumBytesAllocated();
1734 }
1735 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001736 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001737 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001738}
1739
Ian Rogers3bb17a62012-01-27 23:56:44 -08001740// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001741static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001742// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1743// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001744static const size_t kHeapMinFree = kHeapIdealFree / 4;
1745
Carl Shapiro69759ea2011-07-21 18:13:35 -07001746void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001747 // We know what our utilization is at this moment.
1748 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1749 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
1750 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1751 target_size = num_bytes_allocated_ + kHeapIdealFree;
1752 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1753 target_size = num_bytes_allocated_ + kHeapMinFree;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001754 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001755
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001756 // Calculate when to perform the next ConcurrentGC.
1757 if (GetFreeMemory() < concurrent_min_free_) {
1758 // Not enough free memory to perform concurrent GC.
1759 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1760 } else {
1761 // Start a concurrent Gc when we get close to the target size.
1762 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001763 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001764
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001765 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001766}
1767
jeffhaoc1160702011-10-27 15:48:45 -07001768void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001769 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001770 alloc_space_->ClearGrowthLimit();
1771}
1772
Elliott Hughesadb460d2011-10-05 17:02:34 -07001773void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001774 MemberOffset reference_queue_offset,
1775 MemberOffset reference_queueNext_offset,
1776 MemberOffset reference_pendingNext_offset,
1777 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001778 reference_referent_offset_ = reference_referent_offset;
1779 reference_queue_offset_ = reference_queue_offset;
1780 reference_queueNext_offset_ = reference_queueNext_offset;
1781 reference_pendingNext_offset_ = reference_pendingNext_offset;
1782 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1783 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1784 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1785 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1786 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1787 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1788}
1789
1790Object* Heap::GetReferenceReferent(Object* reference) {
1791 DCHECK(reference != NULL);
1792 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1793 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1794}
1795
1796void Heap::ClearReferenceReferent(Object* reference) {
1797 DCHECK(reference != NULL);
1798 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1799 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1800}
1801
1802// Returns true if the reference object has not yet been enqueued.
1803bool Heap::IsEnqueuable(const Object* ref) {
1804 DCHECK(ref != NULL);
1805 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1806 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1807 return (queue != NULL) && (queue_next == NULL);
1808}
1809
1810void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1811 DCHECK(ref != NULL);
1812 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1813 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1814 EnqueuePendingReference(ref, cleared_reference_list);
1815}
1816
1817void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1818 DCHECK(ref != NULL);
1819 DCHECK(list != NULL);
1820
1821 if (*list == NULL) {
1822 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1823 *list = ref;
1824 } else {
1825 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1826 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1827 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1828 }
1829}
1830
1831Object* Heap::DequeuePendingReference(Object** list) {
1832 DCHECK(list != NULL);
1833 DCHECK(*list != NULL);
1834 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1835 Object* ref;
1836 if (*list == head) {
1837 ref = *list;
1838 *list = NULL;
1839 } else {
1840 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1841 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1842 ref = head;
1843 }
1844 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1845 return ref;
1846}
1847
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001848void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001849 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001850 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001851 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001852 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1853 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001854}
1855
1856size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001857 return num_bytes_allocated_;
1858}
1859
1860size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001861 size_t total = 0;
1862 // TODO: C++0x
1863 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1864 Space* space = *it;
1865 if (space->IsAllocSpace()) {
1866 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1867 }
1868 }
1869 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001870}
1871
1872size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001873 return concurrent_start_size_;
1874}
1875
1876size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001877 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001878}
1879
1880void Heap::EnqueueClearedReferences(Object** cleared) {
1881 DCHECK(cleared != NULL);
1882 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001883 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001884 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001885 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001886 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1887 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001888 *cleared = NULL;
1889 }
1890}
1891
Ian Rogers1f539342012-10-03 21:09:42 -07001892void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001893 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001894 Runtime* runtime = Runtime::Current();
1895 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1896 !runtime->IsConcurrentGcEnabled()) {
1897 return;
1898 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001899 {
1900 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1901 if (runtime->IsShuttingDown()) {
1902 return;
1903 }
1904 }
1905 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001906 return;
1907 }
1908
1909 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001910 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001911 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1912 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001913 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1914 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001915 CHECK(!env->ExceptionCheck());
1916 requesting_gc_ = false;
1917}
1918
Ian Rogers81d425b2012-09-27 16:03:43 -07001919void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001920 {
1921 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1922 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
1923 return;
1924 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001925 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001926
Ian Rogers81d425b2012-09-27 16:03:43 -07001927 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001928 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07001929 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001930 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001931 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001932 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001933 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001934 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001935 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001936}
1937
Ian Rogers81d425b2012-09-27 16:03:43 -07001938void Heap::Trim(Thread* self) {
1939 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001940 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001941}
1942
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001943void Heap::RequestHeapTrim() {
1944 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1945 // because that only marks object heads, so a large array looks like lots of empty space. We
1946 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1947 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1948 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1949 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001950 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001951 float utilization =
1952 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1953 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1954 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1955 // heap trim occurred in the last two seconds.
1956 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001957 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001958
1959 Thread* self = Thread::Current();
1960 {
1961 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1962 Runtime* runtime = Runtime::Current();
1963 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1964 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1965 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1966 // as we don't hold the lock while requesting the trim).
1967 return;
1968 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001969 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001970 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001971 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001972 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1973 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001974 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1975 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001976 CHECK(!env->ExceptionCheck());
1977}
1978
Carl Shapiro69759ea2011-07-21 18:13:35 -07001979} // namespace art