blob: adc7b3c996d926729e73522a78ec7d848b73b483 [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>
24
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070026#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080027#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070028#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "gc/accounting/atomic_stack.h"
30#include "gc/accounting/card_table-inl.h"
31#include "gc/accounting/heap_bitmap-inl.h"
32#include "gc/accounting/mod_union_table-inl.h"
33#include "gc/accounting/space_bitmap-inl.h"
34#include "gc/collector/mark_sweep-inl.h"
35#include "gc/collector/partial_mark_sweep.h"
36#include "gc/collector/sticky_mark_sweep.h"
37#include "gc/space/image_space.h"
38#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070040#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080041#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/class-inl.h"
43#include "mirror/field-inl.h"
44#include "mirror/object.h"
45#include "mirror/object-inl.h"
46#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080047#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080048#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070049#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070050#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070051#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070052#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070053#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070055
56namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070057namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070058
Ian Rogers1d54e732013-05-02 21:10:01 -070059// When to create a log message about a slow GC, 100ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080060static const uint64_t kSlowGcThreshold = MsToNs(100);
Ian Rogers1d54e732013-05-02 21:10:01 -070061// When to create a log message about a slow pause, 5ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080062static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080063static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070064// Minimum amount of remaining bytes before a concurrent GC is triggered.
65static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070066const double Heap::kDefaultTargetUtilization = 0.5;
67
Mathieu Chartier0051be62012-10-12 17:47:11 -070068Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
69 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -070070 const std::string& original_image_file_name, bool concurrent_gc)
71 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080072 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070073 concurrent_gc_(concurrent_gc),
74 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070075 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080076 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070077 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070078 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080079 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070080 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070081 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070082 native_footprint_gc_watermark_(initial_size),
83 native_footprint_limit_(2 * initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -070084 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
85 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -070086 total_bytes_freed_ever_(0),
87 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070088 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080089 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070090 native_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -070091 verify_missing_card_marks_(false),
92 verify_system_weaks_(false),
93 verify_pre_gc_heap_(false),
94 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -070095 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070096 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -070097 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -070098 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -080099 allocation_rate_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700100 max_allocation_stack_size_(kDesiredHeapVerification > kNoHeapVerification? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800101 reference_referent_offset_(0),
102 reference_queue_offset_(0),
103 reference_queueNext_offset_(0),
104 reference_pendingNext_offset_(0),
105 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700106 min_free_(min_free),
107 max_free_(max_free),
108 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700109 total_wait_time_(0),
110 measure_allocation_time_(false),
111 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700112 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800113 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800114 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700115 }
116
Ian Rogers1d54e732013-05-02 21:10:01 -0700117 live_bitmap_.reset(new accounting::HeapBitmap(this));
118 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700119
Ian Rogers30fab402012-01-23 15:43:46 -0800120 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700121 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800122 std::string image_file_name(original_image_file_name);
123 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700124 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
125 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700126 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800127 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
128 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800129 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
130 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700131 if (oat_file_end_addr > requested_alloc_space_begin) {
132 requested_alloc_space_begin =
133 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
134 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700135 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700136 }
137
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700138 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700139 const bool kUseFreeListSpaceForLOS = false;
140 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700141 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700142 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700143 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700144 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700145 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
146 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700147
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700148 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700149 initial_size,
150 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700151 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700152 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700153 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700154 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700155
Ian Rogers1d54e732013-05-02 21:10:01 -0700156 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
157 byte* heap_begin = continuous_spaces_.front()->Begin();
158 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
159 if (continuous_spaces_.back()->IsDlMallocSpace()) {
160 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700161 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700162
Ian Rogers30fab402012-01-23 15:43:46 -0800163 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700164 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700165 typedef std::vector<space::ContinuousSpace*>::iterator It;
166 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
167 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800168 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700169 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700170 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800171 }
172 }
173
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800174 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700175 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700176 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700177
Ian Rogers1d54e732013-05-02 21:10:01 -0700178 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
179 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700180
Ian Rogers1d54e732013-05-02 21:10:01 -0700181 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700182 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700183
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700184 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700185 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700186
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800187 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700188 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700189 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
190 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
191 max_allocation_stack_size_));
192 live_stack_.reset(accounting::ObjectStack::Create("live stack",
193 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700194
Mathieu Chartier65db8802012-11-20 12:36:46 -0800195 // It's still too early to take a lock because there are no threads yet, but we can create locks
196 // now. We don't create it earlier to make it clear that you can't use locks during heap
197 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700198 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700199 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
200 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700201
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700202 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700203 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700204
Ian Rogers1d54e732013-05-02 21:10:01 -0700205 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800206 last_gc_size_ = GetBytesAllocated();
207
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800208 // Create our garbage collectors.
209 for (size_t i = 0; i < 2; ++i) {
210 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700211 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
212 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
213 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700214 }
215
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800216 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800217 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800218 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700219 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700220}
221
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700222void Heap::CreateThreadPool() {
223 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
224 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
225 // workers to complete.
Ian Rogers1d54e732013-05-02 21:10:01 -0700226 thread_pool_.reset(new ThreadPool(1)); // new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700227}
228
229void Heap::DeleteThreadPool() {
230 thread_pool_.reset(NULL);
231}
232
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700233// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700234struct ContinuousSpaceSorter {
Brian Carlstromdf629502013-07-17 22:39:56 -0700235 bool operator()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700236 return a->Begin() < b->Begin();
237 }
238};
239
Ian Rogers1d54e732013-05-02 21:10:01 -0700240void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700241 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700242 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700243 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700244 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700245 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700246 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
247 continuous_spaces_.push_back(space);
248 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
249 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700250 }
251
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700252 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700253 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700254
255 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
256 // avoid redundant marking.
257 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700258 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
259 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
260 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700261 if (space->IsImageSpace()) {
262 DCHECK(!seen_zygote);
263 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700264 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700265 DCHECK(!seen_alloc);
266 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700267 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700268 seen_alloc = true;
269 }
270 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800271}
272
Ian Rogers1d54e732013-05-02 21:10:01 -0700273void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
274 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
275 DCHECK(space != NULL);
276 DCHECK(space->GetLiveObjects() != NULL);
277 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
278 DCHECK(space->GetMarkObjects() != NULL);
279 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
280 discontinuous_spaces_.push_back(space);
281}
282
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700283void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700284 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700285 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700286 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800287
288 // Dump cumulative loggers for each GC type.
289 // TODO: C++0x
290 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700291 typedef std::vector<collector::MarkSweep*>::const_iterator It;
292 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800293 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700294 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800295 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800296 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700297 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800298 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700299 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800300 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
301 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
302 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700303 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
304 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
305 << collector->GetName() << " freed: " << freed_objects
306 << " objects with total size " << PrettySize(freed_bytes) << "\n"
307 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
308 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800309 total_duration += total_ns;
310 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700311 }
312 }
313 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700314 size_t total_objects_allocated = GetObjectsAllocatedEver();
315 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700316 if (total_duration != 0) {
317 const double total_seconds = double(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700318 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
319 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700320 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700321 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700322 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700323 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700324 os << "Total number of allocations: " << total_objects_allocated << "\n";
325 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700326 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700327 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
328 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
329 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700330 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700331 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
332 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700333}
334
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800335Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700336 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700337 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700338 }
339
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800340 STLDeleteElements(&mark_sweep_collectors_);
341
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700342 // If we don't reset then the mark stack complains in it's destructor.
343 allocation_stack_->Reset();
344 live_stack_->Reset();
345
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800346 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800347 // We can't take the heap lock here because there might be a daemon thread suspended with the
348 // heap lock held. We know though that no non-daemon threads are executing, and we know that
349 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
350 // 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 -0700351 STLDeleteElements(&continuous_spaces_);
352 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700353 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700354 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700355}
356
Ian Rogers1d54e732013-05-02 21:10:01 -0700357space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
358 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700359 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700360 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
361 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700362 if ((*it)->Contains(obj)) {
363 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700364 }
365 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700366 if (!fail_ok) {
367 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
368 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700369 return NULL;
370}
371
Ian Rogers1d54e732013-05-02 21:10:01 -0700372space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
373 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700374 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700375 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
376 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
377 if ((*it)->Contains(obj)) {
378 return *it;
379 }
380 }
381 if (!fail_ok) {
382 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
383 }
384 return NULL;
385}
386
387space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
388 space::Space* result = FindContinuousSpaceFromObject(obj, true);
389 if (result != NULL) {
390 return result;
391 }
392 return FindDiscontinuousSpaceFromObject(obj, true);
393}
394
395space::ImageSpace* Heap::GetImageSpace() const {
396 // TODO: C++0x auto
397 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
398 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700399 if ((*it)->IsImageSpace()) {
400 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700401 }
402 }
403 return NULL;
404}
405
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700406static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700407 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700408 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700409 size_t chunk_free_bytes = chunk_size - used_bytes;
410 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
411 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700412 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700413}
414
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800415mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
416 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700417 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
418 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800419 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700420
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800421 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700422 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700423 uint64_t allocation_start = 0;
424 if (measure_allocation_time_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700425 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700426 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700427
428 // We need to have a zygote space or else our newly allocated large object can end up in the
429 // Zygote resulting in it being prematurely freed.
430 // We can only do this for primive objects since large objects will not be within the card table
431 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers22a20862013-03-16 16:34:57 -0700432 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700433 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700434 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700435 // Make sure that our large object didn't get placed anywhere within the space interval or else
436 // it breaks the immune range.
437 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700438 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
439 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700440 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700441 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700442
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700443 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700444 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700445 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700446 }
447
Mathieu Chartier037813d2012-08-23 16:44:59 -0700448 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700449 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700450
451 // Record allocation after since we want to use the atomic add for the atomic fence to guard
452 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700453 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700454
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700455 if (Dbg::IsAllocTrackingEnabled()) {
456 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700457 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700458 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700459 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700461 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 }
463 VerifyObject(obj);
464
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700465 if (measure_allocation_time_) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700466 total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700467 }
468
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 return obj;
470 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800471 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700472 int64_t total_bytes_free = GetFreeMemory();
Ian Rogers1d54e732013-05-02 21:10:01 -0700473 uint64_t alloc_space_size = alloc_space_->GetBytesAllocated();
474 uint64_t large_object_size = large_object_space_->GetObjectsAllocated();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800475 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
476 << " free bytes; allocation space size " << alloc_space_size
477 << "; large object space size " << large_object_size;
478 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
479 if (total_bytes_free >= byte_count) {
480 size_t max_contiguous_allocation = 0;
481 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700482 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
483 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
484 space::ContinuousSpace* space = *it;
485 if (space->IsDlMallocSpace()) {
486 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800487 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700488 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800489 oss << "; failed due to fragmentation (largest possible contiguous allocation "
490 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700491 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800492 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700493 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700494}
495
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800496bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700497 // Note: we deliberately don't take the lock here, and mustn't test anything that would
498 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700499 if (obj == NULL) {
500 return true;
501 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700502 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700503 return false;
504 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700505 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700506}
507
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800508bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700509 //Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
510 if (obj == NULL) {
511 return false;
512 }
513 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
514 return false;
515 }
516 space::ContinuousSpace* cont_space = FindContinuousSpaceFromObject(obj, true);
517 if (cont_space != NULL) {
518 if (cont_space->GetLiveBitmap()->Test(obj)) {
519 return true;
520 }
521 } else {
522 space::DiscontinuousSpace* disc_space = FindDiscontinuousSpaceFromObject(obj, true);
523 if (disc_space != NULL) {
524 if (disc_space->GetLiveObjects()->Test(obj)) {
525 return true;
526 }
527 }
528 }
529 for (size_t i = 0; i < 5; ++i) {
530 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
531 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
532 return true;
533 }
534 NanoSleep(MsToNs(10));
535 }
536 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700537}
538
Ian Rogers04d7aa92013-03-16 14:29:17 -0700539void Heap::VerifyObjectImpl(const mirror::Object* obj) {
540 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700541 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700542 return;
543 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700544 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700545}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700546
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700547void Heap::DumpSpaces() {
548 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700549 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
550 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
551 space::ContinuousSpace* space = *it;
552 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
553 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700554 LOG(INFO) << space << " " << *space << "\n"
555 << live_bitmap << " " << *live_bitmap << "\n"
556 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700557 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700558 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
559 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
560 space::DiscontinuousSpace* space = *it;
561 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700562 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700563}
564
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800565void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800566 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700567 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700568 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800569 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
570 return;
571 }
572 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
573 mirror::Object::ClassOffset().Int32Value();
574 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
575 if (UNLIKELY(c == NULL)) {
576 LOG(FATAL) << "Null class in object: " << obj;
577 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
578 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
579 }
580 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
581 // Note: we don't use the accessors here as they have internal sanity checks
582 // that we don't want to run
583 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
584 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
585 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
586 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
587 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700588
Ian Rogers62d6c772013-02-27 08:32:07 -0800589 if (verify_object_mode_ != kVerifyAllFast) {
590 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
591 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700592 if (!IsLiveObjectLocked(obj)) {
593 DumpSpaces();
594 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700595 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700596 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700597 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
598 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700599 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700600}
601
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800602void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700603 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700604 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700605}
606
607void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700608 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700609 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700610}
611
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800612void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700613 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700614 DCHECK_GT(size, 0u);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700615 num_bytes_allocated_.fetch_add(size);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700616
617 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700618 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700619 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700620 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700621
622 // TODO: Update these atomically.
623 RuntimeStats* global_stats = Runtime::Current()->GetStats();
624 ++global_stats->allocated_objects;
625 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700626 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700627
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700628 // This is safe to do since the GC will never free objects which are neither in the allocation
629 // stack or the live bitmap.
630 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700631 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700632 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700633}
634
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700635void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700636 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700637 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700638
639 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700640 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700641 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700642 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700643
644 // TODO: Do this concurrently.
645 RuntimeStats* global_stats = Runtime::Current()->GetStats();
646 global_stats->freed_objects += freed_objects;
647 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700648 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700649}
650
Ian Rogers1d54e732013-05-02 21:10:01 -0700651mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
652 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700653 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800654 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
655 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
656 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
657 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700658 return NULL;
659 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700660 }
661
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700662 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700663}
664
Ian Rogers1d54e732013-05-02 21:10:01 -0700665mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700666 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
667 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700668 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700669 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700670
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800671 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700672 if (ptr != NULL) {
673 return ptr;
674 }
675
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700676 // The allocation failed. If the GC is running, block until it completes, and then retry the
677 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700678 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
679 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700680 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700681 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700682 if (ptr != NULL) {
683 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700684 }
685 }
686
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700687 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700688 for (size_t i = static_cast<size_t>(last_gc) + 1;
689 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700690 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700691 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700692 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700693 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700694 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700695 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
696 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700697 break;
698 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700699 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700700 run_gc = have_zygote_space_;
701 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700702 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700703 run_gc = true;
704 break;
705 default:
706 break;
707 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700708
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700709 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700710 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700711 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800712 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700713 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700714
715 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700716 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700717 if (ptr != NULL) {
718 return ptr;
719 }
720 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700721 }
722
723 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700724 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700725 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700726 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700727 return ptr;
728 }
729
Elliott Hughes81ff3182012-03-23 20:35:56 -0700730 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
731 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
732 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700733
Elliott Hughes418dfe72011-10-06 18:56:27 -0700734 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700735 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
736 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700737
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700738 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700739 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700740 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700741}
742
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700743void Heap::SetTargetHeapUtilization(float target) {
744 DCHECK_GT(target, 0.0f); // asserted in Java code
745 DCHECK_LT(target, 1.0f);
746 target_utilization_ = target;
747}
748
Ian Rogers1d54e732013-05-02 21:10:01 -0700749size_t Heap::GetObjectsAllocated() const {
750 size_t total = 0;
751 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
752 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
753 space::ContinuousSpace* space = *it;
754 if (space->IsDlMallocSpace()) {
755 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700756 }
757 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700758 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
759 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
760 space::DiscontinuousSpace* space = *it;
761 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
762 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700763 return total;
764}
765
Ian Rogers1d54e732013-05-02 21:10:01 -0700766size_t Heap::GetObjectsAllocatedEver() const {
767 size_t total = 0;
768 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
769 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
770 space::ContinuousSpace* space = *it;
771 if (space->IsDlMallocSpace()) {
772 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700773 }
774 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700775 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
776 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
777 space::DiscontinuousSpace* space = *it;
778 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
779 }
780 return total;
781}
782
783size_t Heap::GetBytesAllocatedEver() const {
784 size_t total = 0;
785 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
786 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
787 space::ContinuousSpace* space = *it;
788 if (space->IsDlMallocSpace()) {
789 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
790 }
791 }
792 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
793 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
794 space::DiscontinuousSpace* space = *it;
795 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
796 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700797 return total;
798}
799
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700800class InstanceCounter {
801 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800802 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700803 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800804 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700805 }
806
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800807 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800808 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800809 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800810 if (use_is_assignable_from_) {
811 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
812 ++counts_[i];
813 }
814 } else {
815 if (instance_class == classes_[i]) {
816 ++counts_[i];
817 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700818 }
819 }
820 }
821
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700822 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800823 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800824 bool use_is_assignable_from_;
825 uint64_t* const counts_;
826
827 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700828};
829
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800830void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800831 uint64_t* counts) {
832 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
833 // is empty, so the live bitmap is the only place we need to look.
834 Thread* self = Thread::Current();
835 self->TransitionFromRunnableToSuspended(kNative);
836 CollectGarbage(false);
837 self->TransitionFromSuspendedToRunnable();
838
839 InstanceCounter counter(classes, use_is_assignable_from, counts);
840 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700841 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700842}
843
Elliott Hughes3b78c942013-01-15 17:35:41 -0800844class InstanceCollector {
845 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800846 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800847 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
848 : class_(c), max_count_(max_count), instances_(instances) {
849 }
850
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800851 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
852 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800853 if (instance_class == class_) {
854 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800855 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800856 }
857 }
858 }
859
860 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800861 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800862 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800863 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800864
865 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
866};
867
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800868void Heap::GetInstances(mirror::Class* c, int32_t max_count,
869 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800870 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
871 // is empty, so the live bitmap is the only place we need to look.
872 Thread* self = Thread::Current();
873 self->TransitionFromRunnableToSuspended(kNative);
874 CollectGarbage(false);
875 self->TransitionFromSuspendedToRunnable();
876
877 InstanceCollector collector(c, max_count, instances);
878 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
879 GetLiveBitmap()->Visit(collector);
880}
881
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800882class ReferringObjectsFinder {
883 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800884 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
885 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800886 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
887 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
888 }
889
890 // For bitmap Visit.
891 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
892 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800893 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -0700894 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800895 }
896
897 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -0700898 void operator()(const mirror::Object* referrer, const mirror::Object* object,
899 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800900 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800901 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800902 }
903 }
904
905 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800906 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800907 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800908 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800909
910 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
911};
912
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800913void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
914 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800915 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
916 // is empty, so the live bitmap is the only place we need to look.
917 Thread* self = Thread::Current();
918 self->TransitionFromRunnableToSuspended(kNative);
919 CollectGarbage(false);
920 self->TransitionFromSuspendedToRunnable();
921
922 ReferringObjectsFinder finder(o, max_count, referring_objects);
923 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
924 GetLiveBitmap()->Visit(finder);
925}
926
Ian Rogers30fab402012-01-23 15:43:46 -0800927void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700928 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
929 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700930 Thread* self = Thread::Current();
931 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700932 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700933}
934
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700935void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700936 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800937 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
938 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700939 Thread* self = Thread::Current();
940 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700941
942 // Try to see if we have any Zygote spaces.
943 if (have_zygote_space_) {
944 return;
945 }
946
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700947 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
948
949 {
950 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700951 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700952 FlushAllocStack();
953 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700954
Ian Rogers1d54e732013-05-02 21:10:01 -0700955 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
956 // of the remaining available heap memory.
957 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700958 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -0700959 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700960
Ian Rogers1d54e732013-05-02 21:10:01 -0700961 // Change the GC retention policy of the zygote space to only collect when full.
962 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
963 AddContinuousSpace(alloc_space_);
964 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700965
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700966 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700967 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700968 typedef std::vector<collector::MarkSweep*>::const_iterator It;
969 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
970 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800971 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -0700972 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700973}
974
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700975void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700976 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
977 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700978 allocation_stack_->Reset();
979}
980
Ian Rogers1d54e732013-05-02 21:10:01 -0700981void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
982 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800983 mirror::Object** limit = stack->End();
984 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
985 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700986 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700987 if (LIKELY(bitmap->HasAddress(obj))) {
988 bitmap->Set(obj);
989 } else {
990 large_objects->Set(obj);
991 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700992 }
993}
994
Ian Rogers1d54e732013-05-02 21:10:01 -0700995void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
996 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800997 mirror::Object** limit = stack->End();
998 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
999 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001001 if (LIKELY(bitmap->HasAddress(obj))) {
1002 bitmap->Clear(obj);
1003 } else {
1004 large_objects->Clear(obj);
1005 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001006 }
1007}
1008
Ian Rogers1d54e732013-05-02 21:10:01 -07001009collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1010 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001011 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001012
1013 switch (gc_cause) {
1014 case kGcCauseForAlloc:
1015 ATRACE_BEGIN("GC (alloc)");
1016 break;
1017 case kGcCauseBackground:
1018 ATRACE_BEGIN("GC (background)");
1019 break;
1020 case kGcCauseExplicit:
1021 ATRACE_BEGIN("GC (explicit)");
1022 break;
1023 }
1024
Mathieu Chartier65db8802012-11-20 12:36:46 -08001025 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001026 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001027
Ian Rogers120f1c72012-09-28 17:17:10 -07001028 if (self->IsHandlingStackOverflow()) {
1029 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1030 }
1031
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001032 // Ensure there is only one GC at a time.
1033 bool start_collect = false;
1034 while (!start_collect) {
1035 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001036 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001037 if (!is_gc_running_) {
1038 is_gc_running_ = true;
1039 start_collect = true;
1040 }
1041 }
1042 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001043 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001044 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1045 // Not doing at the moment to ensure soft references are cleared.
1046 }
1047 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001048 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001049
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001050 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1051 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1052 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1053 }
1054
Ian Rogers1d54e732013-05-02 21:10:01 -07001055 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001056 uint64_t gc_start_size = GetBytesAllocated();
1057 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001058 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001059 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1060 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001061 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001062 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001063 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001064 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1065 }
1066
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001067 if (gc_type == collector::kGcTypeSticky &&
1068 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1069 gc_type = collector::kGcTypePartial;
1070 }
1071
Ian Rogers1d54e732013-05-02 21:10:01 -07001072 DCHECK_LT(gc_type, collector::kGcTypeMax);
1073 DCHECK_NE(gc_type, collector::kGcTypeNone);
1074 collector::MarkSweep* collector = NULL;
1075 typedef std::vector<collector::MarkSweep*>::iterator It;
1076 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1077 it != end; ++it) {
1078 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001079 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1080 collector = cur_collector;
1081 break;
1082 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001083 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001084 CHECK(collector != NULL)
1085 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1086 << " and type=" << gc_type;
1087 collector->clear_soft_references_ = clear_soft_references;
1088 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001089 total_objects_freed_ever_ += collector->GetFreedObjects();
1090 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001091
Ian Rogers1d54e732013-05-02 21:10:01 -07001092 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001093 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1094 bool was_slow = duration > kSlowGcThreshold ||
1095 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1096 for (size_t i = 0; i < pauses.size(); ++i) {
1097 if (pauses[i] > kLongGcPauseThreshold) {
1098 was_slow = true;
1099 }
1100 }
1101
1102 if (was_slow) {
1103 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001104 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001105 const size_t total_memory = GetTotalMemory();
1106 std::ostringstream pause_string;
1107 for (size_t i = 0; i < pauses.size(); ++i) {
1108 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1109 << ((i != pauses.size() - 1) ? ", " : "");
1110 }
1111 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001112 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1113 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1114 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1115 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001116 if (VLOG_IS_ON(heap)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001117 LOG(INFO) << Dumpable<base::NewTimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001118 }
1119 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001120
Ian Rogers15bf2d32012-08-28 17:33:04 -07001121 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001122 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001123 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001124 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001125 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001126 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001127 }
1128 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001129 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001130 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001131 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001132}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001133
Ian Rogers1d54e732013-05-02 21:10:01 -07001134void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::NewTimingLogger& timings,
1135 collector::GcType gc_type) {
1136 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001137 // 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 -07001138 // cards.
1139 return;
1140 }
1141
1142 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001143 if (gc_type == collector::kGcTypePartial) {
1144 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001145 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001146
Ian Rogers1d54e732013-05-02 21:10:01 -07001147 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001148 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001149 }
1150
1151 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001152 timings.NewSplit("UpdateModUnionTable");
1153 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001154
1155 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001156 timings.NewSplit("MarkImageToAllocSpaceReferences");
1157 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001158}
1159
Ian Rogers1d54e732013-05-02 21:10:01 -07001160static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001161 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001162 if (root == obj) {
1163 LOG(INFO) << "Object " << obj << " is a root";
1164 }
1165}
1166
1167class ScanVisitor {
1168 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001169 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001170 LOG(INFO) << "Would have rescanned object " << obj;
1171 }
1172};
1173
Ian Rogers1d54e732013-05-02 21:10:01 -07001174// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001175class VerifyReferenceVisitor {
1176 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001177 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001178 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001179 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001180
1181 bool Failed() const {
1182 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001183 }
1184
1185 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001186 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001187 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1188 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001189 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001190 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001191 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1192 accounting::CardTable* card_table = heap_->GetCardTable();
1193 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1194 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001195
Ian Rogers1d54e732013-05-02 21:10:01 -07001196 if (obj != NULL) {
1197 byte* card_addr = card_table->CardFromAddr(obj);
1198 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1199 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1200 << "\nObj type " << PrettyTypeOf(obj)
1201 << "\nRef type " << PrettyTypeOf(ref);
1202 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1203 void* cover_begin = card_table->AddrFromCard(card_addr);
1204 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1205 accounting::CardTable::kCardSize);
1206 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1207 << "-" << cover_end;
1208 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001209
Ian Rogers1d54e732013-05-02 21:10:01 -07001210 // Print out how the object is live.
1211 if (bitmap != NULL && bitmap->Test(obj)) {
1212 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1213 }
1214 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
1215 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1216 }
1217 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
1218 LOG(ERROR) << "Object " << obj << " found in live stack";
1219 }
1220 // Attempt to see if the card table missed the reference.
1221 ScanVisitor scan_visitor;
1222 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1223 card_table->Scan(bitmap, byte_cover_begin,
1224 byte_cover_begin + accounting::CardTable::kCardSize,
1225 scan_visitor, VoidFunctor());
1226
1227 // Search to see if any of the roots reference our object.
1228 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1229 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1230
1231 // Search to see if any of the roots reference our reference.
1232 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1233 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1234 } else {
1235 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001236 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001237 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1238 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001239 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001240 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001241 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001242 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001243 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1244 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1245 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001246 }
1247 }
1248
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001249 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001250 return heap_->IsLiveObjectLocked(obj);
1251 }
1252
1253 static void VerifyRoots(const mirror::Object* root, void* arg) {
1254 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1255 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001256 }
1257
1258 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001259 Heap* const heap_;
1260 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001261};
1262
Ian Rogers1d54e732013-05-02 21:10:01 -07001263// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001264class VerifyObjectVisitor {
1265 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001266 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001267
Brian Carlstromdf629502013-07-17 22:39:56 -07001268 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001269 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001270 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1271 // be live or else how did we find it in the live bitmap?
1272 VerifyReferenceVisitor visitor(heap_);
1273 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1274 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001275 }
1276
1277 bool Failed() const {
1278 return failed_;
1279 }
1280
1281 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001282 Heap* const heap_;
1283 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001284};
1285
1286// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001287bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001288 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001289 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001290 allocation_stack_->Sort();
1291 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001292 // Perform the verification.
1293 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001294 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001295 GetLiveBitmap()->Visit(visitor);
1296 // We don't want to verify the objects in the allocation stack since they themselves may be
1297 // pointing to dead objects if they are not reachable.
1298 if (visitor.Failed()) {
1299 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001300 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001301 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001302 return true;
1303}
1304
1305class VerifyReferenceCardVisitor {
1306 public:
1307 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1308 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1309 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001310 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001311 }
1312
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001313 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1314 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001315 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1316 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001317 // Filter out class references since changing an object's class does not mark the card as dirty.
1318 // Also handles large objects, since the only reference they hold is a class reference.
1319 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001320 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001321 // If the object is not dirty and it is referencing something in the live stack other than
1322 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001323 if (!card_table->AddrIsInCardTable(obj)) {
1324 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1325 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001326 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001327 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1328 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001329 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
1330 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1331 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001332 LOG(ERROR) << "Object " << obj << " found in live stack";
1333 }
1334 if (heap_->GetLiveBitmap()->Test(obj)) {
1335 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1336 }
1337 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1338 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1339
1340 // Print which field of the object is dead.
1341 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001342 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001343 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001344 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1345 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001346 CHECK(fields != NULL);
1347 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001348 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001349 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1350 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1351 << PrettyField(cur);
1352 break;
1353 }
1354 }
1355 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001356 const mirror::ObjectArray<mirror::Object>* object_array =
1357 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001358 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1359 if (object_array->Get(i) == ref) {
1360 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1361 }
1362 }
1363 }
1364
1365 *failed_ = true;
1366 }
1367 }
1368 }
1369 }
1370
1371 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001372 Heap* const heap_;
1373 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001374};
1375
1376class VerifyLiveStackReferences {
1377 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001378 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001379 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001380 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001381
Brian Carlstromdf629502013-07-17 22:39:56 -07001382 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001383 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1384 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001385 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001386 }
1387
1388 bool Failed() const {
1389 return failed_;
1390 }
1391
1392 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001393 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001394 bool failed_;
1395};
1396
1397bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001398 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001399
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001400 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001401 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001402 VerifyLiveStackReferences visitor(this);
1403 GetLiveBitmap()->Visit(visitor);
1404
1405 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001406 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001407 visitor(*it);
1408 }
1409
1410 if (visitor.Failed()) {
1411 DumpSpaces();
1412 return false;
1413 }
1414 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001415}
1416
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001417void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001418 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001419
1420 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001421 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001422 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001423 }
1424}
1425
Ian Rogers1d54e732013-05-02 21:10:01 -07001426void Heap::ProcessCards(base::NewTimingLogger& timings) {
1427 // Clear cards and keep track of cards cleared in the mod-union table.
1428 typedef std::vector<space::ContinuousSpace*>::iterator It;
1429 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1430 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001431 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001432 timings.NewSplit("ModUnionClearCards");
1433 image_mod_union_table_->ClearCards(space);
1434 } else if (space->IsZygoteSpace()) {
1435 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001436 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001437 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001438 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1439 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001440 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001441 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001442 }
1443 }
1444}
1445
Ian Rogers1d54e732013-05-02 21:10:01 -07001446void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001447 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1448 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001449
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001450 if (verify_pre_gc_heap_) {
1451 thread_list->SuspendAll();
1452 {
1453 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1454 if (!VerifyHeapReferences()) {
1455 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1456 }
1457 }
1458 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001459 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001460
1461 // Check that all objects which reference things in the live stack are on dirty cards.
1462 if (verify_missing_card_marks_) {
1463 thread_list->SuspendAll();
1464 {
1465 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1466 SwapStacks();
1467 // Sort the live stack so that we can quickly binary search it later.
1468 if (!VerifyMissingCardMarks()) {
1469 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1470 }
1471 SwapStacks();
1472 }
1473 thread_list->ResumeAll();
1474 }
1475
1476 if (verify_mod_union_table_) {
1477 thread_list->SuspendAll();
1478 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1479 zygote_mod_union_table_->Update();
1480 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001481 image_mod_union_table_->Update();
1482 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001483 thread_list->ResumeAll();
1484 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001485}
1486
Ian Rogers1d54e732013-05-02 21:10:01 -07001487void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001488 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001489
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001490 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1491 // reachable objects.
1492 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001493 Thread* self = Thread::Current();
1494 CHECK_NE(self->GetState(), kRunnable);
1495 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001496 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001497 {
1498 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1499 // Swapping bound bitmaps does nothing.
1500 gc->SwapBitmaps();
1501 if (!VerifyHeapReferences()) {
1502 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1503 }
1504 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001505 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001506 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001507 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001508 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001509}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001510
Ian Rogers1d54e732013-05-02 21:10:01 -07001511void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001512 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001513
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001514 if (verify_system_weaks_) {
1515 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001516 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001517 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001518 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001519}
1520
Ian Rogers1d54e732013-05-02 21:10:01 -07001521collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1522 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001523 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001524 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001525 bool do_wait;
1526 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001527 {
1528 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001529 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001530 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001531 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001532 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001533 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001534 // We must wait, change thread state then sleep on gc_complete_cond_;
1535 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1536 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001537 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001538 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001539 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001541 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001542 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001543 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001544 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001545 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001546 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1547 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001548 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001549 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001550 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001551 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001552}
1553
Elliott Hughesc967f782012-04-16 10:23:15 -07001554void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001555 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001556 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001557 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001558}
1559
1560size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001561 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001562}
1563
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001564void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001565 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001566 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001567 << PrettySize(GetMaxMemory());
1568 max_allowed_footprint = GetMaxMemory();
1569 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001570 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001571}
1572
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001573void Heap::UpdateMaxNativeFootprint() {
1574 size_t native_size = native_bytes_allocated_;
1575 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1576 size_t target_size = native_size / GetTargetHeapUtilization();
1577 if (target_size > native_size + max_free_) {
1578 target_size = native_size + max_free_;
1579 } else if (target_size < native_size + min_free_) {
1580 target_size = native_size + min_free_;
1581 }
1582 native_footprint_gc_watermark_ = target_size;
1583 native_footprint_limit_ = 2 * target_size - native_size;
1584}
1585
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001586void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001587 // We know what our utilization is at this moment.
1588 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001589 const size_t bytes_allocated = GetBytesAllocated();
1590 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001591 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001592
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001593 size_t target_size;
1594 if (gc_type != collector::kGcTypeSticky) {
1595 // Grow the heap for non sticky GC.
1596 target_size = bytes_allocated / GetTargetHeapUtilization();
1597 if (target_size > bytes_allocated + max_free_) {
1598 target_size = bytes_allocated + max_free_;
1599 } else if (target_size < bytes_allocated + min_free_) {
1600 target_size = bytes_allocated + min_free_;
1601 }
1602 next_gc_type_ = collector::kGcTypeSticky;
1603 } else {
1604 // Based on how close the current heap size is to the target size, decide
1605 // whether or not to do a partial or sticky GC next.
1606 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1607 next_gc_type_ = collector::kGcTypeSticky;
1608 } else {
1609 next_gc_type_ = collector::kGcTypePartial;
1610 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001611
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001612 // If we have freed enough memory, shrink the heap back down.
1613 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1614 target_size = bytes_allocated + max_free_;
1615 } else {
1616 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1617 }
1618 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001619 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001620
Ian Rogers1d54e732013-05-02 21:10:01 -07001621 // Calculate when to perform the next ConcurrentGC.
1622 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001623 // Calculate the estimated GC duration.
1624 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1625 // Estimate how many remaining bytes we will have when we need to start the next GC.
1626 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001627 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1628 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1629 // A never going to happen situation that from the estimated allocation rate we will exceed
1630 // the applications entire footprint with the given estimated allocation rate. Schedule
1631 // another GC straight away.
1632 concurrent_start_bytes_ = bytes_allocated;
1633 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001634 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1635 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1636 // right away.
1637 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001638 }
1639 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1640 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1641 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001642
1643 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001644}
1645
jeffhaoc1160702011-10-27 15:48:45 -07001646void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001647 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001648 alloc_space_->ClearGrowthLimit();
1649}
1650
Elliott Hughesadb460d2011-10-05 17:02:34 -07001651void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001652 MemberOffset reference_queue_offset,
1653 MemberOffset reference_queueNext_offset,
1654 MemberOffset reference_pendingNext_offset,
1655 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001656 reference_referent_offset_ = reference_referent_offset;
1657 reference_queue_offset_ = reference_queue_offset;
1658 reference_queueNext_offset_ = reference_queueNext_offset;
1659 reference_pendingNext_offset_ = reference_pendingNext_offset;
1660 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1661 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1662 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1663 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1664 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1665 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1666}
1667
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001668mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001669 DCHECK(reference != NULL);
1670 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001671 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001672}
1673
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001674void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001675 DCHECK(reference != NULL);
1676 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1677 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1678}
1679
1680// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001681bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001682 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001683 const mirror::Object* queue =
1684 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1685 const mirror::Object* queue_next =
1686 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001687 return (queue != NULL) && (queue_next == NULL);
1688}
1689
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001690void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001691 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001692 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1693 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001694 EnqueuePendingReference(ref, cleared_reference_list);
1695}
1696
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001697void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001698 DCHECK(ref != NULL);
1699 DCHECK(list != NULL);
1700
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001701 // TODO: Remove this lock, use atomic stacks for storing references.
1702 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001703 if (*list == NULL) {
1704 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1705 *list = ref;
1706 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001707 mirror::Object* head =
1708 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001709 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1710 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1711 }
1712}
1713
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001714mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001715 DCHECK(list != NULL);
1716 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001717 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1718 false);
1719 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001720
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001721 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1722 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001723 if (*list == head) {
1724 ref = *list;
1725 *list = NULL;
1726 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001727 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1728 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001729 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1730 ref = head;
1731 }
1732 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1733 return ref;
1734}
1735
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001736void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001737 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001738 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001739 ArgArray arg_array(NULL, 0);
1740 arg_array.Append(reinterpret_cast<uint32_t>(object));
1741 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001742 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001743}
1744
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001745void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001746 DCHECK(cleared != NULL);
1747 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001748 // When a runtime isn't started there are no reference queues to care about so ignore.
1749 if (LIKELY(Runtime::Current()->IsStarted())) {
1750 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001751 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001752 ArgArray arg_array(NULL, 0);
1753 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1754 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001755 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001756 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001757 *cleared = NULL;
1758 }
1759}
1760
Ian Rogers1f539342012-10-03 21:09:42 -07001761void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001762 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001763 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001764 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001765 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001766 !runtime->IsConcurrentGcEnabled()) {
1767 return;
1768 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001769 {
1770 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1771 if (runtime->IsShuttingDown()) {
1772 return;
1773 }
1774 }
1775 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001776 return;
1777 }
1778
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001779 // We already have a request pending, no reason to start more until we update
1780 // concurrent_start_bytes_.
1781 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1782
Ian Rogers120f1c72012-09-28 17:17:10 -07001783 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001784 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1785 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001786 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1787 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001788 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001789}
1790
Ian Rogers81d425b2012-09-27 16:03:43 -07001791void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001792 {
1793 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001794 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001795 return;
1796 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001797 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001798
Mathieu Chartier65db8802012-11-20 12:36:46 -08001799 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001800 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001801 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001802 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001803}
1804
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001805void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001806 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1807 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1808 // a space it will hold its lock and can become a cause of jank.
1809 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1810 // forking.
1811
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001812 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1813 // because that only marks object heads, so a large array looks like lots of empty space. We
1814 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1815 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1816 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1817 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001818 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001819 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001820 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1821 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001822 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1823 // heap trim occurred in the last two seconds.
1824 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001825 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001826
1827 Thread* self = Thread::Current();
1828 {
1829 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1830 Runtime* runtime = Runtime::Current();
1831 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1832 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1833 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1834 // as we don't hold the lock while requesting the trim).
1835 return;
1836 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001837 }
Ian Rogers48931882013-01-22 14:35:16 -08001838
1839 SchedPolicy policy;
1840 get_sched_policy(self->GetTid(), &policy);
1841 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1842 // Don't trim the heap if we are a foreground or audio app.
1843 return;
1844 }
1845
Ian Rogers1d54e732013-05-02 21:10:01 -07001846 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001847 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001848 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1849 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001850 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1851 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001852 CHECK(!env->ExceptionCheck());
1853}
1854
Ian Rogers48931882013-01-22 14:35:16 -08001855size_t Heap::Trim() {
1856 // Handle a requested heap trim on a thread outside of the main GC thread.
1857 return alloc_space_->Trim();
1858}
1859
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001860bool Heap::IsGCRequestPending() const {
1861 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
1862}
1863
1864void Heap::RegisterNativeAllocation(int bytes) {
1865 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001866 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001867 Thread* self = Thread::Current();
1868 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
1869 // The second watermark is higher than the gc watermark. If you hit this it means you are
1870 // allocating native objects faster than the GC can keep up with.
1871 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1872 JNIEnv* env = self->GetJniEnv();
1873 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
1874 // point.
1875 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
1876 DCHECK(WellKnownClasses::java_lang_System != NULL);
1877 WellKnownClasses::java_lang_System_runFinalization =
1878 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
1879 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
1880 }
1881 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
1882 // Just finished a GC, attempt to run finalizers.
1883 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1884 WellKnownClasses::java_lang_System_runFinalization);
1885 CHECK(!env->ExceptionCheck());
1886 }
1887
1888 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
1889 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1890 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
1891 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1892 WellKnownClasses::java_lang_System_runFinalization);
1893 CHECK(!env->ExceptionCheck());
1894 }
1895 // We have just run finalizers, update the native watermark since it is very likely that
1896 // finalizers released native managed allocations.
1897 UpdateMaxNativeFootprint();
1898 } else {
1899 if (!IsGCRequestPending()) {
1900 RequestConcurrentGC(self);
1901 }
1902 }
1903 }
1904}
1905
1906void Heap::RegisterNativeFree(int bytes) {
1907 int expected_size, new_size;
1908 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001909 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001910 new_size = expected_size - bytes;
1911 if (new_size < 0) {
1912 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
1913 bytes, expected_size);
1914 break;
1915 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001916 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001917}
1918
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001919int64_t Heap::GetTotalMemory() const {
1920 int64_t ret = 0;
1921 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1922 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1923 space::ContinuousSpace* space = *it;
1924 if (space->IsImageSpace()) {
1925 // Currently don't include the image space.
1926 } else if (space->IsDlMallocSpace()) {
1927 // Zygote or alloc space
1928 ret += space->AsDlMallocSpace()->GetFootprint();
1929 }
1930 }
1931 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
1932 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
1933 space::DiscontinuousSpace* space = *it;
1934 if (space->IsLargeObjectSpace()) {
1935 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
1936 }
1937 }
1938 return ret;
1939}
1940
Ian Rogers1d54e732013-05-02 21:10:01 -07001941} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001942} // namespace art