blob: f55efd68a08054dfffd1a44469bb6680b5f87b69 [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
Elliott Hughes767a1472011-10-26 18:49:02 -070025#include "debugger.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070026#include "gc/atomic_stack.h"
27#include "gc/card_table.h"
28#include "gc/heap_bitmap.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070029#include "gc/large_object_space.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070030#include "gc/mark_sweep.h"
31#include "gc/mod_union_table.h"
32#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070033#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080035#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080036#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070037#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070038#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070039#include "sirt_ref.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070040#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070041#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070042#include "timing_logger.h"
43#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070044#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070045
46namespace art {
47
Mathieu Chartier02b6a782012-10-26 13:51:26 -070048static const bool kDumpGcPerformanceOnShutdown = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070049const double Heap::kDefaultTargetUtilization = 0.5;
50
Elliott Hughesae80b492012-04-24 10:43:17 -070051static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080052 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080053 std::vector<std::string> boot_class_path;
54 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070055 if (boot_class_path.empty()) {
56 LOG(FATAL) << "Failed to generate image because no boot class path specified";
57 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080058
59 std::vector<char*> arg_vector;
60
61 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070062 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080063 const char* dex2oat = dex2oat_string.c_str();
64 arg_vector.push_back(strdup(dex2oat));
65
66 std::string image_option_string("--image=");
67 image_option_string += image_file_name;
68 const char* image_option = image_option_string.c_str();
69 arg_vector.push_back(strdup(image_option));
70
71 arg_vector.push_back(strdup("--runtime-arg"));
72 arg_vector.push_back(strdup("-Xms64m"));
73
74 arg_vector.push_back(strdup("--runtime-arg"));
75 arg_vector.push_back(strdup("-Xmx64m"));
76
77 for (size_t i = 0; i < boot_class_path.size(); i++) {
78 std::string dex_file_option_string("--dex-file=");
79 dex_file_option_string += boot_class_path[i];
80 const char* dex_file_option = dex_file_option_string.c_str();
81 arg_vector.push_back(strdup(dex_file_option));
82 }
83
84 std::string oat_file_option_string("--oat-file=");
85 oat_file_option_string += image_file_name;
86 oat_file_option_string.erase(oat_file_option_string.size() - 3);
87 oat_file_option_string += "oat";
88 const char* oat_file_option = oat_file_option_string.c_str();
89 arg_vector.push_back(strdup(oat_file_option));
90
jeffhao8161c032012-10-31 15:50:00 -070091 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
92 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -080093
Elliott Hughes48436bb2012-02-07 15:23:28 -080094 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080095 LOG(INFO) << command_line;
96
Elliott Hughes48436bb2012-02-07 15:23:28 -080097 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -080098 char** argv = &arg_vector[0];
99
100 // fork and exec dex2oat
101 pid_t pid = fork();
102 if (pid == 0) {
103 // no allocation allowed between fork and exec
104
105 // change process groups, so we don't get reaped by ProcessManager
106 setpgid(0, 0);
107
108 execv(dex2oat, argv);
109
110 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
111 return false;
112 } else {
113 STLDeleteElements(&arg_vector);
114
115 // wait for dex2oat to finish
116 int status;
117 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
118 if (got_pid != pid) {
119 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
120 return false;
121 }
122 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
123 LOG(ERROR) << dex2oat << " failed: " << command_line;
124 return false;
125 }
126 }
127 return true;
128}
129
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700130void Heap::UnReserveOatFileAddressRange() {
131 oat_file_map_.reset(NULL);
132}
133
Mathieu Chartier0051be62012-10-12 17:47:11 -0700134Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
135 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700136 const std::string& original_image_file_name, bool concurrent_gc)
137 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800138 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700139 concurrent_gc_(concurrent_gc),
140 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800141 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700142 last_gc_type_(kGcTypeNone),
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700143 enforce_heap_growth_rate_(false),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700144 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700145 max_allowed_footprint_(initial_size),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700146 concurrent_start_size_(128 * KB),
147 concurrent_min_free_(256 * KB),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700148 concurrent_start_bytes_(initial_size - concurrent_start_size_),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700149 sticky_gc_count_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700150 total_bytes_freed_(0),
151 total_objects_freed_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700152 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800153 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700154 verify_missing_card_marks_(false),
155 verify_system_weaks_(false),
156 verify_pre_gc_heap_(false),
157 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700158 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700159 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700160 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700161 min_remaining_space_for_sticky_gc_(1 * MB),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700162 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700163 requesting_gc_(false),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700164 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800165 reference_referent_offset_(0),
166 reference_queue_offset_(0),
167 reference_queueNext_offset_(0),
168 reference_pendingNext_offset_(0),
169 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700170 min_free_(min_free),
171 max_free_(max_free),
172 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700173 total_paused_time_(0),
174 total_wait_time_(0),
175 measure_allocation_time_(false),
176 total_allocation_time_(0),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700177 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800178 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800179 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700180 }
181
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700182 live_bitmap_.reset(new HeapBitmap(this));
183 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700184
Ian Rogers30fab402012-01-23 15:43:46 -0800185 // Requested begin for the alloc space, to follow the mapped image and oat files
186 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800187 std::string image_file_name(original_image_file_name);
188 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700189 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700190
Brian Carlstrom5643b782012-02-05 12:32:53 -0800191 if (OS::FileExists(image_file_name.c_str())) {
192 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700193 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800194 } else {
195 // If the /system file didn't exist, we need to use one from the art-cache.
196 // If the cache file exists, try to open, but if it fails, regenerate.
197 // If it does not exist, generate.
198 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
199 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700200 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800201 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700202 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700203 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700204 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800205 }
206 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700207
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700208 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700209 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800210 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
211 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700212 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
213 CHECK_GT(oat_end_addr, image_space->End());
214
215 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
216 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
217 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
218 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
219 reinterpret_cast<byte*>(reserve_begin),
220 reserve_end - reserve_begin, PROT_READ));
221
Ian Rogers30fab402012-01-23 15:43:46 -0800222 if (oat_end_addr > requested_begin) {
223 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700224 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700225 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700226 }
227
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700228 // Allocate the large object space.
229 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700230 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
231 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
232
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700233 UniquePtr<DlMallocSpace> alloc_space(DlMallocSpace::Create("alloc space", initial_size,
234 growth_limit, capacity,
235 requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700236 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700237 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700238 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700239 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700240
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700241 // Spaces are sorted in order of Begin().
242 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700243 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
244 if (spaces_.back()->IsAllocSpace()) {
245 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
246 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700247
Ian Rogers30fab402012-01-23 15:43:46 -0800248 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700249 // TODO: C++0x
250 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
251 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800252 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700253 ImageSpace* image_space = space->AsImageSpace();
254 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800255 }
256 }
257
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800258 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700259 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
260 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700261
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700262 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
263 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700264
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700265 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
266 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700267
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700268 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700269 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800271 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700272 static const size_t default_mark_stack_size = 64 * KB;
273 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
274 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700275 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700276 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
277 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700278
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800279 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700280 // but we can create the heap lock now. We don't create it earlier to
281 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700282 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700283 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
284 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700285
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700286 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
287 reference_queue_lock_.reset(new Mutex("reference queue lock"));
288
289 CHECK(max_allowed_footprint_ != 0);
290
Mathieu Chartier0325e622012-09-05 14:22:51 -0700291 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700292 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
293 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700294 std::ostringstream name;
295 name << static_cast<GcType>(i);
296 cumulative_timings_.Put(static_cast<GcType>(i),
297 new CumulativeLogger(name.str().c_str(), true));
298 }
299
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800300 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800301 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700302 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700303}
304
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700305void Heap::CreateThreadPool() {
306 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
307 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
308 // workers to complete.
309 thread_pool_.reset(new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
310}
311
312void Heap::DeleteThreadPool() {
313 thread_pool_.reset(NULL);
314}
315
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700316// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700317struct SpaceSorter {
318 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700319 return a->Begin() < b->Begin();
320 }
321};
322
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700323void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700324 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700325 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700326 DCHECK(space->GetLiveBitmap() != NULL);
327 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700328 DCHECK(space->GetMarkBitmap() != NULL);
329 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800330 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700331 if (space->IsAllocSpace()) {
332 alloc_space_ = space->AsAllocSpace();
333 }
334
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700335 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
336 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700337
338 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
339 // avoid redundant marking.
340 bool seen_zygote = false, seen_alloc = false;
341 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
342 Space* space = *it;
343 if (space->IsImageSpace()) {
344 DCHECK(!seen_zygote);
345 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700346 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700347 DCHECK(!seen_alloc);
348 seen_zygote = true;
349 } else if (space->IsAllocSpace()) {
350 seen_alloc = true;
351 }
352 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800353}
354
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700355void Heap::DumpGcPerformanceInfo() {
356 // Dump cumulative timings.
357 LOG(INFO) << "Dumping cumulative Gc timings";
358 uint64_t total_duration = 0;
359 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
360 it != cumulative_timings_.end(); ++it) {
361 CumulativeLogger* logger = it->second;
362 if (logger->GetTotalNs() != 0) {
363 logger->Dump();
364 total_duration += logger->GetTotalNs();
365 }
366 }
367 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
368 size_t total_objects_allocated = GetTotalObjectsAllocated();
369 size_t total_bytes_allocated = GetTotalBytesAllocated();
370 if (total_duration != 0) {
371 const double total_seconds = double(total_duration / 1000) / 1000000.0;
372 LOG(INFO) << "Total time spent in GC: " << PrettyDuration(total_duration);
373 LOG(INFO) << "Mean GC size throughput: "
374 << PrettySize(GetTotalBytesFreed() / total_seconds) << "/s";
375 LOG(INFO) << "Mean GC object throughput: " << GetTotalObjectsFreed() / total_seconds << "/s";
376 }
377 LOG(INFO) << "Total number of allocations: " << total_objects_allocated;
378 LOG(INFO) << "Total bytes allocated " << PrettySize(total_bytes_allocated);
379 if (measure_allocation_time_) {
380 LOG(INFO) << "Total time spent allocating: " << PrettyDuration(allocation_time);
381 LOG(INFO) << "Mean allocation time: "
382 << PrettyDuration(allocation_time / total_objects_allocated);
383 }
384 LOG(INFO) << "Total mutator paused time: " << PrettyDuration(total_paused_time_);
385 LOG(INFO) << "Total waiting for Gc to complete time: " << PrettyDuration(total_wait_time_);
386}
387
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800388Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700389 if (kDumpGcPerformanceOnShutdown) {
390 DumpGcPerformanceInfo();
391 }
392
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700393 // If we don't reset then the mark stack complains in it's destructor.
394 allocation_stack_->Reset();
395 live_stack_->Reset();
396
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800397 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800398 // We can't take the heap lock here because there might be a daemon thread suspended with the
399 // heap lock held. We know though that no non-daemon threads are executing, and we know that
400 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
401 // 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 -0700402 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700403 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700404 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700405}
406
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700407ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700408 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700409 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
410 if ((*it)->Contains(obj)) {
411 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700412 }
413 }
414 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
415 return NULL;
416}
417
418ImageSpace* Heap::GetImageSpace() {
419 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700420 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
421 if ((*it)->IsImageSpace()) {
422 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700423 }
424 }
425 return NULL;
426}
427
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700428DlMallocSpace* Heap::GetAllocSpace() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700429 return alloc_space_;
430}
431
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700432static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700433 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700434 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700435 size_t chunk_free_bytes = chunk_size - used_bytes;
436 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
437 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700438 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700439}
440
Ian Rogers50b35e22012-10-04 10:09:15 -0700441Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700442 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
443 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
444 strlen(ClassHelper(c).GetDescriptor()) == 0);
445 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700446
447 Object* obj = NULL;
448 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700449 uint64_t allocation_start = 0;
450 if (measure_allocation_time_) {
451 allocation_start = NanoTime();
452 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700453
454 // We need to have a zygote space or else our newly allocated large object can end up in the
455 // Zygote resulting in it being prematurely freed.
456 // We can only do this for primive objects since large objects will not be within the card table
457 // range. This also means that we rely on SetClass not dirtying the object's card.
458 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700459 size = RoundUp(byte_count, kPageSize);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700460 obj = Allocate(self, large_object_space_.get(), size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700461 // Make sure that our large object didn't get placed anywhere within the space interval or else
462 // it breaks the immune range.
463 DCHECK(obj == NULL ||
464 reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
465 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700466 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700467 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700468
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700469 // Ensure that we did not allocate into a zygote space.
470 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
471 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700472 }
473
Mathieu Chartier037813d2012-08-23 16:44:59 -0700474 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700475 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700476
477 // Record allocation after since we want to use the atomic add for the atomic fence to guard
478 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700479 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700480
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 if (Dbg::IsAllocTrackingEnabled()) {
482 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700483 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700484 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700485 // We already have a request pending, no reason to start more until we update
486 // concurrent_start_bytes_.
487 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700489 SirtRef<Object> ref(self, obj);
490 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700491 }
492 VerifyObject(obj);
493
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700494 if (measure_allocation_time_) {
495 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
496 }
497
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498 return obj;
499 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700500 int64_t total_bytes_free = GetFreeMemory();
501 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700502 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700503 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
504 if ((*it)->IsAllocSpace()) {
505 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700506 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700507 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700508
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700509 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 -0700510 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700511 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700512 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700513}
514
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700515bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700516 // Note: we deliberately don't take the lock here, and mustn't test anything that would
517 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700518 if (obj == NULL) {
519 return true;
520 }
521 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700522 return false;
523 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800524 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800525 if (spaces_[i]->Contains(obj)) {
526 return true;
527 }
528 }
Mathieu Chartier0b0b5152012-10-15 13:53:46 -0700529 // Note: Doing this only works for the free list version of the large object space since the
530 // multiple memory map version uses a lock to do the contains check.
531 return large_object_space_->Contains(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700532}
533
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700534bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700535 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700536 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700537}
538
Elliott Hughes3e465b12011-09-02 18:26:12 -0700539#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700540void Heap::VerifyObject(const Object* obj) {
jeffhao4eb68ed2012-10-17 16:41:07 -0700541 if (obj == NULL || this == NULL || !verify_objects_ || Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700542 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700543 return;
544 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700545 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700546}
547#endif
548
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700549void Heap::DumpSpaces() {
550 // TODO: C++0x auto
551 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700552 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700553 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
554 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
555 LOG(INFO) << space << " " << *space << "\n"
556 << live_bitmap << " " << *live_bitmap << "\n"
557 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700558 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700559 if (large_object_space_.get() != NULL) {
560 large_object_space_->Dump(LOG(INFO));
561 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700562}
563
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700564void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700565 if (!IsAligned<kObjectAlignment>(obj)) {
566 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700567 }
568
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700569 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
570 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700571 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700572 // Check the allocation stack / live stack.
573 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
574 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
575 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700576 if (large_object_space_->GetLiveObjects()->Test(obj)) {
577 DumpSpaces();
578 LOG(FATAL) << "Object is dead: " << obj;
579 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700580 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700581 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700582
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700583 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700584 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700585 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
586 Object::ClassOffset().Int32Value();
587 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
588 if (c == NULL) {
589 LOG(FATAL) << "Null class in object: " << obj;
590 } else if (!IsAligned<kObjectAlignment>(c)) {
591 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
592 } else if (!GetLiveBitmap()->Test(c)) {
593 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
594 }
595 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
596 // Note: we don't use the accessors here as they have internal sanity checks
597 // that we don't want to run
598 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
599 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
600 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
601 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
602 CHECK_EQ(c_c, c_c_c);
603 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700604}
605
Brian Carlstrom78128a62011-09-15 17:21:19 -0700606void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700607 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700608 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700609}
610
611void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700612 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700613 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700614}
615
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700616void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700617 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700618 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700619 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700620
621 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700622 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700623 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700624 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700625
626 // TODO: Update these atomically.
627 RuntimeStats* global_stats = Runtime::Current()->GetStats();
628 ++global_stats->allocated_objects;
629 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700630 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700631
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700632 // This is safe to do since the GC will never free objects which are neither in the allocation
633 // stack or the live bitmap.
634 while (!allocation_stack_->AtomicPushBack(obj)) {
635 Thread* self = Thread::Current();
636 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
637 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
638 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
639 self->TransitionFromSuspendedToRunnable();
640 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700641}
642
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700643void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700644 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
645 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700646
647 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700648 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700649 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700650 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700651
652 // TODO: Do this concurrently.
653 RuntimeStats* global_stats = Runtime::Current()->GetStats();
654 global_stats->freed_objects += freed_objects;
655 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700656 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700657}
658
Ian Rogers50b35e22012-10-04 10:09:15 -0700659Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700660 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700661 if (enforce_heap_growth_rate_ && num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
662 if (grow) {
663 // Grow the heap by alloc_size extra bytes.
664 max_allowed_footprint_ = std::min(max_allowed_footprint_ + alloc_size, growth_limit_);
665 VLOG(gc) << "Grow heap to " << PrettySize(max_allowed_footprint_)
666 << " for a " << PrettySize(alloc_size) << " allocation";
667 } else {
668 return NULL;
669 }
670 }
671
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700672 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700673 // Completely out of memory.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700674 return NULL;
675 }
676
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700677 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700678}
679
Ian Rogers50b35e22012-10-04 10:09:15 -0700680Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700681 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
682 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700683 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700684 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700685
Ian Rogers50b35e22012-10-04 10:09:15 -0700686 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700687 if (ptr != NULL) {
688 return ptr;
689 }
690
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700691 // The allocation failed. If the GC is running, block until it completes, and then retry the
692 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700693 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700694 if (last_gc != kGcTypeNone) {
695 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700696 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700697 if (ptr != NULL) {
698 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700699 }
700 }
701
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700702 // Loop through our different Gc types and try to Gc until we get enough free memory.
703 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
704 bool run_gc = false;
705 GcType gc_type = static_cast<GcType>(i);
706 switch (gc_type) {
707 case kGcTypeSticky: {
708 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700709 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
710 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700711 break;
712 }
713 case kGcTypePartial:
714 run_gc = have_zygote_space_;
715 break;
716 case kGcTypeFull:
717 run_gc = true;
718 break;
719 default:
720 break;
721 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700722
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700723 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700724 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
725
726 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700727 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700728 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
729 i = static_cast<size_t>(gc_type_ran);
730 self->TransitionFromSuspendedToRunnable();
731
732 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700733 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700734 if (ptr != NULL) {
735 return ptr;
736 }
737 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700738 }
739
740 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700741 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700742 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700743 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700744 return ptr;
745 }
746
Elliott Hughes81ff3182012-03-23 20:35:56 -0700747 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
748 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
749 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700750
Elliott Hughes418dfe72011-10-06 18:56:27 -0700751 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700752 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
753 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700754
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700755 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700756 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700757 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700758 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700759 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700760}
761
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700762void Heap::SetTargetHeapUtilization(float target) {
763 DCHECK_GT(target, 0.0f); // asserted in Java code
764 DCHECK_LT(target, 1.0f);
765 target_utilization_ = target;
766}
767
768int64_t Heap::GetMaxMemory() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700769 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700770}
771
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700772int64_t Heap::GetTotalMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700773 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700774}
775
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700776int64_t Heap::GetFreeMemory() const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700777 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700778}
779
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700780size_t Heap::GetTotalBytesFreed() const {
781 return total_bytes_freed_;
782}
783
784size_t Heap::GetTotalObjectsFreed() const {
785 return total_objects_freed_;
786}
787
788size_t Heap::GetTotalObjectsAllocated() const {
789 size_t total = large_object_space_->GetTotalObjectsAllocated();
790 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
791 Space* space = *it;
792 if (space->IsAllocSpace()) {
793 total += space->AsAllocSpace()->GetTotalObjectsAllocated();
794 }
795 }
796 return total;
797}
798
799size_t Heap::GetTotalBytesAllocated() const {
800 size_t total = large_object_space_->GetTotalBytesAllocated();
801 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
802 Space* space = *it;
803 if (space->IsAllocSpace()) {
804 total += space->AsAllocSpace()->GetTotalBytesAllocated();
805 }
806 }
807 return total;
808}
809
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700810class InstanceCounter {
811 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700812 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700813 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700814 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700815
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700816 }
817
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700818 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
819 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700820 if (count_assignable_) {
821 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700822 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700823 }
824 } else {
825 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700826 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700827 }
828 }
829 }
830
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700831 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700832 Class* class_;
833 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700834 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700835};
836
837int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700838 size_t count = 0;
839 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700840 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700841 GetLiveBitmap()->Visit(counter);
842 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700843}
844
Ian Rogers30fab402012-01-23 15:43:46 -0800845void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700846 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
847 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700848 Thread* self = Thread::Current();
849 WaitForConcurrentGcToComplete(self);
850 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700851 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
852 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700853}
854
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700855void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700856 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800857 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
858 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700859 Thread* self = Thread::Current();
860 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700861
862 // Try to see if we have any Zygote spaces.
863 if (have_zygote_space_) {
864 return;
865 }
866
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700867 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
868
869 {
870 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700871 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700872 FlushAllocStack();
873 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700874
875 // Replace the first alloc space we find with a zygote space.
876 // TODO: C++0x auto
877 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
878 if ((*it)->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700879 DlMallocSpace* zygote_space = (*it)->AsAllocSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700880
881 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
882 // of the remaining available heap memory.
883 alloc_space_ = zygote_space->CreateZygoteSpace();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700884 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700885
886 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700887 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700888 AddSpace(alloc_space_);
889 have_zygote_space_ = true;
890 break;
891 }
892 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700893
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700894 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700895 // TODO: C++0x
896 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
897 it != cumulative_timings_.end(); ++it) {
898 it->second->Reset();
899 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700900}
901
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700902void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700903 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
904 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700905 allocation_stack_->Reset();
906}
907
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700908size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700909 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700910}
911
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700912void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
913 Object** limit = stack->End();
914 for (Object** it = stack->Begin(); it != limit; ++it) {
915 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700916 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700917 if (LIKELY(bitmap->HasAddress(obj))) {
918 bitmap->Set(obj);
919 } else {
920 large_objects->Set(obj);
921 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700922 }
923}
924
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700925void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
926 Object** limit = stack->End();
927 for (Object** it = stack->Begin(); it != limit; ++it) {
928 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700929 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700930 if (LIKELY(bitmap->HasAddress(obj))) {
931 bitmap->Clear(obj);
932 } else {
933 large_objects->Clear(obj);
934 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700935 }
936}
937
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700938GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700939 Thread* self = Thread::Current();
940 Locks::mutator_lock_->AssertNotHeld(self);
941 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700942
Ian Rogers120f1c72012-09-28 17:17:10 -0700943 if (self->IsHandlingStackOverflow()) {
944 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
945 }
946
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700947 // Ensure there is only one GC at a time.
948 bool start_collect = false;
949 while (!start_collect) {
950 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700951 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700952 if (!is_gc_running_) {
953 is_gc_running_ = true;
954 start_collect = true;
955 }
956 }
957 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700958 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700959 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
960 // Not doing at the moment to ensure soft references are cleared.
961 }
962 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700963 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700964
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700965 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
966 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
967 ++Thread::Current()->GetStats()->gc_for_alloc_count;
968 }
969
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700970 // We need to do partial GCs every now and then to avoid the heap growing too much and
971 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700972 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700973 gc_type = have_zygote_space_ ? kGcTypePartial : kGcTypeFull;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700974 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700975 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700976 sticky_gc_count_ = 0;
977 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800978
Mathieu Chartier637e3482012-08-17 10:41:32 -0700979 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700980 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700981 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700982 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700983 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700984 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700985
Ian Rogers15bf2d32012-08-28 17:33:04 -0700986 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700987 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700988 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700989 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700990 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -0700991 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700992 }
993 // Inform DDMS that a GC completed.
994 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700995 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700996}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700997
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700998void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
999 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -07001001
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001002 std::stringstream gc_type_str;
1003 gc_type_str << gc_type << " ";
1004
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001005 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001006 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -07001007 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1008 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001009 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001010 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001011
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001012 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001013 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -07001014 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001015 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -07001016 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001017 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -07001018
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001019 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001020 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001021 if (!VerifyHeapReferences()) {
1022 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1023 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001024 timings.AddSplit("VerifyHeapReferencesPreGC");
1025 }
1026
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001027 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001028 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001029
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001030 // Process dirty cards and add dirty cards to mod union tables.
1031 ProcessCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001032
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001033 // Bind live to mark bitmaps.
1034 BindBitmaps(gc_type, mark_sweep);
1035 timings.AddSplit("BindBitmaps");
1036
Ian Rogers120f1c72012-09-28 17:17:10 -07001037 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Carl Shapiro58551df2011-07-24 03:09:51 -07001038 mark_sweep.MarkRoots();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001039 mark_sweep.MarkConcurrentRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001040 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -07001041
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001042 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1043
1044 if (gc_type != kGcTypeSticky) {
1045 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1046 live_stack_.get());
1047 timings.AddSplit("MarkStackAsLive");
1048 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001049
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001050 if (verify_mod_union_table_) {
1051 zygote_mod_union_table_->Update();
1052 zygote_mod_union_table_->Verify();
1053 mod_union_table_->Update();
1054 mod_union_table_->Verify();
1055 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001056
1057 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001058 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001059 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001060 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001061 // Use -1 since we want to scan all of the cards which we aged earlier when we did
1062 // ClearCards. These are the cards which were dirty before the GC started.
1063 mark_sweep.RecursiveMarkDirtyObjects(CardTable::kCardDirty - 1);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001064 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001065 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -07001066
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001067 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -08001068 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -07001069 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -07001070
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001071 if (kIsDebugBuild) {
1072 // Verify that we only reach marked objects from the image space
1073 mark_sweep.VerifyImageRoots();
1074 timings.AddSplit("VerifyImageRoots");
1075 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001076
Mathieu Chartier0325e622012-09-05 14:22:51 -07001077 if (gc_type != kGcTypeSticky) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001078 mark_sweep.Sweep(timings, gc_type == kGcTypePartial, false);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001079 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001080 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001081 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001082 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001083 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001084 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001085 live_stack_->Reset();
1086
1087 // Unbind the live and mark bitmaps.
1088 mark_sweep.UnBindBitmaps();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001089 if (gc_type == kGcTypeSticky) {
1090 SwapLargeObjects();
1091 } else {
1092 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001093 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001094 timings.AddSplit("SwapBitmaps");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001095
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001096 if (verify_system_weaks_) {
1097 mark_sweep.VerifySystemWeaks();
1098 timings.AddSplit("VerifySystemWeaks");
1099 }
1100
Elliott Hughesadb460d2011-10-05 17:02:34 -07001101 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001102 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001103 total_bytes_freed_ += bytes_freed;
1104 total_objects_freed_ += mark_sweep.GetFreedObjects();
Carl Shapiro58551df2011-07-24 03:09:51 -07001105 }
1106
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001107 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001108 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001109 if (!VerifyHeapReferences()) {
1110 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1111 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001112 timings.AddSplit("VerifyHeapReferencesPostGC");
1113 }
1114
Carl Shapiro58551df2011-07-24 03:09:51 -07001115 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001116 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001117
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001118 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001119 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001120
1121 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001122 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001123 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001124
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001125 // If the GC was slow, then print timings in the log.
1126 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001127 total_paused_time_ += duration;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001128 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001129 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001130 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001131 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001132 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001133 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001134 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001135 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001136 if (VLOG_IS_ON(heap)) {
1137 timings.Dump();
1138 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001139 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001140
Mathieu Chartier0325e622012-09-05 14:22:51 -07001141 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1142 logger->Start();
1143 logger->AddLogger(timings);
1144 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001145}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001146
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001147void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001148 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001149 // Don't need to do anything for mod union table in this case since we are only scanning dirty
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001150 // cards.
1151 return;
1152 }
1153
1154 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001155 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001156 zygote_mod_union_table_->Update();
1157 timings.AddSplit("UpdateZygoteModUnionTable");
1158
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001159 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001160 timings.AddSplit("ZygoteMarkReferences");
1161 }
1162
1163 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1164 mod_union_table_->Update();
1165 timings.AddSplit("UpdateModUnionTable");
1166
1167 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001168 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001169 timings.AddSplit("MarkImageToAllocSpaceReferences");
1170}
1171
1172void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1173 Object* obj = reinterpret_cast<Object*>(arg);
1174 if (root == obj) {
1175 LOG(INFO) << "Object " << obj << " is a root";
1176 }
1177}
1178
1179class ScanVisitor {
1180 public:
1181 void operator ()(const Object* obj) const {
1182 LOG(INFO) << "Would have rescanned object " << obj;
1183 }
1184};
1185
1186class VerifyReferenceVisitor {
1187 public:
1188 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001189 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1190 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001191 : heap_(heap),
1192 failed_(failed) {
1193 }
1194
1195 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1196 // analysis.
1197 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1198 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1199 // Verify that the reference is live.
1200 if (ref != NULL && !IsLive(ref)) {
1201 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001202 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1203 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001204
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001205 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001206 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1207 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1208 << "Obj type " << PrettyTypeOf(obj) << "\n"
1209 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001210 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001211 void* cover_begin = card_table->AddrFromCard(card_addr);
1212 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001213 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001214 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001215 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001216 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1217
1218 // Print out how the object is live.
1219 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001220 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1221 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001222 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1223 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1224 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001225 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1226 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001227 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001228 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001229 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001230 }
1231
1232 // Attempt to see if the card table missed the reference.
1233 ScanVisitor scan_visitor;
1234 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001235 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001236 scan_visitor, VoidFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001237
1238 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001239 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240 MarkSweep ms(mark_stack);
1241 ms.Init();
1242 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001243 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001244
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001245 // All the references should end up in the mark stack.
1246 ms.ScanRoot(obj);
1247 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001248 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001249 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001250 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001251 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001252 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001253 }
1254 }
1255 mark_stack->Reset();
1256
1257 // Search to see if any of the roots reference our object.
1258 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1259 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1260 *failed_ = true;
1261 }
1262 }
1263
1264 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1265 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1266 if (bitmap != NULL) {
1267 if (bitmap->Test(obj)) {
1268 return true;
1269 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001270 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001271 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001272 } else {
1273 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001274 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001275 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001276 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001277 // At this point we need to search the allocation since things in the live stack may get swept.
1278 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1279 return true;
1280 }
1281 // Not either in the live bitmap or allocation stack, so the object must be dead.
1282 return false;
1283 }
1284
1285 private:
1286 Heap* heap_;
1287 bool* failed_;
1288};
1289
1290class VerifyObjectVisitor {
1291 public:
1292 VerifyObjectVisitor(Heap* heap)
1293 : heap_(heap),
1294 failed_(false) {
1295
1296 }
1297
1298 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001299 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001300 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1301 MarkSweep::VisitObjectReferences(obj, visitor);
1302 }
1303
1304 bool Failed() const {
1305 return failed_;
1306 }
1307
1308 private:
1309 Heap* heap_;
1310 bool failed_;
1311};
1312
1313// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001314bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001315 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001316 // Lets sort our allocation stacks so that we can efficiently binary search them.
1317 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1318 std::sort(live_stack_->Begin(), live_stack_->End());
1319 // Perform the verification.
1320 VerifyObjectVisitor visitor(this);
1321 GetLiveBitmap()->Visit(visitor);
1322 // We don't want to verify the objects in the allocation stack since they themselves may be
1323 // pointing to dead objects if they are not reachable.
1324 if (visitor.Failed()) {
1325 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001326 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001327 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001328 return true;
1329}
1330
1331class VerifyReferenceCardVisitor {
1332 public:
1333 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1334 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1335 Locks::heap_bitmap_lock_)
1336 : heap_(heap),
1337 failed_(failed) {
1338 }
1339
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001340 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1341 // annotalysis on visitors.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001342 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1343 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001344 // Filter out class references since changing an object's class does not mark the card as dirty.
1345 // Also handles large objects, since the only reference they hold is a class reference.
1346 if (ref != NULL && !ref->IsClass()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001347 CardTable* card_table = heap_->GetCardTable();
1348 // If the object is not dirty and it is referencing something in the live stack other than
1349 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001350 if (!card_table->AddrIsInCardTable(obj)) {
1351 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1352 *failed_ = true;
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001353 } else if (card_table->GetCard(obj) < CardTable::kCardDirty - 1) {
1354 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1355 // kCardDirty - 1 if it didnt get touched since we aged it.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001356 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001357 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001358 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1359 LOG(ERROR) << "Object " << obj << " found in live stack";
1360 }
1361 if (heap_->GetLiveBitmap()->Test(obj)) {
1362 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1363 }
1364 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1365 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1366
1367 // Print which field of the object is dead.
1368 if (!obj->IsObjectArray()) {
1369 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1370 CHECK(klass != NULL);
1371 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1372 CHECK(fields != NULL);
1373 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1374 const Field* cur = fields->Get(i);
1375 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1376 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1377 << PrettyField(cur);
1378 break;
1379 }
1380 }
1381 } else {
1382 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1383 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1384 if (object_array->Get(i) == ref) {
1385 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1386 }
1387 }
1388 }
1389
1390 *failed_ = true;
1391 }
1392 }
1393 }
1394 }
1395
1396 private:
1397 Heap* heap_;
1398 bool* failed_;
1399};
1400
1401class VerifyLiveStackReferences {
1402 public:
1403 VerifyLiveStackReferences(Heap* heap)
1404 : heap_(heap),
1405 failed_(false) {
1406
1407 }
1408
1409 void operator ()(const Object* obj) const
1410 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1411 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1412 MarkSweep::VisitObjectReferences(obj, visitor);
1413 }
1414
1415 bool Failed() const {
1416 return failed_;
1417 }
1418
1419 private:
1420 Heap* heap_;
1421 bool failed_;
1422};
1423
1424bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001425 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001426
1427 VerifyLiveStackReferences visitor(this);
1428 GetLiveBitmap()->Visit(visitor);
1429
1430 // We can verify objects in the live stack since none of these should reference dead objects.
1431 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1432 visitor(*it);
1433 }
1434
1435 if (visitor.Failed()) {
1436 DumpSpaces();
1437 return false;
1438 }
1439 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001440}
1441
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001442void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001443 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001444 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1445 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001446 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1447 ContinuousSpace* space = *it;
1448 // We never allocate into zygote spaces.
1449 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1450 (gc_type == kGcTypeFull &&
1451 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001452 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1453 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1454 if (live_bitmap != mark_bitmap) {
1455 live_bitmap_->ReplaceBitmap(live_bitmap, mark_bitmap);
1456 mark_bitmap_->ReplaceBitmap(mark_bitmap, live_bitmap);
1457 space->AsAllocSpace()->SwapBitmaps();
1458 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001459 }
1460 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001461 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001462}
1463
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001464void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001465 large_object_space_->SwapBitmaps();
1466 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1467 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001468}
1469
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001470void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001471 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001472
1473 // Sort the live stack so that we can quickly binary search it later.
1474 if (VERIFY_OBJECT_ENABLED) {
1475 std::sort(live_stack_->Begin(), live_stack_->End());
1476 }
1477}
1478
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001479void Heap::ProcessCards(TimingLogger& timings) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001480 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1481 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1482 ContinuousSpace* space = *it;
1483 if (space->IsImageSpace()) {
1484 mod_union_table_->ClearCards(*it);
1485 timings.AddSplit("ModUnionClearCards");
1486 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1487 zygote_mod_union_table_->ClearCards(space);
1488 timings.AddSplit("ZygoteModUnionClearCards");
1489 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001490 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1491 // were dirty before the GC started.
1492 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
1493 timings.AddSplit("AllocSpaceClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001494 }
1495 }
1496}
1497
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001498// Bind the live bits to the mark bits of bitmaps based on the gc type.
1499void Heap::BindBitmaps(GcType gc_type, MarkSweep& mark_sweep) {
1500 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1501 if (gc_type == kGcTypePartial) {
1502 // For partial GCs we need to bind the bitmap of the zygote space so that all objects in the
1503 // zygote space are viewed as marked.
1504 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1505 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1506 mark_sweep.BindLiveToMarkBitmap(*it);
1507 }
1508 }
1509 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1510 reinterpret_cast<Object*>(alloc_space_->Begin()));
1511 } else if (gc_type == kGcTypeSticky) {
1512 // For sticky GC, we want to bind the bitmaps of both the zygote space and the alloc space.
1513 // This lets us start with the mark bitmap of the previous garbage collection as the current
1514 // mark bitmap of the alloc space. After the sticky GC finishes, we then unbind the bitmaps,
1515 // making it so that the live bitmap of the alloc space is contains the newly marked objects
1516 // from the sticky GC.
1517 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1518 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1519 mark_sweep.BindLiveToMarkBitmap(*it);
1520 }
1521 }
1522
1523 large_object_space_->CopyLiveToMarked();
1524 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1525 reinterpret_cast<Object*>(alloc_space_->Begin()));
1526 }
1527 mark_sweep.FindDefaultMarkBitmap();
1528}
1529
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001530void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1531 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001532 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001533 uint64_t gc_begin = NanoTime(), dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001534 std::stringstream gc_type_str;
1535 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001536
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001537 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001538 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001539 Object* cleared_references = NULL;
1540 {
1541 MarkSweep mark_sweep(mark_stack_.get());
1542 timings.AddSplit("ctor");
1543
1544 mark_sweep.Init();
1545 timings.AddSplit("Init");
1546
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001547 BindBitmaps(gc_type, mark_sweep);
1548 timings.AddSplit("BindBitmaps");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001549
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001550 if (verify_pre_gc_heap_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001551 thread_list->SuspendAll();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001552 {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001553 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1554 if (!VerifyHeapReferences()) {
1555 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1556 }
1557 timings.AddSplit("VerifyHeapReferencesPreGC");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001558 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001559 thread_list->ResumeAll();
1560 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001561
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001562 // Process dirty cards and add dirty cards to mod union tables.
1563 ProcessCards(timings);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001564
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001565 // Need to do this before the checkpoint since we don't want any threads to add references to
1566 // the live stack during the recursive mark.
1567 SwapStacks();
1568 timings.AddSplit("SwapStacks");
1569
1570 // Tell the running threads to suspend and mark their roots.
1571 mark_sweep.MarkRootsCheckpoint();
1572 timings.AddSplit("MarkRootsCheckpoint");
1573
1574 // Check that all objects which reference things in the live stack are on dirty cards.
1575 if (verify_missing_card_marks_) {
1576 thread_list->SuspendAll();
1577 {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001578 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1579 // Sort the live stack so that we can quickly binary search it later.
1580 std::sort(live_stack_->Begin(), live_stack_->End());
1581 if (!VerifyMissingCardMarks()) {
1582 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1583 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001584 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001585 thread_list->ResumeAll();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001586 }
1587
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001588 if (verify_mod_union_table_) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001589 thread_list->SuspendAll();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001590 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1591 zygote_mod_union_table_->Update();
1592 zygote_mod_union_table_->Verify();
1593 mod_union_table_->Update();
1594 mod_union_table_->Verify();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001595 thread_list->ResumeAll();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001596 }
1597
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001598 {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001599 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
Ian Rogers81d425b2012-09-27 16:03:43 -07001600 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001601
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001602 // Mark the roots which we can do concurrently.
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001603 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -07001604 mark_sweep.MarkConcurrentRoots();
1605 timings.AddSplit("MarkConcurrentRoots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001606 mark_sweep.MarkNonThreadRoots();
1607 timings.AddSplit("MarkNonThreadRoots");
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001608
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001609 if (gc_type != kGcTypeSticky) {
1610 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1611 // knowing that new allocations won't be marked as live.
1612 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1613 live_stack_.get());
1614 timings.AddSplit("MarkStackAsLive");
1615 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001616
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001617 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
1618
Mathieu Chartier0325e622012-09-05 14:22:51 -07001619 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001620 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001621 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001622 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001623 mark_sweep.RecursiveMarkDirtyObjects(CardTable::kCardDirty - 1);
1624 timings.AddSplit("RecursiveMarkCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001625 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001626 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001627 }
1628 // Release share on mutator_lock_ and then get exclusive access.
1629 dirty_begin = NanoTime();
1630 thread_list->SuspendAll();
1631 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001632 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001633
1634 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001635 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001636
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001637 // Re-mark root set.
1638 mark_sweep.ReMarkRoots();
1639 timings.AddSplit("ReMarkRoots");
1640
1641 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001642 mark_sweep.RecursiveMarkDirtyObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001643 timings.AddSplit("RecursiveMarkDirtyObjects");
1644 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001645
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001646 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001647 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001648
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001649 mark_sweep.ProcessReferences(clear_soft_references);
1650 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001651 }
1652
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001653 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1654 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001655 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001656 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001657 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001658 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001659 // We only sweep over the live stack, and the live stack should not intersect with the
1660 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001661 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1662 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001663 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001664 if (kIsDebugBuild) {
1665 if (gc_type == kGcTypeSticky) {
1666 // Make sure everything in the live stack isn't something we unmarked.
1667 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1668 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1669 DCHECK(!std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it))
1670 << "Unmarked object " << *it << " in the live stack";
1671 }
1672 } else {
1673 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
1674 DCHECK(!GetLiveBitmap()->Test(*it)) << "Object " << *it << " is marked as live";
1675 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001676 }
1677 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001678 }
1679
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001680 if (kIsDebugBuild) {
1681 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001682 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001683 mark_sweep.VerifyImageRoots();
1684 timings.AddSplit("VerifyImageRoots");
1685 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001686
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001687 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001688 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001689 // Swapping bound bitmaps does nothing.
1690 SwapBitmaps(kGcTypeFull);
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001691 if (!VerifyHeapReferences()) {
1692 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001693 }
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001694 SwapBitmaps(kGcTypeFull);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001695 timings.AddSplit("VerifyHeapReferencesPostGC");
1696 }
1697
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001698 thread_list->ResumeAll();
1699 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001700 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001701
1702 {
1703 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001704 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001705 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001706 mark_sweep.Sweep(timings, gc_type == kGcTypePartial, false);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001707 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001708 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001709 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001710 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001711 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001712 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001713 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001714 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001715 }
1716
1717 {
1718 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1719 // Unbind the live and mark bitmaps.
1720 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001721
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001722 // Swap the live and mark bitmaps for each space which we modified space. This is an
1723 // optimization that enables us to not clear live bits inside of the sweep.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001724 if (gc_type == kGcTypeSticky) {
1725 SwapLargeObjects();
1726 } else {
1727 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001728 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001729 timings.AddSplit("SwapBitmaps");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001730 }
1731
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001732 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001733 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001734 mark_sweep.VerifySystemWeaks();
1735 timings.AddSplit("VerifySystemWeaks");
1736 }
1737
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001738 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001739 bytes_freed = mark_sweep.GetFreedBytes();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001740 total_bytes_freed_ += bytes_freed;
1741 total_objects_freed_ += mark_sweep.GetFreedObjects();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001742 }
1743
1744 GrowForUtilization();
1745 timings.AddSplit("GrowForUtilization");
1746
1747 EnqueueClearedReferences(&cleared_references);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001748 timings.AddSplit("EnqueueClearedReferences");
1749
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001750 RequestHeapTrim();
1751 timings.AddSplit("Finish");
1752
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001753 // If the GC was slow, then print timings in the log.
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001754 uint64_t pause_time = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001755 uint64_t duration = (NanoTime() - gc_begin) / 1000 * 1000;
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001756 total_paused_time_ += pause_time;
1757 if (pause_time > MsToNs(5) || (gc_cause == kGcCauseForAlloc && duration > MsToNs(20))) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001758 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001759 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001760 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001761 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001762 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001763 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001764 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_time)
1765 << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001766 if (VLOG_IS_ON(heap)) {
1767 timings.Dump();
1768 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001769 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001770
Mathieu Chartier0325e622012-09-05 14:22:51 -07001771 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1772 logger->Start();
1773 logger->AddLogger(timings);
1774 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001775}
1776
Ian Rogers81d425b2012-09-27 16:03:43 -07001777GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001778 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001779 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001780 bool do_wait;
1781 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001782 {
1783 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001784 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001785 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001786 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001787 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001788 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001789 // We must wait, change thread state then sleep on gc_complete_cond_;
1790 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1791 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001792 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001793 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001794 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001795 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001796 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001797 wait_time = NanoTime() - wait_start;;
1798 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001799 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001800 if (wait_time > MsToNs(5)) {
1801 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1802 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001803 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001804 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001805 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001806}
1807
Elliott Hughesc967f782012-04-16 10:23:15 -07001808void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001809 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1810 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001811 DumpGcPerformanceInfo();
Elliott Hughesc967f782012-04-16 10:23:15 -07001812}
1813
1814size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001815 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001816}
1817
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001818void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001819 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001820 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001821 << PrettySize(GetMaxMemory());
1822 max_allowed_footprint = GetMaxMemory();
1823 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001824 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001825}
1826
Carl Shapiro69759ea2011-07-21 18:13:35 -07001827void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001828 // We know what our utilization is at this moment.
1829 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001830 size_t target_size = num_bytes_allocated_ / GetTargetHeapUtilization();
Mathieu Chartier0051be62012-10-12 17:47:11 -07001831 if (target_size > num_bytes_allocated_ + max_free_) {
1832 target_size = num_bytes_allocated_ + max_free_;
1833 } else if (target_size < num_bytes_allocated_ + min_free_) {
1834 target_size = num_bytes_allocated_ + min_free_;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001835 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001836
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001837 // Calculate when to perform the next ConcurrentGC.
1838 if (GetFreeMemory() < concurrent_min_free_) {
1839 // Not enough free memory to perform concurrent GC.
1840 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1841 } else {
1842 // Start a concurrent Gc when we get close to the target size.
1843 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001844 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001845
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001846 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001847}
1848
jeffhaoc1160702011-10-27 15:48:45 -07001849void Heap::ClearGrowthLimit() {
jeffhaoc1160702011-10-27 15:48:45 -07001850 alloc_space_->ClearGrowthLimit();
1851}
1852
Elliott Hughesadb460d2011-10-05 17:02:34 -07001853void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001854 MemberOffset reference_queue_offset,
1855 MemberOffset reference_queueNext_offset,
1856 MemberOffset reference_pendingNext_offset,
1857 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001858 reference_referent_offset_ = reference_referent_offset;
1859 reference_queue_offset_ = reference_queue_offset;
1860 reference_queueNext_offset_ = reference_queueNext_offset;
1861 reference_pendingNext_offset_ = reference_pendingNext_offset;
1862 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1863 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1864 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1865 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1866 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1867 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1868}
1869
1870Object* Heap::GetReferenceReferent(Object* reference) {
1871 DCHECK(reference != NULL);
1872 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1873 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1874}
1875
1876void Heap::ClearReferenceReferent(Object* reference) {
1877 DCHECK(reference != NULL);
1878 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1879 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1880}
1881
1882// Returns true if the reference object has not yet been enqueued.
1883bool Heap::IsEnqueuable(const Object* ref) {
1884 DCHECK(ref != NULL);
1885 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1886 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1887 return (queue != NULL) && (queue_next == NULL);
1888}
1889
1890void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1891 DCHECK(ref != NULL);
1892 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1893 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1894 EnqueuePendingReference(ref, cleared_reference_list);
1895}
1896
1897void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1898 DCHECK(ref != NULL);
1899 DCHECK(list != NULL);
1900
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001901 // TODO: Remove this lock, use atomic stacks for storing references.
1902 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001903 if (*list == NULL) {
1904 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1905 *list = ref;
1906 } else {
1907 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1908 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1909 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1910 }
1911}
1912
1913Object* Heap::DequeuePendingReference(Object** list) {
1914 DCHECK(list != NULL);
1915 DCHECK(*list != NULL);
1916 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1917 Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001918
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001919 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1920 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001921 if (*list == head) {
1922 ref = *list;
1923 *list = NULL;
1924 } else {
1925 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1926 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1927 ref = head;
1928 }
1929 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1930 return ref;
1931}
1932
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001933void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001934 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001935 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001936 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001937 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1938 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001939}
1940
1941size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001942 return num_bytes_allocated_;
1943}
1944
1945size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001946 size_t total = 0;
1947 // TODO: C++0x
1948 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1949 Space* space = *it;
1950 if (space->IsAllocSpace()) {
1951 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1952 }
1953 }
1954 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001955}
1956
1957size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001958 return concurrent_start_size_;
1959}
1960
1961size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001962 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001963}
1964
1965void Heap::EnqueueClearedReferences(Object** cleared) {
1966 DCHECK(cleared != NULL);
1967 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001968 // When a runtime isn't started there are no reference queues to care about so ignore.
1969 if (LIKELY(Runtime::Current()->IsStarted())) {
1970 ScopedObjectAccess soa(Thread::Current());
1971 JValue args[1];
1972 args[0].SetL(*cleared);
1973 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1974 args, NULL);
1975 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001976 *cleared = NULL;
1977 }
1978}
1979
Ian Rogers1f539342012-10-03 21:09:42 -07001980void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001981 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001982 Runtime* runtime = Runtime::Current();
1983 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1984 !runtime->IsConcurrentGcEnabled()) {
1985 return;
1986 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001987 {
1988 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1989 if (runtime->IsShuttingDown()) {
1990 return;
1991 }
1992 }
1993 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001994 return;
1995 }
1996
1997 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001998 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001999 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2000 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002001 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2002 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002003 CHECK(!env->ExceptionCheck());
2004 requesting_gc_ = false;
2005}
2006
Ian Rogers81d425b2012-09-27 16:03:43 -07002007void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002008 {
2009 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2010 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
2011 return;
2012 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07002013 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002014
Ian Rogers81d425b2012-09-27 16:03:43 -07002015 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002016 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07002017 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002018 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002019 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002020 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002021 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002022 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002023 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002024}
2025
Mathieu Chartier3056d0c2012-10-19 10:49:56 -07002026void Heap::Trim() {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002027 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002028}
2029
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002030void Heap::RequestHeapTrim() {
2031 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2032 // because that only marks object heads, so a large array looks like lots of empty space. We
2033 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2034 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2035 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2036 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002037 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002038 float utilization =
2039 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
2040 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
2041 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
2042 // heap trim occurred in the last two seconds.
2043 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002044 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002045
2046 Thread* self = Thread::Current();
2047 {
2048 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2049 Runtime* runtime = Runtime::Current();
2050 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2051 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2052 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2053 // as we don't hold the lock while requesting the trim).
2054 return;
2055 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002056 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002057 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07002058 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07002059 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2060 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002061 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2062 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002063 CHECK(!env->ExceptionCheck());
2064}
2065
Carl Shapiro69759ea2011-07-21 18:13:35 -07002066} // namespace art