blob: ae843cbd42589eafd7746ac32b3fb55a1e5ce4bd [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"
Ian Rogers48931882013-01-22 14:35:16 -080026#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070027#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070028#include "gc/accounting/atomic_stack.h"
29#include "gc/accounting/card_table-inl.h"
30#include "gc/accounting/heap_bitmap-inl.h"
31#include "gc/accounting/mod_union_table-inl.h"
32#include "gc/accounting/space_bitmap-inl.h"
33#include "gc/collector/mark_sweep-inl.h"
34#include "gc/collector/partial_mark_sweep.h"
35#include "gc/collector/sticky_mark_sweep.h"
36#include "gc/space/image_space.h"
37#include "gc/space/large_object_space.h"
38#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070039#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080040#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mirror/class-inl.h"
42#include "mirror/field-inl.h"
43#include "mirror/object.h"
44#include "mirror/object-inl.h"
45#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080046#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080047#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070048#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070049#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070050#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070051#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070052#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070054
55namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070056namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070057
Ian Rogers1d54e732013-05-02 21:10:01 -070058// When to create a log message about a slow GC, 100ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080059static const uint64_t kSlowGcThreshold = MsToNs(100);
Mathieu Chartier82353312013-07-18 10:47:51 -070060// When to create a log message about a long pause, 5ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080061static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080062static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070063// Minimum amount of remaining bytes before a concurrent GC is triggered.
64static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070065const double Heap::kDefaultTargetUtilization = 0.5;
66
Mathieu Chartier0051be62012-10-12 17:47:11 -070067Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
68 double target_utilization, size_t capacity,
Mathieu Chartier63a54342013-07-23 13:17:59 -070069 const std::string& original_image_file_name, bool concurrent_gc, size_t num_gc_threads)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070070 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080071 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070072 concurrent_gc_(concurrent_gc),
Mathieu Chartier63a54342013-07-23 13:17:59 -070073 num_gc_threads_(num_gc_threads),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070074 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),
Ian Rogers1d54e732013-05-02 21:10:01 -070082 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
83 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -070084 total_bytes_freed_ever_(0),
85 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070086 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080087 num_bytes_allocated_(0),
Mathieu Chartier82353312013-07-18 10:47:51 -070088 process_state_(PROCESS_STATE_TOP),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -070089 verify_missing_card_marks_(false),
90 verify_system_weaks_(false),
91 verify_pre_gc_heap_(false),
92 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -070093 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070094 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -070095 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -070096 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -080097 allocation_rate_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -070098 max_allocation_stack_size_(kDesiredHeapVerification > kNoHeapVerification? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080099 reference_referent_offset_(0),
100 reference_queue_offset_(0),
101 reference_queueNext_offset_(0),
102 reference_pendingNext_offset_(0),
103 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700104 min_free_(min_free),
105 max_free_(max_free),
106 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700107 total_wait_time_(0),
108 measure_allocation_time_(false),
109 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700110 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800111 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800112 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700113 }
114
Ian Rogers1d54e732013-05-02 21:10:01 -0700115 live_bitmap_.reset(new accounting::HeapBitmap(this));
116 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700117
Ian Rogers30fab402012-01-23 15:43:46 -0800118 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700119 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800120 std::string image_file_name(original_image_file_name);
121 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700122 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
123 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700124 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800125 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
126 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800127 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
128 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700129 if (oat_file_end_addr > requested_alloc_space_begin) {
130 requested_alloc_space_begin =
131 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
132 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700133 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700134 }
135
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700136 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700137 const bool kUseFreeListSpaceForLOS = false;
138 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700139 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700140 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700141 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700142 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700143 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
144 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700145
Ian Rogers1d54e732013-05-02 21:10:01 -0700146 alloc_space_ = space::DlMallocSpace::Create("alloc space",
147 initial_size,
148 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700149 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700150 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700151 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700152 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700153
Ian Rogers1d54e732013-05-02 21:10:01 -0700154 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
155 byte* heap_begin = continuous_spaces_.front()->Begin();
156 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
157 if (continuous_spaces_.back()->IsDlMallocSpace()) {
158 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700159 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700160
Ian Rogers30fab402012-01-23 15:43:46 -0800161 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700162 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700163 typedef std::vector<space::ContinuousSpace*>::iterator It;
164 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
165 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800166 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700167 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700168 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800169 }
170 }
171
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800172 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700173 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700174 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700175
Ian Rogers1d54e732013-05-02 21:10:01 -0700176 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
177 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700178
Ian Rogers1d54e732013-05-02 21:10:01 -0700179 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700180 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700181
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700182 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700183 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700184
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800185 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700186 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700187 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
188 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
189 max_allocation_stack_size_));
190 live_stack_.reset(accounting::ObjectStack::Create("live stack",
191 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700192
Mathieu Chartier65db8802012-11-20 12:36:46 -0800193 // It's still too early to take a lock because there are no threads yet, but we can create locks
194 // now. We don't create it earlier to make it clear that you can't use locks during heap
195 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700196 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700197 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
198 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700199
Mathieu Chartier63a54342013-07-23 13:17:59 -0700200 // Create the reference queue lock, this is required so for parallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700201 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700202
Ian Rogers1d54e732013-05-02 21:10:01 -0700203 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800204 last_gc_size_ = GetBytesAllocated();
205
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800206 // Create our garbage collectors.
207 for (size_t i = 0; i < 2; ++i) {
208 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700209 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
210 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
211 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700212 }
213
Brian Carlstrom42748892013-07-18 18:04:08 -0700214 CHECK_NE(max_allowed_footprint_, 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800215 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800216 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700217 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700218}
219
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700220void Heap::CreateThreadPool() {
Mathieu Chartier63a54342013-07-23 13:17:59 -0700221 thread_pool_.reset(new ThreadPool(num_gc_threads_));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700222}
223
224void Heap::DeleteThreadPool() {
225 thread_pool_.reset(NULL);
226}
227
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700228// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700229struct ContinuousSpaceSorter {
Brian Carlstromdf629502013-07-17 22:39:56 -0700230 bool operator()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700231 return a->Begin() < b->Begin();
232 }
233};
234
Mathieu Chartier82353312013-07-18 10:47:51 -0700235void Heap::UpdateProcessState(ProcessState process_state) {
236 process_state_ = process_state;
237}
238
Ian Rogers1d54e732013-05-02 21:10:01 -0700239void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700240 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700241 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700242 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700243 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700244 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700245 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
246 continuous_spaces_.push_back(space);
247 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
248 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700249 }
250
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700251 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700252 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700253
254 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
255 // avoid redundant marking.
256 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700257 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
258 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
259 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700260 if (space->IsImageSpace()) {
261 DCHECK(!seen_zygote);
262 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700263 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700264 DCHECK(!seen_alloc);
265 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700266 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700267 seen_alloc = true;
268 }
269 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800270}
271
Ian Rogers1d54e732013-05-02 21:10:01 -0700272void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
273 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
274 DCHECK(space != NULL);
275 DCHECK(space->GetLiveObjects() != NULL);
276 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
277 DCHECK(space->GetMarkObjects() != NULL);
278 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
279 discontinuous_spaces_.push_back(space);
280}
281
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700282void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700283 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700284 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700285 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800286
287 // Dump cumulative loggers for each GC type.
288 // TODO: C++0x
289 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700290 typedef std::vector<collector::MarkSweep*>::const_iterator It;
291 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800292 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700293 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800294 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800295 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700296 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800297 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700298 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800299 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
300 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
301 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700302 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
303 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
304 << collector->GetName() << " freed: " << freed_objects
305 << " objects with total size " << PrettySize(freed_bytes) << "\n"
306 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
307 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800308 total_duration += total_ns;
309 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700310 }
311 }
312 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700313 size_t total_objects_allocated = GetObjectsAllocatedEver();
314 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700315 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700316 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700317 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
318 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700319 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700320 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700321 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700322 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700323 os << "Total number of allocations: " << total_objects_allocated << "\n";
324 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700325 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700326 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
327 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
328 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700329 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700330 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
331 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700332}
333
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800334Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700335 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700336 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700337 }
338
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800339 STLDeleteElements(&mark_sweep_collectors_);
340
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700341 // If we don't reset then the mark stack complains in it's destructor.
342 allocation_stack_->Reset();
343 live_stack_->Reset();
344
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800345 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800346 // We can't take the heap lock here because there might be a daemon thread suspended with the
347 // heap lock held. We know though that no non-daemon threads are executing, and we know that
348 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
349 // 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 -0700350 STLDeleteElements(&continuous_spaces_);
351 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700352 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700353 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700354}
355
Ian Rogers1d54e732013-05-02 21:10:01 -0700356space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
357 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700358 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700359 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
360 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700361 if ((*it)->Contains(obj)) {
362 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700363 }
364 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700365 if (!fail_ok) {
366 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
367 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700368 return NULL;
369}
370
Ian Rogers1d54e732013-05-02 21:10:01 -0700371space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
372 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700373 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700374 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
375 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
376 if ((*it)->Contains(obj)) {
377 return *it;
378 }
379 }
380 if (!fail_ok) {
381 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
382 }
383 return NULL;
384}
385
386space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
387 space::Space* result = FindContinuousSpaceFromObject(obj, true);
388 if (result != NULL) {
389 return result;
390 }
391 return FindDiscontinuousSpaceFromObject(obj, true);
392}
393
394space::ImageSpace* Heap::GetImageSpace() const {
395 // TODO: C++0x auto
396 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
397 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700398 if ((*it)->IsImageSpace()) {
399 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700400 }
401 }
402 return NULL;
403}
404
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700405static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700406 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700407 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700408 size_t chunk_free_bytes = chunk_size - used_bytes;
409 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
410 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700411 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700412}
413
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800414mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
415 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700416 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
417 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800418 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700419
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800420 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700421 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700422 uint64_t allocation_start = 0;
423 if (measure_allocation_time_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700424 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700425 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700426
427 // We need to have a zygote space or else our newly allocated large object can end up in the
428 // Zygote resulting in it being prematurely freed.
429 // We can only do this for primive objects since large objects will not be within the card table
430 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers22a20862013-03-16 16:34:57 -0700431 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700432 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700433 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700434 // Make sure that our large object didn't get placed anywhere within the space interval or else
435 // it breaks the immune range.
436 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700437 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
438 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700439 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700440 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700441
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700442 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700443 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700444 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700445 }
446
Mathieu Chartier037813d2012-08-23 16:44:59 -0700447 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700449
450 // Record allocation after since we want to use the atomic add for the atomic fence to guard
451 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700452 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700453
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454 if (Dbg::IsAllocTrackingEnabled()) {
455 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700456 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700457 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700458 // We already have a request pending, no reason to start more until we update
459 // concurrent_start_bytes_.
460 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800462 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700463 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 }
465 VerifyObject(obj);
466
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700467 if (measure_allocation_time_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700468 total_allocation_time_ += NanoTime() / kTimeAdjust - allocation_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700469 }
470
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700471 return obj;
472 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800473 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700474 int64_t total_bytes_free = GetFreeMemory();
Ian Rogers1d54e732013-05-02 21:10:01 -0700475 uint64_t alloc_space_size = alloc_space_->GetBytesAllocated();
476 uint64_t large_object_size = large_object_space_->GetObjectsAllocated();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800477 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
478 << " free bytes; allocation space size " << alloc_space_size
479 << "; large object space size " << large_object_size;
480 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
481 if (total_bytes_free >= byte_count) {
482 size_t max_contiguous_allocation = 0;
483 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700484 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
485 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
486 space::ContinuousSpace* space = *it;
487 if (space->IsDlMallocSpace()) {
488 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800489 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700490 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800491 oss << "; failed due to fragmentation (largest possible contiguous allocation "
492 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700493 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800494 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700495 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700496}
497
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800498bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700499 // Note: we deliberately don't take the lock here, and mustn't test anything that would
500 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700501 if (obj == NULL) {
502 return true;
503 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700504 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700505 return false;
506 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700507 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700508}
509
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800510bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700511 //Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
512 if (obj == NULL) {
513 return false;
514 }
515 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
516 return false;
517 }
518 space::ContinuousSpace* cont_space = FindContinuousSpaceFromObject(obj, true);
519 if (cont_space != NULL) {
520 if (cont_space->GetLiveBitmap()->Test(obj)) {
521 return true;
522 }
523 } else {
524 space::DiscontinuousSpace* disc_space = FindDiscontinuousSpaceFromObject(obj, true);
525 if (disc_space != NULL) {
526 if (disc_space->GetLiveObjects()->Test(obj)) {
527 return true;
528 }
529 }
530 }
531 for (size_t i = 0; i < 5; ++i) {
532 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
533 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
534 return true;
535 }
536 NanoSleep(MsToNs(10));
537 }
538 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700539}
540
Ian Rogers04d7aa92013-03-16 14:29:17 -0700541void Heap::VerifyObjectImpl(const mirror::Object* obj) {
542 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700543 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700544 return;
545 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700546 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700547}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700548
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700549void Heap::DumpSpaces() {
550 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700551 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
552 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
553 space::ContinuousSpace* space = *it;
554 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
555 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700556 LOG(INFO) << space << " " << *space << "\n"
557 << live_bitmap << " " << *live_bitmap << "\n"
558 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700559 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700560 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
561 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
562 space::DiscontinuousSpace* space = *it;
563 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700564 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700565}
566
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800567void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800568 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700569 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700570 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800571 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
572 return;
573 }
574 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
575 mirror::Object::ClassOffset().Int32Value();
576 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
577 if (UNLIKELY(c == NULL)) {
578 LOG(FATAL) << "Null class in object: " << obj;
579 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
580 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
581 }
582 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
583 // Note: we don't use the accessors here as they have internal sanity checks
584 // that we don't want to run
585 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
586 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
587 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
588 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
589 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700590
Ian Rogers62d6c772013-02-27 08:32:07 -0800591 if (verify_object_mode_ != kVerifyAllFast) {
592 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
593 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700594 if (!IsLiveObjectLocked(obj)) {
595 DumpSpaces();
596 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700597 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700598 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700599 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
600 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700601 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700602}
603
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800604void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700605 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700606 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700607}
608
609void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700610 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700611 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700612}
613
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800614void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700615 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700616 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700617 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700618
619 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700620 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700621 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700622 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700623
624 // TODO: Update these atomically.
625 RuntimeStats* global_stats = Runtime::Current()->GetStats();
626 ++global_stats->allocated_objects;
627 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700628 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700629
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700630 // This is safe to do since the GC will never free objects which are neither in the allocation
631 // stack or the live bitmap.
632 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700633 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700634 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700635}
636
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700637void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700638 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
639 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700640
641 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700642 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700643 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700644 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700645
646 // TODO: Do this concurrently.
647 RuntimeStats* global_stats = Runtime::Current()->GetStats();
648 global_stats->freed_objects += freed_objects;
649 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700650 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700651}
652
Ian Rogers1d54e732013-05-02 21:10:01 -0700653mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
654 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700655 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800656 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
657 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
658 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
659 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700660 return NULL;
661 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700662 }
663
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700664 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700665}
666
Ian Rogers1d54e732013-05-02 21:10:01 -0700667mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700668 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
669 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700670 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700672
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800673 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700674 if (ptr != NULL) {
675 return ptr;
676 }
677
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700678 // The allocation failed. If the GC is running, block until it completes, and then retry the
679 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700680 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
681 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700682 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700683 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700684 if (ptr != NULL) {
685 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700686 }
687 }
688
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700689 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700690 for (size_t i = static_cast<size_t>(last_gc) + 1;
691 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700692 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700693 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700694 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700695 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700696 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700697 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
698 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700699 break;
700 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700701 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700702 run_gc = have_zygote_space_;
703 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700704 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700705 run_gc = true;
706 break;
707 default:
708 break;
709 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700710
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700711 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700712 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700713 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800714 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700715 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700716
717 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700718 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700719 if (ptr != NULL) {
720 return ptr;
721 }
722 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700723 }
724
725 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700726 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700727 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700728 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700729 return ptr;
730 }
731
Elliott Hughes81ff3182012-03-23 20:35:56 -0700732 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
733 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
734 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700735
Elliott Hughes418dfe72011-10-06 18:56:27 -0700736 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700737 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
738 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700739
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700740 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700741 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700742 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700743}
744
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700745void Heap::SetTargetHeapUtilization(float target) {
746 DCHECK_GT(target, 0.0f); // asserted in Java code
747 DCHECK_LT(target, 1.0f);
748 target_utilization_ = target;
749}
750
Ian Rogers1d54e732013-05-02 21:10:01 -0700751size_t Heap::GetObjectsAllocated() const {
752 size_t total = 0;
753 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
754 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
755 space::ContinuousSpace* space = *it;
756 if (space->IsDlMallocSpace()) {
757 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700758 }
759 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700760 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
761 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
762 space::DiscontinuousSpace* space = *it;
763 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
764 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700765 return total;
766}
767
Ian Rogers1d54e732013-05-02 21:10:01 -0700768size_t Heap::GetObjectsAllocatedEver() const {
769 size_t total = 0;
770 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
771 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
772 space::ContinuousSpace* space = *it;
773 if (space->IsDlMallocSpace()) {
774 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700775 }
776 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700777 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
778 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
779 space::DiscontinuousSpace* space = *it;
780 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
781 }
782 return total;
783}
784
785size_t Heap::GetBytesAllocatedEver() const {
786 size_t total = 0;
787 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
788 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
789 space::ContinuousSpace* space = *it;
790 if (space->IsDlMallocSpace()) {
791 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
792 }
793 }
794 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
795 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
796 space::DiscontinuousSpace* space = *it;
797 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
798 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700799 return total;
800}
801
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700802class InstanceCounter {
803 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800804 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700805 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800806 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700807 }
808
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800809 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800810 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800811 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800812 if (use_is_assignable_from_) {
813 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
814 ++counts_[i];
815 }
816 } else {
817 if (instance_class == classes_[i]) {
818 ++counts_[i];
819 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700820 }
821 }
822 }
823
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700824 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800825 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800826 bool use_is_assignable_from_;
827 uint64_t* const counts_;
828
829 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700830};
831
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800832void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800833 uint64_t* counts) {
834 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
835 // is empty, so the live bitmap is the only place we need to look.
836 Thread* self = Thread::Current();
837 self->TransitionFromRunnableToSuspended(kNative);
838 CollectGarbage(false);
839 self->TransitionFromSuspendedToRunnable();
840
841 InstanceCounter counter(classes, use_is_assignable_from, counts);
842 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700843 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700844}
845
Elliott Hughes3b78c942013-01-15 17:35:41 -0800846class InstanceCollector {
847 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800848 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800849 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
850 : class_(c), max_count_(max_count), instances_(instances) {
851 }
852
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800853 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
854 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800855 if (instance_class == class_) {
856 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800857 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800858 }
859 }
860 }
861
862 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800863 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800864 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800865 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800866
867 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
868};
869
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800870void Heap::GetInstances(mirror::Class* c, int32_t max_count,
871 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800872 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
873 // is empty, so the live bitmap is the only place we need to look.
874 Thread* self = Thread::Current();
875 self->TransitionFromRunnableToSuspended(kNative);
876 CollectGarbage(false);
877 self->TransitionFromSuspendedToRunnable();
878
879 InstanceCollector collector(c, max_count, instances);
880 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
881 GetLiveBitmap()->Visit(collector);
882}
883
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800884class ReferringObjectsFinder {
885 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800886 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
887 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800888 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
889 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
890 }
891
892 // For bitmap Visit.
893 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
894 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800895 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -0700896 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800897 }
898
899 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -0700900 void operator()(const mirror::Object* referrer, const mirror::Object* object,
901 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800902 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800903 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800904 }
905 }
906
907 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800908 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800909 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800910 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800911
912 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
913};
914
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800915void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
916 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800917 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
918 // is empty, so the live bitmap is the only place we need to look.
919 Thread* self = Thread::Current();
920 self->TransitionFromRunnableToSuspended(kNative);
921 CollectGarbage(false);
922 self->TransitionFromSuspendedToRunnable();
923
924 ReferringObjectsFinder finder(o, max_count, referring_objects);
925 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
926 GetLiveBitmap()->Visit(finder);
927}
928
Ian Rogers30fab402012-01-23 15:43:46 -0800929void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700930 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
931 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700932 Thread* self = Thread::Current();
933 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700934 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700935}
936
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700937void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700938 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800939 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
940 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700941 Thread* self = Thread::Current();
942 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700943
944 // Try to see if we have any Zygote spaces.
945 if (have_zygote_space_) {
946 return;
947 }
948
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700949 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
950
951 {
952 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700953 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700954 FlushAllocStack();
955 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700956
Ian Rogers1d54e732013-05-02 21:10:01 -0700957 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
958 // of the remaining available heap memory.
959 space::DlMallocSpace* zygote_space = alloc_space_;
960 alloc_space_ = zygote_space->CreateZygoteSpace();
961 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700962
Ian Rogers1d54e732013-05-02 21:10:01 -0700963 // Change the GC retention policy of the zygote space to only collect when full.
964 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
965 AddContinuousSpace(alloc_space_);
966 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700967
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700968 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700969 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700970 typedef std::vector<collector::MarkSweep*>::const_iterator It;
971 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
972 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800973 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -0700974 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700975}
976
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700977void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700978 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
979 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700980 allocation_stack_->Reset();
981}
982
Ian Rogers1d54e732013-05-02 21:10:01 -0700983void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
984 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800985 mirror::Object** limit = stack->End();
986 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
987 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700988 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700989 if (LIKELY(bitmap->HasAddress(obj))) {
990 bitmap->Set(obj);
991 } else {
992 large_objects->Set(obj);
993 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700994 }
995}
996
Ian Rogers1d54e732013-05-02 21:10:01 -0700997void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
998 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800999 mirror::Object** limit = stack->End();
1000 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1001 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001002 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001003 if (LIKELY(bitmap->HasAddress(obj))) {
1004 bitmap->Clear(obj);
1005 } else {
1006 large_objects->Clear(obj);
1007 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001008 }
1009}
1010
Ian Rogers1d54e732013-05-02 21:10:01 -07001011collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1012 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001013 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001014
1015 switch (gc_cause) {
1016 case kGcCauseForAlloc:
1017 ATRACE_BEGIN("GC (alloc)");
1018 break;
1019 case kGcCauseBackground:
1020 ATRACE_BEGIN("GC (background)");
1021 break;
1022 case kGcCauseExplicit:
1023 ATRACE_BEGIN("GC (explicit)");
1024 break;
1025 }
1026
Mathieu Chartier65db8802012-11-20 12:36:46 -08001027 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001028 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001029
Ian Rogers120f1c72012-09-28 17:17:10 -07001030 if (self->IsHandlingStackOverflow()) {
1031 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1032 }
1033
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001034 // Ensure there is only one GC at a time.
1035 bool start_collect = false;
1036 while (!start_collect) {
1037 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001038 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001039 if (!is_gc_running_) {
1040 is_gc_running_ = true;
1041 start_collect = true;
1042 }
1043 }
1044 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001045 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001046 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1047 // Not doing at the moment to ensure soft references are cleared.
1048 }
1049 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001050 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001051
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001052 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1053 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1054 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1055 }
1056
Ian Rogers1d54e732013-05-02 21:10:01 -07001057 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001058 uint64_t gc_start_size = GetBytesAllocated();
1059 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001060 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001061 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1062 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001063 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001064 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001065 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001066 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1067 }
1068
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001069 if (gc_type == collector::kGcTypeSticky &&
1070 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1071 gc_type = collector::kGcTypePartial;
1072 }
1073
Ian Rogers1d54e732013-05-02 21:10:01 -07001074 DCHECK_LT(gc_type, collector::kGcTypeMax);
1075 DCHECK_NE(gc_type, collector::kGcTypeNone);
1076 collector::MarkSweep* collector = NULL;
1077 typedef std::vector<collector::MarkSweep*>::iterator It;
1078 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1079 it != end; ++it) {
1080 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001081 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1082 collector = cur_collector;
1083 break;
1084 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001085 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001086 CHECK(collector != NULL)
1087 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1088 << " and type=" << gc_type;
1089 collector->clear_soft_references_ = clear_soft_references;
1090 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001091 total_objects_freed_ever_ += collector->GetFreedObjects();
1092 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001093
Ian Rogers1d54e732013-05-02 21:10:01 -07001094 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001095 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1096 bool was_slow = duration > kSlowGcThreshold ||
1097 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1098 for (size_t i = 0; i < pauses.size(); ++i) {
1099 if (pauses[i] > kLongGcPauseThreshold) {
1100 was_slow = true;
1101 }
1102 }
1103
1104 if (was_slow) {
1105 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001106 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001107 const size_t total_memory = GetTotalMemory();
1108 std::ostringstream pause_string;
1109 for (size_t i = 0; i < pauses.size(); ++i) {
1110 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1111 << ((i != pauses.size() - 1) ? ", " : "");
1112 }
1113 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001114 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1115 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1116 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1117 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001118 if (VLOG_IS_ON(heap)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001119 LOG(INFO) << Dumpable<base::NewTimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001120 }
1121 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001122
Ian Rogers15bf2d32012-08-28 17:33:04 -07001123 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001124 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001125 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001126 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001127 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001128 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001129 }
1130 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001131 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001132 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001133 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001134}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001135
Ian Rogers1d54e732013-05-02 21:10:01 -07001136void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::NewTimingLogger& timings,
1137 collector::GcType gc_type) {
1138 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001139 // 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 -07001140 // cards.
1141 return;
1142 }
1143
1144 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001145 if (gc_type == collector::kGcTypePartial) {
1146 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001147 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001148
Ian Rogers1d54e732013-05-02 21:10:01 -07001149 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001150 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001151 }
1152
1153 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001154 timings.NewSplit("UpdateModUnionTable");
1155 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001156
1157 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001158 timings.NewSplit("MarkImageToAllocSpaceReferences");
1159 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001160}
1161
Ian Rogers1d54e732013-05-02 21:10:01 -07001162static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001163 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001164 if (root == obj) {
1165 LOG(INFO) << "Object " << obj << " is a root";
1166 }
1167}
1168
1169class ScanVisitor {
1170 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001171 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001172 LOG(INFO) << "Would have rescanned object " << obj;
1173 }
1174};
1175
Ian Rogers1d54e732013-05-02 21:10:01 -07001176// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001177class VerifyReferenceVisitor {
1178 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001179 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001180 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001181 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001182
1183 bool Failed() const {
1184 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001185 }
1186
1187 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001188 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001189 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1190 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001191 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001192 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001193 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1194 accounting::CardTable* card_table = heap_->GetCardTable();
1195 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1196 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001197
Ian Rogers1d54e732013-05-02 21:10:01 -07001198 if (obj != NULL) {
1199 byte* card_addr = card_table->CardFromAddr(obj);
1200 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1201 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1202 << "\nObj type " << PrettyTypeOf(obj)
1203 << "\nRef type " << PrettyTypeOf(ref);
1204 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1205 void* cover_begin = card_table->AddrFromCard(card_addr);
1206 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1207 accounting::CardTable::kCardSize);
1208 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1209 << "-" << cover_end;
1210 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001211
Ian Rogers1d54e732013-05-02 21:10:01 -07001212 // Print out how the object is live.
1213 if (bitmap != NULL && bitmap->Test(obj)) {
1214 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1215 }
1216 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
1217 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1218 }
1219 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
1220 LOG(ERROR) << "Object " << obj << " found in live stack";
1221 }
1222 // Attempt to see if the card table missed the reference.
1223 ScanVisitor scan_visitor;
1224 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1225 card_table->Scan(bitmap, byte_cover_begin,
1226 byte_cover_begin + accounting::CardTable::kCardSize,
1227 scan_visitor, VoidFunctor());
1228
1229 // Search to see if any of the roots reference our object.
1230 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1231 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1232
1233 // Search to see if any of the roots reference our reference.
1234 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1235 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1236 } else {
1237 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001238 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001239 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1240 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001241 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001242 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001243 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001244 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001245 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1246 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1247 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001248 }
1249 }
1250
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001251 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001252 return heap_->IsLiveObjectLocked(obj);
1253 }
1254
1255 static void VerifyRoots(const mirror::Object* root, void* arg) {
1256 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1257 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001258 }
1259
1260 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001261 Heap* const heap_;
1262 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001263};
1264
Ian Rogers1d54e732013-05-02 21:10:01 -07001265// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001266class VerifyObjectVisitor {
1267 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001268 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001269
Brian Carlstromdf629502013-07-17 22:39:56 -07001270 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001271 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001272 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1273 // be live or else how did we find it in the live bitmap?
1274 VerifyReferenceVisitor visitor(heap_);
1275 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1276 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001277 }
1278
1279 bool Failed() const {
1280 return failed_;
1281 }
1282
1283 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001284 Heap* const heap_;
1285 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001286};
1287
1288// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001289bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001290 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001291 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001292 allocation_stack_->Sort();
1293 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001294 // Perform the verification.
1295 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001296 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001297 GetLiveBitmap()->Visit(visitor);
1298 // We don't want to verify the objects in the allocation stack since they themselves may be
1299 // pointing to dead objects if they are not reachable.
1300 if (visitor.Failed()) {
1301 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001302 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001303 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001304 return true;
1305}
1306
1307class VerifyReferenceCardVisitor {
1308 public:
1309 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1310 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1311 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001312 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001313 }
1314
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001315 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1316 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001317 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1318 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001319 // Filter out class references since changing an object's class does not mark the card as dirty.
1320 // Also handles large objects, since the only reference they hold is a class reference.
1321 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001322 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001323 // If the object is not dirty and it is referencing something in the live stack other than
1324 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001325 if (!card_table->AddrIsInCardTable(obj)) {
1326 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1327 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001328 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001329 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1330 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001331 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
1332 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1333 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001334 LOG(ERROR) << "Object " << obj << " found in live stack";
1335 }
1336 if (heap_->GetLiveBitmap()->Test(obj)) {
1337 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1338 }
1339 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1340 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1341
1342 // Print which field of the object is dead.
1343 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001344 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001345 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001346 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1347 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001348 CHECK(fields != NULL);
1349 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001350 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001351 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1352 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1353 << PrettyField(cur);
1354 break;
1355 }
1356 }
1357 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001358 const mirror::ObjectArray<mirror::Object>* object_array =
1359 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001360 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1361 if (object_array->Get(i) == ref) {
1362 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1363 }
1364 }
1365 }
1366
1367 *failed_ = true;
1368 }
1369 }
1370 }
1371 }
1372
1373 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001374 Heap* const heap_;
1375 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001376};
1377
1378class VerifyLiveStackReferences {
1379 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001380 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001381 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001382 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001383
Brian Carlstromdf629502013-07-17 22:39:56 -07001384 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001385 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1386 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001387 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001388 }
1389
1390 bool Failed() const {
1391 return failed_;
1392 }
1393
1394 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001395 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001396 bool failed_;
1397};
1398
1399bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001400 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001401
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001402 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001403 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001404 VerifyLiveStackReferences visitor(this);
1405 GetLiveBitmap()->Visit(visitor);
1406
1407 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001408 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001409 visitor(*it);
1410 }
1411
1412 if (visitor.Failed()) {
1413 DumpSpaces();
1414 return false;
1415 }
1416 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001417}
1418
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001419void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001420 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001421
1422 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001423 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001424 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001425 }
1426}
1427
Ian Rogers1d54e732013-05-02 21:10:01 -07001428void Heap::ProcessCards(base::NewTimingLogger& timings) {
1429 // Clear cards and keep track of cards cleared in the mod-union table.
1430 typedef std::vector<space::ContinuousSpace*>::iterator It;
1431 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1432 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001433 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001434 timings.NewSplit("ModUnionClearCards");
1435 image_mod_union_table_->ClearCards(space);
1436 } else if (space->IsZygoteSpace()) {
1437 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001438 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001439 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001440 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1441 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001442 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001443 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001444 }
1445 }
1446}
1447
Ian Rogers1d54e732013-05-02 21:10:01 -07001448void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001449 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1450 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001451
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001452 if (verify_pre_gc_heap_) {
1453 thread_list->SuspendAll();
1454 {
1455 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1456 if (!VerifyHeapReferences()) {
1457 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1458 }
1459 }
1460 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001461 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001462
1463 // Check that all objects which reference things in the live stack are on dirty cards.
1464 if (verify_missing_card_marks_) {
1465 thread_list->SuspendAll();
1466 {
1467 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1468 SwapStacks();
1469 // Sort the live stack so that we can quickly binary search it later.
1470 if (!VerifyMissingCardMarks()) {
1471 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1472 }
1473 SwapStacks();
1474 }
1475 thread_list->ResumeAll();
1476 }
1477
1478 if (verify_mod_union_table_) {
1479 thread_list->SuspendAll();
1480 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1481 zygote_mod_union_table_->Update();
1482 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001483 image_mod_union_table_->Update();
1484 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001485 thread_list->ResumeAll();
1486 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001487}
1488
Ian Rogers1d54e732013-05-02 21:10:01 -07001489void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001490 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001491
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001492 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1493 // reachable objects.
1494 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001495 Thread* self = Thread::Current();
1496 CHECK_NE(self->GetState(), kRunnable);
1497 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001498 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001499 {
1500 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1501 // Swapping bound bitmaps does nothing.
1502 gc->SwapBitmaps();
1503 if (!VerifyHeapReferences()) {
1504 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1505 }
1506 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001507 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001508 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001509 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001510 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001511}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001512
Ian Rogers1d54e732013-05-02 21:10:01 -07001513void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001514 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001515
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001516 if (verify_system_weaks_) {
1517 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001518 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001519 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001520 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001521}
1522
Ian Rogers1d54e732013-05-02 21:10:01 -07001523collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1524 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001525 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001526 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001527 bool do_wait;
1528 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001529 {
1530 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001531 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001532 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001533 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001534 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001535 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001536 // We must wait, change thread state then sleep on gc_complete_cond_;
1537 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1538 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001539 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001541 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001542 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001543 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001544 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001545 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001546 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001547 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001548 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1549 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001550 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001551 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001552 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001553 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001554}
1555
Elliott Hughesc967f782012-04-16 10:23:15 -07001556void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001557 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001558 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001559 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001560}
1561
1562size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001563 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001564}
1565
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001566void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001567 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001568 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001569 << PrettySize(GetMaxMemory());
1570 max_allowed_footprint = GetMaxMemory();
1571 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001572 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001573}
1574
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001575void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001576 // We know what our utilization is at this moment.
1577 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001578 const size_t bytes_allocated = GetBytesAllocated();
1579 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001580 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001581
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001582 size_t target_size;
1583 if (gc_type != collector::kGcTypeSticky) {
1584 // Grow the heap for non sticky GC.
1585 target_size = bytes_allocated / GetTargetHeapUtilization();
1586 if (target_size > bytes_allocated + max_free_) {
1587 target_size = bytes_allocated + max_free_;
1588 } else if (target_size < bytes_allocated + min_free_) {
1589 target_size = bytes_allocated + min_free_;
1590 }
1591 next_gc_type_ = collector::kGcTypeSticky;
1592 } else {
1593 // Based on how close the current heap size is to the target size, decide
1594 // whether or not to do a partial or sticky GC next.
1595 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1596 next_gc_type_ = collector::kGcTypeSticky;
1597 } else {
1598 next_gc_type_ = collector::kGcTypePartial;
1599 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001600
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001601 // If we have freed enough memory, shrink the heap back down.
1602 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1603 target_size = bytes_allocated + max_free_;
1604 } else {
1605 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1606 }
1607 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001608 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001609
Ian Rogers1d54e732013-05-02 21:10:01 -07001610 // Calculate when to perform the next ConcurrentGC.
1611 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001612 // Calculate the estimated GC duration.
1613 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1614 // Estimate how many remaining bytes we will have when we need to start the next GC.
1615 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001616 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1617 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1618 // A never going to happen situation that from the estimated allocation rate we will exceed
1619 // the applications entire footprint with the given estimated allocation rate. Schedule
1620 // another GC straight away.
1621 concurrent_start_bytes_ = bytes_allocated;
1622 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001623 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1624 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1625 // right away.
1626 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001627 }
1628 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1629 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1630 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001631}
1632
jeffhaoc1160702011-10-27 15:48:45 -07001633void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001634 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001635 alloc_space_->ClearGrowthLimit();
1636}
1637
Elliott Hughesadb460d2011-10-05 17:02:34 -07001638void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001639 MemberOffset reference_queue_offset,
1640 MemberOffset reference_queueNext_offset,
1641 MemberOffset reference_pendingNext_offset,
1642 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001643 reference_referent_offset_ = reference_referent_offset;
1644 reference_queue_offset_ = reference_queue_offset;
1645 reference_queueNext_offset_ = reference_queueNext_offset;
1646 reference_pendingNext_offset_ = reference_pendingNext_offset;
1647 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1648 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1649 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1650 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1651 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1652 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1653}
1654
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001655mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001656 DCHECK(reference != NULL);
1657 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001658 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001659}
1660
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001661void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001662 DCHECK(reference != NULL);
1663 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1664 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1665}
1666
1667// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001668bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001669 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001670 const mirror::Object* queue =
1671 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1672 const mirror::Object* queue_next =
1673 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001674 return (queue != NULL) && (queue_next == NULL);
1675}
1676
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001677void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001678 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001679 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1680 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001681 EnqueuePendingReference(ref, cleared_reference_list);
1682}
1683
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001684void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001685 DCHECK(ref != NULL);
1686 DCHECK(list != NULL);
1687
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001688 // TODO: Remove this lock, use atomic stacks for storing references.
1689 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001690 if (*list == NULL) {
1691 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1692 *list = ref;
1693 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001694 mirror::Object* head =
1695 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001696 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1697 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1698 }
1699}
1700
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001701mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001702 DCHECK(list != NULL);
1703 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001704 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1705 false);
1706 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001707
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001708 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1709 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001710 if (*list == head) {
1711 ref = *list;
1712 *list = NULL;
1713 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001714 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1715 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001716 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1717 ref = head;
1718 }
1719 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1720 return ref;
1721}
1722
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001723void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001724 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001725 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001726 ArgArray arg_array(NULL, 0);
1727 arg_array.Append(reinterpret_cast<uint32_t>(object));
1728 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001729 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001730}
1731
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001732void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001733 DCHECK(cleared != NULL);
1734 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001735 // When a runtime isn't started there are no reference queues to care about so ignore.
1736 if (LIKELY(Runtime::Current()->IsStarted())) {
1737 ScopedObjectAccess soa(Thread::Current());
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>(*cleared));
1741 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001742 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001743 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001744 *cleared = NULL;
1745 }
1746}
1747
Ian Rogers1f539342012-10-03 21:09:42 -07001748void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001749 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001750 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001751 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001752 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001753 !runtime->IsConcurrentGcEnabled()) {
1754 return;
1755 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001756 {
1757 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1758 if (runtime->IsShuttingDown()) {
1759 return;
1760 }
1761 }
1762 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001763 return;
1764 }
1765
Ian Rogers120f1c72012-09-28 17:17:10 -07001766 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001767 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1768 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001769 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1770 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001771 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001772}
1773
Ian Rogers81d425b2012-09-27 16:03:43 -07001774void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001775 {
1776 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001777 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001778 return;
1779 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001780 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001781
Mathieu Chartier65db8802012-11-20 12:36:46 -08001782 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001783 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001784 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001785 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001786}
1787
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001788void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001789 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1790 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1791 // a space it will hold its lock and can become a cause of jank.
1792 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1793 // forking.
1794
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001795 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1796 // because that only marks object heads, so a large array looks like lots of empty space. We
1797 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1798 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1799 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1800 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001801 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001802 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001803 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1804 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001805 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1806 // heap trim occurred in the last two seconds.
1807 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001808 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001809
1810 Thread* self = Thread::Current();
1811 {
1812 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1813 Runtime* runtime = Runtime::Current();
1814 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1815 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1816 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1817 // as we don't hold the lock while requesting the trim).
1818 return;
1819 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001820 }
Ian Rogers48931882013-01-22 14:35:16 -08001821
1822 SchedPolicy policy;
1823 get_sched_policy(self->GetTid(), &policy);
1824 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1825 // Don't trim the heap if we are a foreground or audio app.
1826 return;
1827 }
1828
Ian Rogers1d54e732013-05-02 21:10:01 -07001829 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001830 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001831 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1832 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001833 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1834 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001835 CHECK(!env->ExceptionCheck());
1836}
1837
Ian Rogers48931882013-01-22 14:35:16 -08001838size_t Heap::Trim() {
1839 // Handle a requested heap trim on a thread outside of the main GC thread.
1840 return alloc_space_->Trim();
1841}
1842
Ian Rogers1d54e732013-05-02 21:10:01 -07001843} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001844} // namespace art