blob: 6dcdab9b60ba669b63282cd018f64c600fff22c5 [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
Mathieu Chartier752a0e62013-06-27 11:03:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
Brian Carlstrom5643b782012-02-05 12:32:53 -080021
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070024#include <valgrind.h>
Carl Shapiro58551df2011-07-24 03:09:51 -070025
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070027#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080028#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070029#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070030#include "gc/accounting/atomic_stack.h"
31#include "gc/accounting/card_table-inl.h"
32#include "gc/accounting/heap_bitmap-inl.h"
33#include "gc/accounting/mod_union_table-inl.h"
34#include "gc/accounting/space_bitmap-inl.h"
35#include "gc/collector/mark_sweep-inl.h"
36#include "gc/collector/partial_mark_sweep.h"
37#include "gc/collector/sticky_mark_sweep.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070038#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/image_space.h"
40#include "gc/space/large_object_space.h"
41#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070042#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080043#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/class-inl.h"
45#include "mirror/field-inl.h"
46#include "mirror/object.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080049#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080050#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070051#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070052#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070053#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070054#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070055#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070056#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070057
58namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070059namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070060
Ian Rogers1d54e732013-05-02 21:10:01 -070061// When to create a log message about a slow GC, 100ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080062static const uint64_t kSlowGcThreshold = MsToNs(100);
Mathieu Chartier82353312013-07-18 10:47:51 -070063// When to create a log message about a long pause, 5ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080064static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier0418ae22013-07-31 13:35:46 -070065static const bool kGCALotMode = false;
66static const size_t kGcAlotInterval = KB;
Mathieu Chartier65db8802012-11-20 12:36:46 -080067static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070068// Minimum amount of remaining bytes before a concurrent GC is triggered.
69static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070070const double Heap::kDefaultTargetUtilization = 0.5;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070071// If true, measure the total allocation time.
72static const bool kMeasureAllocationTime = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070073
Mathieu Chartier0051be62012-10-12 17:47:11 -070074Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070075 double target_utilization, size_t capacity, const std::string& original_image_file_name,
76 bool concurrent_gc, size_t num_gc_threads, bool low_memory_mode)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070077 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080078 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070079 concurrent_gc_(concurrent_gc),
Mathieu Chartier63a54342013-07-23 13:17:59 -070080 num_gc_threads_(num_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070081 low_memory_mode_(low_memory_mode),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070082 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070083 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080084 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070085 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070086 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080087 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070088 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070089 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070090 native_footprint_gc_watermark_(initial_size),
91 native_footprint_limit_(2 * initial_size),
Mathieu Chartierc39e3422013-08-07 16:41:36 -070092 activity_thread_class_(NULL),
93 application_thread_class_(NULL),
94 activity_thread_(NULL),
95 application_thread_(NULL),
96 last_process_state_id_(NULL),
97 // Initially care about pauses in case we never get notified of process states, or if the JNI
98 // code becomes broken.
99 care_about_pause_times_(true),
Ian Rogers1d54e732013-05-02 21:10:01 -0700100 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
101 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700102 total_bytes_freed_ever_(0),
103 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700104 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800105 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700106 native_bytes_allocated_(0),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700107 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700108 verify_missing_card_marks_(false),
109 verify_system_weaks_(false),
110 verify_pre_gc_heap_(false),
111 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700112 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700113 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700114 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700115 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800116 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700117 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
118 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
119 * verification is enabled, we limit the size of allocation stacks to speed up their
120 * searching.
121 */
122 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
123 : (kDesiredHeapVerification > kNoHeapVerification) ? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800124 reference_referent_offset_(0),
125 reference_queue_offset_(0),
126 reference_queueNext_offset_(0),
127 reference_pendingNext_offset_(0),
128 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700129 min_free_(min_free),
130 max_free_(max_free),
131 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700132 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700133 total_allocation_time_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700134 verify_object_mode_(kHeapVerificationNotPermitted),
135 running_on_valgrind_(RUNNING_ON_VALGRIND) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800136 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800137 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700138 }
139
Ian Rogers1d54e732013-05-02 21:10:01 -0700140 live_bitmap_.reset(new accounting::HeapBitmap(this));
141 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700142
Ian Rogers30fab402012-01-23 15:43:46 -0800143 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700144 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800145 std::string image_file_name(original_image_file_name);
146 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700147 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
148 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700149 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800150 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
151 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800152 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
153 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700154 if (oat_file_end_addr > requested_alloc_space_begin) {
155 requested_alloc_space_begin =
156 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
157 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700158 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700159 }
160
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700161 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700162 initial_size,
163 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700164 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700165 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700166 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700167 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700168
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700169 // Allocate the large object space.
170 const bool kUseFreeListSpaceForLOS = false;
171 if (kUseFreeListSpaceForLOS) {
172 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
173 } else {
174 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
175 }
176 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
177 AddDiscontinuousSpace(large_object_space_);
178
Ian Rogers1d54e732013-05-02 21:10:01 -0700179 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
180 byte* heap_begin = continuous_spaces_.front()->Begin();
181 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
182 if (continuous_spaces_.back()->IsDlMallocSpace()) {
183 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700184 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700185
Ian Rogers30fab402012-01-23 15:43:46 -0800186 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700187 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700188 typedef std::vector<space::ContinuousSpace*>::iterator It;
189 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
190 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800191 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700192 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700193 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800194 }
195 }
196
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800197 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700198 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700199 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700200
Mathieu Chartier161a8e02013-08-01 19:12:52 -0700201 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
Ian Rogers1d54e732013-05-02 21:10:01 -0700202 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700203
Ian Rogers1d54e732013-05-02 21:10:01 -0700204 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700205 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700206
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700207 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700208 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700209
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800210 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700211 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700212 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
213 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
214 max_allocation_stack_size_));
215 live_stack_.reset(accounting::ObjectStack::Create("live stack",
216 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700217
Mathieu Chartier65db8802012-11-20 12:36:46 -0800218 // It's still too early to take a lock because there are no threads yet, but we can create locks
219 // now. We don't create it earlier to make it clear that you can't use locks during heap
220 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700221 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700222 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
223 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700224
Mathieu Chartier63a54342013-07-23 13:17:59 -0700225 // Create the reference queue lock, this is required so for parallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700226 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700227
Ian Rogers1d54e732013-05-02 21:10:01 -0700228 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800229 last_gc_size_ = GetBytesAllocated();
230
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800231 // Create our garbage collectors.
232 for (size_t i = 0; i < 2; ++i) {
233 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700234 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
235 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
236 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700237 }
238
Brian Carlstrom42748892013-07-18 18:04:08 -0700239 CHECK_NE(max_allowed_footprint_, 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800240 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800241 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700242 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700243}
244
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700245void Heap::CreateThreadPool() {
Mathieu Chartier63a54342013-07-23 13:17:59 -0700246 thread_pool_.reset(new ThreadPool(num_gc_threads_));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700247}
248
249void Heap::DeleteThreadPool() {
250 thread_pool_.reset(NULL);
251}
252
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700253// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700254struct ContinuousSpaceSorter {
Brian Carlstromdf629502013-07-17 22:39:56 -0700255 bool operator()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700256 return a->Begin() < b->Begin();
257 }
258};
259
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700260static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
261 CHECK(out_value != NULL);
262 jfieldID field = env->GetStaticFieldID(clz, name, "I");
263 if (field == NULL) {
264 env->ExceptionClear();
265 return false;
266 }
267 *out_value = env->GetStaticIntField(clz, field);
268 return true;
269}
270
271void Heap::ListenForProcessStateChange() {
272 VLOG(gc) << "Heap notified of process state change";
273
274 Thread* self = Thread::Current();
275 JNIEnvExt* env = self->GetJniEnv();
276
277 if (!have_zygote_space_) {
278 return;
279 }
280
281 if (activity_thread_class_ == NULL) {
282 jclass clz = env->FindClass("android/app/ActivityThread");
283 if (clz == NULL) {
284 env->ExceptionClear();
285 LOG(WARNING) << "Could not find activity thread class in process state change";
286 return;
287 }
288 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
289 }
290
291 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
292 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
293 "currentActivityThread",
294 "()Landroid/app/ActivityThread;");
295 if (current_activity_method == NULL) {
296 env->ExceptionClear();
297 LOG(WARNING) << "Could not get method for currentActivityThread";
298 return;
299 }
300
301 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
302 if (obj == NULL) {
303 env->ExceptionClear();
304 LOG(WARNING) << "Could not get current activity";
305 return;
306 }
307 activity_thread_ = env->NewGlobalRef(obj);
308 }
309
310 if (process_state_cares_about_pause_time_.empty()) {
311 // Just attempt to do this the first time.
312 jclass clz = env->FindClass("android/app/ActivityManager");
313 if (clz == NULL) {
314 LOG(WARNING) << "Activity manager class is null";
315 return;
316 }
317 ScopedLocalRef<jclass> activity_manager(env, clz);
318 std::vector<const char*> care_about_pauses;
319 care_about_pauses.push_back("PROCESS_STATE_TOP");
320 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
321 // Attempt to read the constants and classify them as whether or not we care about pause times.
322 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
323 int process_state = 0;
324 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
325 process_state_cares_about_pause_time_.insert(process_state);
326 VLOG(gc) << "Adding process state " << process_state
327 << " to set of states which care about pause time";
328 }
329 }
330 }
331
332 if (application_thread_class_ == NULL) {
333 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
334 if (clz == NULL) {
335 env->ExceptionClear();
336 LOG(WARNING) << "Could not get application thread class";
337 return;
338 }
339 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
340 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
341 if (last_process_state_id_ == NULL) {
342 env->ExceptionClear();
343 LOG(WARNING) << "Could not get last process state member";
344 return;
345 }
346 }
347
348 if (application_thread_class_ != NULL && application_thread_ == NULL) {
349 jmethodID get_application_thread =
350 env->GetMethodID(activity_thread_class_, "getApplicationThread",
351 "()Landroid/app/ActivityThread$ApplicationThread;");
352 if (get_application_thread == NULL) {
353 LOG(WARNING) << "Could not get method ID for get application thread";
354 return;
355 }
356
357 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
358 if (obj == NULL) {
359 LOG(WARNING) << "Could not get application thread";
360 return;
361 }
362
363 application_thread_ = env->NewGlobalRef(obj);
364 }
365
366 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
367 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
368 env->ExceptionClear();
369
370 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
371 process_state_cares_about_pause_time_.end();
372
373 VLOG(gc) << "New process state " << process_state
374 << " care about pauses " << care_about_pause_times_;
375 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700376}
377
Ian Rogers1d54e732013-05-02 21:10:01 -0700378void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700379 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700380 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700381 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700382 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700383 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700384 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
385 continuous_spaces_.push_back(space);
386 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
387 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700388 }
389
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700390 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700391 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700392
393 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
394 // avoid redundant marking.
395 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700396 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
397 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
398 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700399 if (space->IsImageSpace()) {
400 DCHECK(!seen_zygote);
401 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700402 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700403 DCHECK(!seen_alloc);
404 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700405 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700406 seen_alloc = true;
407 }
408 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800409}
410
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700411void Heap::RegisterGCAllocation(size_t bytes) {
412 if (this != NULL) {
413 gc_memory_overhead_.fetch_add(bytes);
414 }
415}
416
417void Heap::RegisterGCDeAllocation(size_t bytes) {
418 if (this != NULL) {
419 gc_memory_overhead_.fetch_sub(bytes);
420 }
421}
422
Ian Rogers1d54e732013-05-02 21:10:01 -0700423void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
424 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
425 DCHECK(space != NULL);
426 DCHECK(space->GetLiveObjects() != NULL);
427 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
428 DCHECK(space->GetMarkObjects() != NULL);
429 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
430 discontinuous_spaces_.push_back(space);
431}
432
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700433void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700434 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700435 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700436 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800437
438 // Dump cumulative loggers for each GC type.
439 // TODO: C++0x
440 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700441 typedef std::vector<collector::MarkSweep*>::const_iterator It;
442 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800443 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700444 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800445 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800446 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700447 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800448 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700449 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800450 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
451 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
452 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700453 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
454 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
455 << collector->GetName() << " freed: " << freed_objects
456 << " objects with total size " << PrettySize(freed_bytes) << "\n"
457 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
458 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800459 total_duration += total_ns;
460 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700461 }
462 }
463 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700464 size_t total_objects_allocated = GetObjectsAllocatedEver();
465 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700466 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700467 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700468 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
469 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700470 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700471 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700472 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700473 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700474 os << "Total number of allocations: " << total_objects_allocated << "\n";
475 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700476 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700477 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
478 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
479 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700480 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700481 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
482 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700483 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700484}
485
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800486Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700487 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700488 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700489 }
490
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800491 STLDeleteElements(&mark_sweep_collectors_);
492
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700493 // If we don't reset then the mark stack complains in it's destructor.
494 allocation_stack_->Reset();
495 live_stack_->Reset();
496
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800497 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800498 // We can't take the heap lock here because there might be a daemon thread suspended with the
499 // heap lock held. We know though that no non-daemon threads are executing, and we know that
500 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
501 // those threads can't resume. We're the only running thread, and we can do whatever we like...
Ian Rogers1d54e732013-05-02 21:10:01 -0700502 STLDeleteElements(&continuous_spaces_);
503 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700504 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700505 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700506}
507
Ian Rogers1d54e732013-05-02 21:10:01 -0700508space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
509 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700510 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700511 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
512 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700513 if ((*it)->Contains(obj)) {
514 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700515 }
516 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700517 if (!fail_ok) {
518 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
519 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700520 return NULL;
521}
522
Ian Rogers1d54e732013-05-02 21:10:01 -0700523space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
524 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700525 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700526 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
527 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
528 if ((*it)->Contains(obj)) {
529 return *it;
530 }
531 }
532 if (!fail_ok) {
533 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
534 }
535 return NULL;
536}
537
538space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
539 space::Space* result = FindContinuousSpaceFromObject(obj, true);
540 if (result != NULL) {
541 return result;
542 }
543 return FindDiscontinuousSpaceFromObject(obj, true);
544}
545
546space::ImageSpace* Heap::GetImageSpace() const {
547 // TODO: C++0x auto
548 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
549 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700550 if ((*it)->IsImageSpace()) {
551 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700552 }
553 }
554 return NULL;
555}
556
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700557static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700558 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700559 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700560 size_t chunk_free_bytes = chunk_size - used_bytes;
561 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
562 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700563 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700564}
565
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800566mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
567 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700568 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
569 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800570 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700571
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800572 mirror::Object* obj = NULL;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700573 size_t bytes_allocated = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700574 uint64_t allocation_start = 0;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700575 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700576 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700577 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700578
579 // We need to have a zygote space or else our newly allocated large object can end up in the
580 // Zygote resulting in it being prematurely freed.
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700581 // We can only do this for primitive objects since large objects will not be within the card table
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700582 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers333cf1b2013-07-24 11:57:02 -0700583 bool large_object_allocation =
584 byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
585 if (UNLIKELY(large_object_allocation)) {
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700586 obj = Allocate(self, large_object_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700587 // Make sure that our large object didn't get placed anywhere within the space interval or else
588 // it breaks the immune range.
589 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700590 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
591 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700592 } else {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700593 obj = Allocate(self, alloc_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700594 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700595 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700596 }
597
Mathieu Chartier037813d2012-08-23 16:44:59 -0700598 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700599 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700600
601 // Record allocation after since we want to use the atomic add for the atomic fence to guard
602 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700603 RecordAllocation(bytes_allocated, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700604
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700605 if (Dbg::IsAllocTrackingEnabled()) {
606 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700607 }
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700608 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700609 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800610 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700611 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700612 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700613 if (kDesiredHeapVerification > kNoHeapVerification) {
614 VerifyObject(obj);
615 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700616
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700617 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700618 total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700619 }
620
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700621 return obj;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700622 } else {
623 std::ostringstream oss;
624 int64_t total_bytes_free = GetFreeMemory();
625 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
626 << " free bytes";
627 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
628 if (!large_object_allocation && total_bytes_free >= byte_count) {
629 size_t max_contiguous_allocation = 0;
630 // TODO: C++0x auto
631 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
632 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
633 space::ContinuousSpace* space = *it;
634 if (space->IsDlMallocSpace()) {
635 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
636 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800637 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700638 oss << "; failed due to fragmentation (largest possible contiguous allocation "
639 << max_contiguous_allocation << " bytes)";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700640 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700641 self->ThrowOutOfMemoryError(oss.str().c_str());
642 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700643 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700644}
645
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800646bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700647 // Note: we deliberately don't take the lock here, and mustn't test anything that would
648 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700649 if (obj == NULL) {
650 return true;
651 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700652 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700653 return false;
654 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700655 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700656}
657
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800658bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700659 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700660 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700661 return false;
662 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700663 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
664 space::DiscontinuousSpace* d_space = NULL;
665 if (c_space != NULL) {
666 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700667 return true;
668 }
669 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700670 d_space = FindDiscontinuousSpaceFromObject(obj, true);
671 if (d_space != NULL) {
672 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700673 return true;
674 }
675 }
676 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700677 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Ian Rogers1d54e732013-05-02 21:10:01 -0700678 for (size_t i = 0; i < 5; ++i) {
679 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
680 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
681 return true;
682 }
683 NanoSleep(MsToNs(10));
684 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700685 // We need to check the bitmaps again since there is a race where we mark something as live and
686 // then clear the stack containing it.
687 if (c_space != NULL) {
688 if (c_space->GetLiveBitmap()->Test(obj)) {
689 return true;
690 }
691 } else {
692 d_space = FindDiscontinuousSpaceFromObject(obj, true);
693 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
694 return true;
695 }
696 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700697 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700698}
699
Ian Rogers04d7aa92013-03-16 14:29:17 -0700700void Heap::VerifyObjectImpl(const mirror::Object* obj) {
701 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700702 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700703 return;
704 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700705 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700706}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700707
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700708void Heap::DumpSpaces() {
709 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700710 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
711 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
712 space::ContinuousSpace* space = *it;
713 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
714 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700715 LOG(INFO) << space << " " << *space << "\n"
716 << live_bitmap << " " << *live_bitmap << "\n"
717 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700718 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700719 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
720 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
721 space::DiscontinuousSpace* space = *it;
722 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700723 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700724}
725
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800726void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800727 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700728 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700729 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800730 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
731 return;
732 }
733 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
734 mirror::Object::ClassOffset().Int32Value();
735 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
736 if (UNLIKELY(c == NULL)) {
737 LOG(FATAL) << "Null class in object: " << obj;
738 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
739 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
740 }
741 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
742 // Note: we don't use the accessors here as they have internal sanity checks
743 // that we don't want to run
744 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
745 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
746 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
747 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
748 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700749
Ian Rogers62d6c772013-02-27 08:32:07 -0800750 if (verify_object_mode_ != kVerifyAllFast) {
751 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
752 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700753 if (!IsLiveObjectLocked(obj)) {
754 DumpSpaces();
755 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700756 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700757 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700758 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
759 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700760 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700761}
762
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800763void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700764 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700765 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700766}
767
768void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700769 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700770 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700771}
772
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700773inline void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700774 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700775 DCHECK_GT(size, 0u);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700776 num_bytes_allocated_.fetch_add(size);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700777
778 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700779 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700780 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700781 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700782
783 // TODO: Update these atomically.
784 RuntimeStats* global_stats = Runtime::Current()->GetStats();
785 ++global_stats->allocated_objects;
786 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700787 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700788
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700789 // This is safe to do since the GC will never free objects which are neither in the allocation
790 // stack or the live bitmap.
791 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700792 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700793 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700794}
795
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700796void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700797 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700798 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700799
800 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700801 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700802 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700803 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700804
805 // TODO: Do this concurrently.
806 RuntimeStats* global_stats = Runtime::Current()->GetStats();
807 global_stats->freed_objects += freed_objects;
808 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700809 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700810}
811
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700812inline bool Heap::IsOutOfMemoryOnAllocation(size_t alloc_size) {
813 return num_bytes_allocated_ + alloc_size > growth_limit_;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700814}
815
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700816inline mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
817 bool grow, size_t* bytes_allocated) {
818 if (IsOutOfMemoryOnAllocation(alloc_size)) {
819 return NULL;
820 }
821 return space->Alloc(self, alloc_size, bytes_allocated);
822}
823
824// DlMallocSpace-specific version.
825inline mirror::Object* Heap::TryToAllocate(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
826 bool grow, size_t* bytes_allocated) {
827 if (IsOutOfMemoryOnAllocation(alloc_size)) {
828 return NULL;
829 }
830 if (!running_on_valgrind_) {
831 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
832 } else {
833 return space->Alloc(self, alloc_size, bytes_allocated);
834 }
835}
836
837template <class T>
838inline mirror::Object* Heap::Allocate(Thread* self, T* space, size_t alloc_size, size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700839 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
840 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700841 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700842 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700843
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700844 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700845 if (ptr != NULL) {
846 return ptr;
847 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700848 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
849}
850
851mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space, size_t alloc_size,
852 size_t* bytes_allocated) {
853 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700854
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700855 // The allocation failed. If the GC is running, block until it completes, and then retry the
856 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700857 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
858 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700859 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700860 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700861 if (ptr != NULL) {
862 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700863 }
864 }
865
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700866 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700867 for (size_t i = static_cast<size_t>(last_gc) + 1;
868 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700869 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700870 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700871 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700872 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700873 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700874 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
875 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700876 break;
877 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700878 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700879 run_gc = have_zygote_space_;
880 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700881 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700882 run_gc = true;
883 break;
884 default:
885 break;
886 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700887
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700888 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700889 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700890 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800891 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700892 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700893
894 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700895 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700896 if (ptr != NULL) {
897 return ptr;
898 }
899 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700900 }
901
902 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700903 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700904 ptr = TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700905 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700906 return ptr;
907 }
908
Elliott Hughes81ff3182012-03-23 20:35:56 -0700909 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
910 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
911 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700912
Elliott Hughes418dfe72011-10-06 18:56:27 -0700913 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700914 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
915 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700916
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700917 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700918 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700919 return TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700920}
921
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700922void Heap::SetTargetHeapUtilization(float target) {
923 DCHECK_GT(target, 0.0f); // asserted in Java code
924 DCHECK_LT(target, 1.0f);
925 target_utilization_ = target;
926}
927
Ian Rogers1d54e732013-05-02 21:10:01 -0700928size_t Heap::GetObjectsAllocated() const {
929 size_t total = 0;
930 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
931 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
932 space::ContinuousSpace* space = *it;
933 if (space->IsDlMallocSpace()) {
934 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700935 }
936 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700937 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
938 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
939 space::DiscontinuousSpace* space = *it;
940 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
941 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700942 return total;
943}
944
Ian Rogers1d54e732013-05-02 21:10:01 -0700945size_t Heap::GetObjectsAllocatedEver() const {
946 size_t total = 0;
947 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
948 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
949 space::ContinuousSpace* space = *it;
950 if (space->IsDlMallocSpace()) {
951 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700952 }
953 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700954 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
955 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
956 space::DiscontinuousSpace* space = *it;
957 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
958 }
959 return total;
960}
961
962size_t Heap::GetBytesAllocatedEver() const {
963 size_t total = 0;
964 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
965 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
966 space::ContinuousSpace* space = *it;
967 if (space->IsDlMallocSpace()) {
968 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
969 }
970 }
971 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
972 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
973 space::DiscontinuousSpace* space = *it;
974 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
975 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700976 return total;
977}
978
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700979class InstanceCounter {
980 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800981 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700982 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800983 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700984 }
985
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800986 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800987 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800988 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800989 if (use_is_assignable_from_) {
990 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
991 ++counts_[i];
992 }
993 } else {
994 if (instance_class == classes_[i]) {
995 ++counts_[i];
996 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700997 }
998 }
999 }
1000
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001001 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001002 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001003 bool use_is_assignable_from_;
1004 uint64_t* const counts_;
1005
1006 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001007};
1008
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001009void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001010 uint64_t* counts) {
1011 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1012 // is empty, so the live bitmap is the only place we need to look.
1013 Thread* self = Thread::Current();
1014 self->TransitionFromRunnableToSuspended(kNative);
1015 CollectGarbage(false);
1016 self->TransitionFromSuspendedToRunnable();
1017
1018 InstanceCounter counter(classes, use_is_assignable_from, counts);
1019 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001020 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001021}
1022
Elliott Hughes3b78c942013-01-15 17:35:41 -08001023class InstanceCollector {
1024 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001025 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001026 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1027 : class_(c), max_count_(max_count), instances_(instances) {
1028 }
1029
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001030 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1031 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001032 if (instance_class == class_) {
1033 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001034 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001035 }
1036 }
1037 }
1038
1039 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001040 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001041 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001042 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001043
1044 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1045};
1046
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001047void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1048 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001049 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1050 // is empty, so the live bitmap is the only place we need to look.
1051 Thread* self = Thread::Current();
1052 self->TransitionFromRunnableToSuspended(kNative);
1053 CollectGarbage(false);
1054 self->TransitionFromSuspendedToRunnable();
1055
1056 InstanceCollector collector(c, max_count, instances);
1057 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1058 GetLiveBitmap()->Visit(collector);
1059}
1060
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001061class ReferringObjectsFinder {
1062 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001063 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1064 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001065 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1066 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1067 }
1068
1069 // For bitmap Visit.
1070 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1071 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001072 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001073 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001074 }
1075
1076 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -07001077 void operator()(const mirror::Object* referrer, const mirror::Object* object,
1078 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001079 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001080 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001081 }
1082 }
1083
1084 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001085 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001086 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001087 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001088
1089 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1090};
1091
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001092void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1093 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001094 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1095 // is empty, so the live bitmap is the only place we need to look.
1096 Thread* self = Thread::Current();
1097 self->TransitionFromRunnableToSuspended(kNative);
1098 CollectGarbage(false);
1099 self->TransitionFromSuspendedToRunnable();
1100
1101 ReferringObjectsFinder finder(o, max_count, referring_objects);
1102 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1103 GetLiveBitmap()->Visit(finder);
1104}
1105
Ian Rogers30fab402012-01-23 15:43:46 -08001106void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001107 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1108 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001109 Thread* self = Thread::Current();
1110 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001111 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001112}
1113
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001114void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001115 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001116 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1117 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001118 Thread* self = Thread::Current();
1119 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001120
1121 // Try to see if we have any Zygote spaces.
1122 if (have_zygote_space_) {
1123 return;
1124 }
1125
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001126 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1127
1128 {
1129 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001130 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001131 FlushAllocStack();
1132 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001133
Ian Rogers1d54e732013-05-02 21:10:01 -07001134 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1135 // of the remaining available heap memory.
1136 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001137 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -07001138 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001139
Ian Rogers1d54e732013-05-02 21:10:01 -07001140 // Change the GC retention policy of the zygote space to only collect when full.
1141 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1142 AddContinuousSpace(alloc_space_);
1143 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001144
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001145 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001146 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001147 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1148 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1149 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001150 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001151 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001152}
1153
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001154void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001155 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1156 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001157 allocation_stack_->Reset();
1158}
1159
Ian Rogers1d54e732013-05-02 21:10:01 -07001160void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1161 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001162 mirror::Object** limit = stack->End();
1163 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1164 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001165 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001166 if (LIKELY(bitmap->HasAddress(obj))) {
1167 bitmap->Set(obj);
1168 } else {
1169 large_objects->Set(obj);
1170 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001171 }
1172}
1173
Ian Rogers1d54e732013-05-02 21:10:01 -07001174collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1175 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001176 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001177
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001178
Mathieu Chartier65db8802012-11-20 12:36:46 -08001179 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001180 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001181
Ian Rogers120f1c72012-09-28 17:17:10 -07001182 if (self->IsHandlingStackOverflow()) {
1183 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1184 }
1185
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001186 // Ensure there is only one GC at a time.
1187 bool start_collect = false;
1188 while (!start_collect) {
1189 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001190 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001191 if (!is_gc_running_) {
1192 is_gc_running_ = true;
1193 start_collect = true;
1194 }
1195 }
1196 if (!start_collect) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001197 // TODO: timinglog this.
Ian Rogers81d425b2012-09-27 16:03:43 -07001198 WaitForConcurrentGcToComplete(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001199
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001200 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1201 // Not doing at the moment to ensure soft references are cleared.
1202 }
1203 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001204 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001205
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001206 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1207 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1208 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1209 }
1210
Ian Rogers1d54e732013-05-02 21:10:01 -07001211 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001212 uint64_t gc_start_size = GetBytesAllocated();
1213 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001214 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001215 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1216 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001217 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001218 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001219 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001220 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1221 }
1222
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001223 if (gc_type == collector::kGcTypeSticky &&
1224 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1225 gc_type = collector::kGcTypePartial;
1226 }
1227
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001228 switch (gc_cause) {
1229 case kGcCauseForAlloc:
1230 ATRACE_BEGIN("GC (alloc)");
1231 break;
1232 case kGcCauseBackground:
1233 ATRACE_BEGIN("GC (background)");
1234 break;
1235 case kGcCauseExplicit:
1236 ATRACE_BEGIN("GC (explicit)");
1237 break;
1238 }
1239
Ian Rogers1d54e732013-05-02 21:10:01 -07001240 DCHECK_LT(gc_type, collector::kGcTypeMax);
1241 DCHECK_NE(gc_type, collector::kGcTypeNone);
1242 collector::MarkSweep* collector = NULL;
1243 typedef std::vector<collector::MarkSweep*>::iterator It;
1244 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1245 it != end; ++it) {
1246 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001247 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1248 collector = cur_collector;
1249 break;
1250 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001251 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001252 CHECK(collector != NULL)
1253 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1254 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001255
1256 base::TimingLogger& timings = collector->GetTimings();
1257
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001258 collector->clear_soft_references_ = clear_soft_references;
1259 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001260 total_objects_freed_ever_ += collector->GetFreedObjects();
1261 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001262
Ian Rogers1d54e732013-05-02 21:10:01 -07001263 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001264 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1265 bool was_slow = duration > kSlowGcThreshold ||
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001266 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001267 for (size_t i = 0; i < pauses.size(); ++i) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001268 if (pauses[i] > kLongGcPauseThreshold) {
1269 was_slow = true;
1270 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001271 }
1272
1273 if (was_slow) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001274 const size_t percent_free = GetPercentFree();
1275 const size_t current_heap_size = GetBytesAllocated();
1276 const size_t total_memory = GetTotalMemory();
1277 std::ostringstream pause_string;
1278 for (size_t i = 0; i < pauses.size(); ++i) {
1279 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1280 << ((i != pauses.size() - 1) ? ", " : "");
1281 }
1282 LOG(INFO) << gc_cause << " " << collector->GetName()
1283 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1284 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1285 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1286 << " total " << PrettyDuration((duration / 1000) * 1000);
1287 if (VLOG_IS_ON(heap)) {
1288 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
1289 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001290 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001291
Ian Rogers15bf2d32012-08-28 17:33:04 -07001292 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001293 MutexLock mu(self, *gc_complete_lock_);
1294 is_gc_running_ = false;
1295 last_gc_type_ = gc_type;
1296 // Wake anyone who may have been waiting for the GC to complete.
1297 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001298 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001299
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001300 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001301
1302 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001303 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001304 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001305}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001306
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001307void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
Ian Rogers1d54e732013-05-02 21:10:01 -07001308 collector::GcType gc_type) {
1309 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001310 // 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 -07001311 // cards.
1312 return;
1313 }
1314
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001315 base::TimingLogger::ScopedSplit split("UpdateModUnionTable", &timings);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001316 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001317 if (gc_type == collector::kGcTypePartial) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001318 base::TimingLogger::ScopedSplit split("UpdateZygoteModUnionTable", &timings);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001319 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001320
Ian Rogers1d54e732013-05-02 21:10:01 -07001321 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001322 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001323 }
1324
1325 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001326 timings.NewSplit("UpdateModUnionTable");
1327 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001328
1329 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001330 timings.NewSplit("MarkImageToAllocSpaceReferences");
1331 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001332}
1333
Ian Rogers1d54e732013-05-02 21:10:01 -07001334static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001335 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001336 if (root == obj) {
1337 LOG(INFO) << "Object " << obj << " is a root";
1338 }
1339}
1340
1341class ScanVisitor {
1342 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001343 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001344 LOG(INFO) << "Would have rescanned object " << obj;
1345 }
1346};
1347
Ian Rogers1d54e732013-05-02 21:10:01 -07001348// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001349class VerifyReferenceVisitor {
1350 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001351 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001352 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001353 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001354
1355 bool Failed() const {
1356 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001357 }
1358
1359 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001360 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001361 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1362 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001363 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001364 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001365 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1366 accounting::CardTable* card_table = heap_->GetCardTable();
1367 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1368 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001369
Ian Rogers1d54e732013-05-02 21:10:01 -07001370 if (obj != NULL) {
1371 byte* card_addr = card_table->CardFromAddr(obj);
1372 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1373 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1374 << "\nObj type " << PrettyTypeOf(obj)
1375 << "\nRef type " << PrettyTypeOf(ref);
1376 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1377 void* cover_begin = card_table->AddrFromCard(card_addr);
1378 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1379 accounting::CardTable::kCardSize);
1380 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1381 << "-" << cover_end;
1382 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001383
Ian Rogers1d54e732013-05-02 21:10:01 -07001384 // Print out how the object is live.
1385 if (bitmap != NULL && bitmap->Test(obj)) {
1386 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1387 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001388 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001389 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1390 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001391 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001392 LOG(ERROR) << "Object " << obj << " found in live stack";
1393 }
1394 // Attempt to see if the card table missed the reference.
1395 ScanVisitor scan_visitor;
1396 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1397 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001398 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001399
1400 // Search to see if any of the roots reference our object.
1401 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1402 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1403
1404 // Search to see if any of the roots reference our reference.
1405 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1406 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1407 } else {
1408 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001409 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001410 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001411 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001412 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001413 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001414 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001415 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001416 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1417 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1418 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001419 }
1420 }
1421
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001422 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001423 return heap_->IsLiveObjectLocked(obj);
1424 }
1425
1426 static void VerifyRoots(const mirror::Object* root, void* arg) {
1427 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1428 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001429 }
1430
1431 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001432 Heap* const heap_;
1433 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001434};
1435
Ian Rogers1d54e732013-05-02 21:10:01 -07001436// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001437class VerifyObjectVisitor {
1438 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001439 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001440
Brian Carlstromdf629502013-07-17 22:39:56 -07001441 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001442 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001443 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1444 // be live or else how did we find it in the live bitmap?
1445 VerifyReferenceVisitor visitor(heap_);
1446 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1447 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001448 }
1449
1450 bool Failed() const {
1451 return failed_;
1452 }
1453
1454 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001455 Heap* const heap_;
1456 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001457};
1458
1459// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001460bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001461 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001462 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001463 allocation_stack_->Sort();
1464 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001465 // Perform the verification.
1466 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001467 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001468 GetLiveBitmap()->Visit(visitor);
1469 // We don't want to verify the objects in the allocation stack since they themselves may be
1470 // pointing to dead objects if they are not reachable.
1471 if (visitor.Failed()) {
1472 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001473 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001474 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001475 return true;
1476}
1477
1478class VerifyReferenceCardVisitor {
1479 public:
1480 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1481 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1482 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001483 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001484 }
1485
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001486 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1487 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001488 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1489 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001490 // Filter out class references since changing an object's class does not mark the card as dirty.
1491 // Also handles large objects, since the only reference they hold is a class reference.
1492 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001493 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001494 // If the object is not dirty and it is referencing something in the live stack other than
1495 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001496 if (!card_table->AddrIsInCardTable(obj)) {
1497 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1498 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001499 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001500 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1501 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001502 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001503 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1504 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001505 LOG(ERROR) << "Object " << obj << " found in live stack";
1506 }
1507 if (heap_->GetLiveBitmap()->Test(obj)) {
1508 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1509 }
1510 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1511 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1512
1513 // Print which field of the object is dead.
1514 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001515 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001516 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001517 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1518 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001519 CHECK(fields != NULL);
1520 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001521 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001522 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1523 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1524 << PrettyField(cur);
1525 break;
1526 }
1527 }
1528 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001529 const mirror::ObjectArray<mirror::Object>* object_array =
1530 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001531 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1532 if (object_array->Get(i) == ref) {
1533 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1534 }
1535 }
1536 }
1537
1538 *failed_ = true;
1539 }
1540 }
1541 }
1542 }
1543
1544 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001545 Heap* const heap_;
1546 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001547};
1548
1549class VerifyLiveStackReferences {
1550 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001551 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001552 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001553 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001554
Brian Carlstromdf629502013-07-17 22:39:56 -07001555 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001556 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1557 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001558 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001559 }
1560
1561 bool Failed() const {
1562 return failed_;
1563 }
1564
1565 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001566 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001567 bool failed_;
1568};
1569
1570bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001571 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001572
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001573 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001574 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001575 VerifyLiveStackReferences visitor(this);
1576 GetLiveBitmap()->Visit(visitor);
1577
1578 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001579 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001580 visitor(*it);
1581 }
1582
1583 if (visitor.Failed()) {
1584 DumpSpaces();
1585 return false;
1586 }
1587 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001588}
1589
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001590void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001591 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001592
1593 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001594 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001595 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001596 }
1597}
1598
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001599void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001600 // Clear cards and keep track of cards cleared in the mod-union table.
1601 typedef std::vector<space::ContinuousSpace*>::iterator It;
1602 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1603 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001604 if (space->IsImageSpace()) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001605 base::TimingLogger::ScopedSplit split("ImageModUnionClearCards", &timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07001606 image_mod_union_table_->ClearCards(space);
1607 } else if (space->IsZygoteSpace()) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001608 base::TimingLogger::ScopedSplit split("ZygoteModUnionClearCards", &timings);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001609 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001610 } else {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001611 base::TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001612 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1613 // were dirty before the GC started.
1614 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001615 }
1616 }
1617}
1618
Ian Rogers1d54e732013-05-02 21:10:01 -07001619void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001620 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1621 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001622
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001623 if (verify_pre_gc_heap_) {
1624 thread_list->SuspendAll();
1625 {
1626 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1627 if (!VerifyHeapReferences()) {
1628 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1629 }
1630 }
1631 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001632 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001633
1634 // Check that all objects which reference things in the live stack are on dirty cards.
1635 if (verify_missing_card_marks_) {
1636 thread_list->SuspendAll();
1637 {
1638 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1639 SwapStacks();
1640 // Sort the live stack so that we can quickly binary search it later.
1641 if (!VerifyMissingCardMarks()) {
1642 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1643 }
1644 SwapStacks();
1645 }
1646 thread_list->ResumeAll();
1647 }
1648
1649 if (verify_mod_union_table_) {
1650 thread_list->SuspendAll();
1651 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1652 zygote_mod_union_table_->Update();
1653 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001654 image_mod_union_table_->Update();
1655 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001656 thread_list->ResumeAll();
1657 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001658}
1659
Ian Rogers1d54e732013-05-02 21:10:01 -07001660void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001661 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001662
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001663 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1664 // reachable objects.
1665 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001666 Thread* self = Thread::Current();
1667 CHECK_NE(self->GetState(), kRunnable);
1668 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001669 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001670 {
1671 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1672 // Swapping bound bitmaps does nothing.
1673 gc->SwapBitmaps();
1674 if (!VerifyHeapReferences()) {
1675 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1676 }
1677 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001678 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001679 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001680 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001681 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001682}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001683
Ian Rogers1d54e732013-05-02 21:10:01 -07001684void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001685 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001686
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001687 if (verify_system_weaks_) {
1688 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001689 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001690 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001691 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001692}
1693
Ian Rogers1d54e732013-05-02 21:10:01 -07001694collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1695 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001696 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001697 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001698 bool do_wait;
1699 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001700 {
1701 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001702 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001703 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001704 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001705 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001706 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707 // We must wait, change thread state then sleep on gc_complete_cond_;
1708 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1709 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001710 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001711 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001712 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001713 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001714 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001715 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001716 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001717 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001718 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001719 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1720 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001721 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001722 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001723 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001724 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001725}
1726
Elliott Hughesc967f782012-04-16 10:23:15 -07001727void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001728 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001729 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001730 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001731}
1732
1733size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001734 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001735}
1736
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001737void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001738 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001739 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001740 << PrettySize(GetMaxMemory());
1741 max_allowed_footprint = GetMaxMemory();
1742 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001743 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001744}
1745
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001746void Heap::UpdateMaxNativeFootprint() {
1747 size_t native_size = native_bytes_allocated_;
1748 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1749 size_t target_size = native_size / GetTargetHeapUtilization();
1750 if (target_size > native_size + max_free_) {
1751 target_size = native_size + max_free_;
1752 } else if (target_size < native_size + min_free_) {
1753 target_size = native_size + min_free_;
1754 }
1755 native_footprint_gc_watermark_ = target_size;
1756 native_footprint_limit_ = 2 * target_size - native_size;
1757}
1758
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001759void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001760 // We know what our utilization is at this moment.
1761 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001762 const size_t bytes_allocated = GetBytesAllocated();
1763 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001764 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001765
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001766 size_t target_size;
1767 if (gc_type != collector::kGcTypeSticky) {
1768 // Grow the heap for non sticky GC.
1769 target_size = bytes_allocated / GetTargetHeapUtilization();
1770 if (target_size > bytes_allocated + max_free_) {
1771 target_size = bytes_allocated + max_free_;
1772 } else if (target_size < bytes_allocated + min_free_) {
1773 target_size = bytes_allocated + min_free_;
1774 }
1775 next_gc_type_ = collector::kGcTypeSticky;
1776 } else {
1777 // Based on how close the current heap size is to the target size, decide
1778 // whether or not to do a partial or sticky GC next.
1779 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1780 next_gc_type_ = collector::kGcTypeSticky;
1781 } else {
1782 next_gc_type_ = collector::kGcTypePartial;
1783 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001784
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001785 // If we have freed enough memory, shrink the heap back down.
1786 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1787 target_size = bytes_allocated + max_free_;
1788 } else {
1789 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1790 }
1791 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001792 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001793
Ian Rogers1d54e732013-05-02 21:10:01 -07001794 // Calculate when to perform the next ConcurrentGC.
1795 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001796 // Calculate the estimated GC duration.
1797 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1798 // Estimate how many remaining bytes we will have when we need to start the next GC.
1799 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001800 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1801 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1802 // A never going to happen situation that from the estimated allocation rate we will exceed
1803 // the applications entire footprint with the given estimated allocation rate. Schedule
1804 // another GC straight away.
1805 concurrent_start_bytes_ = bytes_allocated;
1806 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001807 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1808 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1809 // right away.
1810 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001811 }
1812 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1813 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1814 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001815
1816 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001817}
1818
jeffhaoc1160702011-10-27 15:48:45 -07001819void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001820 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001821 alloc_space_->ClearGrowthLimit();
1822}
1823
Elliott Hughesadb460d2011-10-05 17:02:34 -07001824void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001825 MemberOffset reference_queue_offset,
1826 MemberOffset reference_queueNext_offset,
1827 MemberOffset reference_pendingNext_offset,
1828 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001829 reference_referent_offset_ = reference_referent_offset;
1830 reference_queue_offset_ = reference_queue_offset;
1831 reference_queueNext_offset_ = reference_queueNext_offset;
1832 reference_pendingNext_offset_ = reference_pendingNext_offset;
1833 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1834 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1835 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1836 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1837 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1838 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1839}
1840
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001841mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001842 DCHECK(reference != NULL);
1843 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001844 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001845}
1846
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001847void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001848 DCHECK(reference != NULL);
1849 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1850 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1851}
1852
1853// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001854bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001855 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001856 const mirror::Object* queue =
1857 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1858 const mirror::Object* queue_next =
1859 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001860 return (queue != NULL) && (queue_next == NULL);
1861}
1862
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001863void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001864 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001865 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1866 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001867 EnqueuePendingReference(ref, cleared_reference_list);
1868}
1869
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001870void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001871 DCHECK(ref != NULL);
1872 DCHECK(list != NULL);
1873
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001874 // TODO: Remove this lock, use atomic stacks for storing references.
1875 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001876 if (*list == NULL) {
1877 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1878 *list = ref;
1879 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001880 mirror::Object* head =
1881 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001882 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1883 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1884 }
1885}
1886
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001887mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001888 DCHECK(list != NULL);
1889 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001890 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1891 false);
1892 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001893
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001894 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1895 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001896 if (*list == head) {
1897 ref = *list;
1898 *list = NULL;
1899 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001900 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1901 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001902 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1903 ref = head;
1904 }
1905 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1906 return ref;
1907}
1908
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001909void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001910 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001911 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001912 ArgArray arg_array(NULL, 0);
1913 arg_array.Append(reinterpret_cast<uint32_t>(object));
1914 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001915 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001916}
1917
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001918void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001919 DCHECK(cleared != NULL);
1920 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001921 // When a runtime isn't started there are no reference queues to care about so ignore.
1922 if (LIKELY(Runtime::Current()->IsStarted())) {
1923 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001924 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001925 ArgArray arg_array(NULL, 0);
1926 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1927 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001928 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001929 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001930 *cleared = NULL;
1931 }
1932}
1933
Ian Rogers1f539342012-10-03 21:09:42 -07001934void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001935 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001936 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001937 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001938 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001939 !runtime->IsConcurrentGcEnabled()) {
1940 return;
1941 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001942 {
1943 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1944 if (runtime->IsShuttingDown()) {
1945 return;
1946 }
1947 }
1948 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001949 return;
1950 }
1951
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001952 // We already have a request pending, no reason to start more until we update
1953 // concurrent_start_bytes_.
1954 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1955
Ian Rogers120f1c72012-09-28 17:17:10 -07001956 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001957 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1958 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001959 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1960 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001961 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001962}
1963
Ian Rogers81d425b2012-09-27 16:03:43 -07001964void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001965 {
1966 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001967 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001968 return;
1969 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001970 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001971
Mathieu Chartier65db8802012-11-20 12:36:46 -08001972 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001973 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001974 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001975 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001976}
1977
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001978void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001979 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1980 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1981 // a space it will hold its lock and can become a cause of jank.
1982 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1983 // forking.
1984
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001985 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1986 // because that only marks object heads, so a large array looks like lots of empty space. We
1987 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1988 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1989 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1990 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001991 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001992 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001993 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
Mathieu Chartiere0a53e92013-08-05 10:17:40 -07001994 if ((utilization > 0.75f && !IsLowMemoryMode()) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
1995 // Don't bother trimming the alloc space if it's more than 75% utilized and low memory mode is
1996 // not enabled, or if a heap trim occurred in the last two seconds.
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001997 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001998 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001999
2000 Thread* self = Thread::Current();
2001 {
2002 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2003 Runtime* runtime = Runtime::Current();
2004 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2005 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2006 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2007 // as we don't hold the lock while requesting the trim).
2008 return;
2009 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002010 }
Ian Rogers48931882013-01-22 14:35:16 -08002011
Ian Rogers1d54e732013-05-02 21:10:01 -07002012 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002013 ListenForProcessStateChange();
2014
2015 // Trim only if we do not currently care about pause times.
2016 if (!care_about_pause_times_) {
2017 JNIEnv* env = self->GetJniEnv();
2018 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2019 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2020 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2021 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2022 CHECK(!env->ExceptionCheck());
2023 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002024}
2025
Ian Rogers48931882013-01-22 14:35:16 -08002026size_t Heap::Trim() {
2027 // Handle a requested heap trim on a thread outside of the main GC thread.
2028 return alloc_space_->Trim();
2029}
2030
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002031bool Heap::IsGCRequestPending() const {
2032 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2033}
2034
2035void Heap::RegisterNativeAllocation(int bytes) {
2036 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002037 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002038 Thread* self = Thread::Current();
2039 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
2040 // The second watermark is higher than the gc watermark. If you hit this it means you are
2041 // allocating native objects faster than the GC can keep up with.
2042 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2043 JNIEnv* env = self->GetJniEnv();
2044 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
2045 // point.
2046 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
2047 DCHECK(WellKnownClasses::java_lang_System != NULL);
2048 WellKnownClasses::java_lang_System_runFinalization =
2049 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2050 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
2051 }
2052 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
2053 // Just finished a GC, attempt to run finalizers.
2054 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2055 WellKnownClasses::java_lang_System_runFinalization);
2056 CHECK(!env->ExceptionCheck());
2057 }
2058
2059 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2060 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2061 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2062 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2063 WellKnownClasses::java_lang_System_runFinalization);
2064 CHECK(!env->ExceptionCheck());
2065 }
2066 // We have just run finalizers, update the native watermark since it is very likely that
2067 // finalizers released native managed allocations.
2068 UpdateMaxNativeFootprint();
2069 } else {
2070 if (!IsGCRequestPending()) {
2071 RequestConcurrentGC(self);
2072 }
2073 }
2074 }
2075}
2076
2077void Heap::RegisterNativeFree(int bytes) {
2078 int expected_size, new_size;
2079 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002080 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002081 new_size = expected_size - bytes;
2082 if (new_size < 0) {
2083 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
2084 bytes, expected_size);
2085 break;
2086 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002087 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002088}
2089
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002090int64_t Heap::GetTotalMemory() const {
2091 int64_t ret = 0;
2092 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
2093 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
2094 space::ContinuousSpace* space = *it;
2095 if (space->IsImageSpace()) {
2096 // Currently don't include the image space.
2097 } else if (space->IsDlMallocSpace()) {
2098 // Zygote or alloc space
2099 ret += space->AsDlMallocSpace()->GetFootprint();
2100 }
2101 }
2102 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
2103 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
2104 space::DiscontinuousSpace* space = *it;
2105 if (space->IsLargeObjectSpace()) {
2106 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2107 }
2108 }
2109 return ret;
2110}
2111
Ian Rogers1d54e732013-05-02 21:10:01 -07002112} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002113} // namespace art