blob: deb1b8c3e5570278233e80488d892331b9246283 [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);
Ian Rogers1d54e732013-05-02 21:10:01 -070060// When to create a log message about a slow 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,
Ian Rogers00f7d0e2012-07-19 15:28:27 -070069 const std::string& original_image_file_name, bool concurrent_gc)
70 : 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),
73 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070074 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080075 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070076 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070077 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080078 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070079 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070080 max_allowed_footprint_(initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -070081 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
82 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -070083 total_bytes_freed_ever_(0),
84 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070085 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080086 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -070087 verify_missing_card_marks_(false),
88 verify_system_weaks_(false),
89 verify_pre_gc_heap_(false),
90 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -070091 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070092 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -070093 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -070094 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -080095 allocation_rate_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -070096 max_allocation_stack_size_(kDesiredHeapVerification > kNoHeapVerification? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080097 reference_referent_offset_(0),
98 reference_queue_offset_(0),
99 reference_queueNext_offset_(0),
100 reference_pendingNext_offset_(0),
101 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700102 min_free_(min_free),
103 max_free_(max_free),
104 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700105 total_wait_time_(0),
106 measure_allocation_time_(false),
107 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700108 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800109 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800110 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700111 }
112
Ian Rogers1d54e732013-05-02 21:10:01 -0700113 live_bitmap_.reset(new accounting::HeapBitmap(this));
114 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700115
Ian Rogers30fab402012-01-23 15:43:46 -0800116 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700117 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800118 std::string image_file_name(original_image_file_name);
119 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700120 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
121 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700122 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800123 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
124 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800125 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
126 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700127 if (oat_file_end_addr > requested_alloc_space_begin) {
128 requested_alloc_space_begin =
129 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
130 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700131 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700132 }
133
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700134 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700135 const bool kUseFreeListSpaceForLOS = false;
136 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700137 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700138 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700139 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700140 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700141 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
142 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700143
Ian Rogers1d54e732013-05-02 21:10:01 -0700144 alloc_space_ = space::DlMallocSpace::Create("alloc space",
145 initial_size,
146 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700147 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700148 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700149 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700150 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700151
Ian Rogers1d54e732013-05-02 21:10:01 -0700152 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
153 byte* heap_begin = continuous_spaces_.front()->Begin();
154 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
155 if (continuous_spaces_.back()->IsDlMallocSpace()) {
156 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700157 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700158
Ian Rogers30fab402012-01-23 15:43:46 -0800159 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700160 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700161 typedef std::vector<space::ContinuousSpace*>::iterator It;
162 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
163 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800164 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700165 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700166 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800167 }
168 }
169
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800170 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700171 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700172 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700173
Ian Rogers1d54e732013-05-02 21:10:01 -0700174 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
175 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700176
Ian Rogers1d54e732013-05-02 21:10:01 -0700177 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700178 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700179
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700180 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700181 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700182
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800183 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700184 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700185 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
186 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
187 max_allocation_stack_size_));
188 live_stack_.reset(accounting::ObjectStack::Create("live stack",
189 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700190
Mathieu Chartier65db8802012-11-20 12:36:46 -0800191 // It's still too early to take a lock because there are no threads yet, but we can create locks
192 // now. We don't create it earlier to make it clear that you can't use locks during heap
193 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700194 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700195 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
196 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700197
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700198 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700199 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700200
Ian Rogers1d54e732013-05-02 21:10:01 -0700201 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800202 last_gc_size_ = GetBytesAllocated();
203
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800204 // Create our garbage collectors.
205 for (size_t i = 0; i < 2; ++i) {
206 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700207 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
208 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
209 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700210 }
211
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800212 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800213 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800214 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700215 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700216}
217
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700218void Heap::CreateThreadPool() {
219 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
220 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
221 // workers to complete.
Ian Rogers1d54e732013-05-02 21:10:01 -0700222 thread_pool_.reset(new ThreadPool(1)); // new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700223}
224
225void Heap::DeleteThreadPool() {
226 thread_pool_.reset(NULL);
227}
228
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700229// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700230struct ContinuousSpaceSorter {
231 bool operator ()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700232 return a->Begin() < b->Begin();
233 }
234};
235
Ian Rogers1d54e732013-05-02 21:10:01 -0700236void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700237 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700238 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700239 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700240 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700241 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700242 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
243 continuous_spaces_.push_back(space);
244 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
245 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700246 }
247
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700248 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700249 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700250
251 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
252 // avoid redundant marking.
253 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700254 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
255 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
256 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700257 if (space->IsImageSpace()) {
258 DCHECK(!seen_zygote);
259 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700260 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700261 DCHECK(!seen_alloc);
262 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700263 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700264 seen_alloc = true;
265 }
266 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800267}
268
Ian Rogers1d54e732013-05-02 21:10:01 -0700269void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
270 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
271 DCHECK(space != NULL);
272 DCHECK(space->GetLiveObjects() != NULL);
273 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
274 DCHECK(space->GetMarkObjects() != NULL);
275 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
276 discontinuous_spaces_.push_back(space);
277}
278
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700279void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700280 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700281 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700282 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800283
284 // Dump cumulative loggers for each GC type.
285 // TODO: C++0x
286 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700287 typedef std::vector<collector::MarkSweep*>::const_iterator It;
288 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800289 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700290 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800291 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800292 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700293 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800294 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700295 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800296 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
297 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
298 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700299 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
300 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
301 << collector->GetName() << " freed: " << freed_objects
302 << " objects with total size " << PrettySize(freed_bytes) << "\n"
303 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
304 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800305 total_duration += total_ns;
306 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700307 }
308 }
309 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700310 size_t total_objects_allocated = GetObjectsAllocatedEver();
311 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700312 if (total_duration != 0) {
313 const double total_seconds = double(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700314 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
315 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700316 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700317 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700318 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700319 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700320 os << "Total number of allocations: " << total_objects_allocated << "\n";
321 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700322 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700323 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
324 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
325 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700326 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700327 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
328 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700329}
330
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800331Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700332 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700333 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700334 }
335
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800336 STLDeleteElements(&mark_sweep_collectors_);
337
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700338 // If we don't reset then the mark stack complains in it's destructor.
339 allocation_stack_->Reset();
340 live_stack_->Reset();
341
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800342 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800343 // We can't take the heap lock here because there might be a daemon thread suspended with the
344 // heap lock held. We know though that no non-daemon threads are executing, and we know that
345 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
346 // 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 -0700347 STLDeleteElements(&continuous_spaces_);
348 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700349 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700350 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700351}
352
Ian Rogers1d54e732013-05-02 21:10:01 -0700353space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
354 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700355 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700356 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
357 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700358 if ((*it)->Contains(obj)) {
359 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700360 }
361 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700362 if (!fail_ok) {
363 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
364 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700365 return NULL;
366}
367
Ian Rogers1d54e732013-05-02 21:10:01 -0700368space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
369 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700370 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700371 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
372 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
373 if ((*it)->Contains(obj)) {
374 return *it;
375 }
376 }
377 if (!fail_ok) {
378 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
379 }
380 return NULL;
381}
382
383space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
384 space::Space* result = FindContinuousSpaceFromObject(obj, true);
385 if (result != NULL) {
386 return result;
387 }
388 return FindDiscontinuousSpaceFromObject(obj, true);
389}
390
391space::ImageSpace* Heap::GetImageSpace() const {
392 // TODO: C++0x auto
393 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
394 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700395 if ((*it)->IsImageSpace()) {
396 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700397 }
398 }
399 return NULL;
400}
401
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700402static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700403 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700404 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700405 size_t chunk_free_bytes = chunk_size - used_bytes;
406 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
407 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700408 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700409}
410
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800411mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
412 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700413 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
414 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800415 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700416
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800417 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700418 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700419 uint64_t allocation_start = 0;
420 if (measure_allocation_time_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700421 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700422 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700423
424 // We need to have a zygote space or else our newly allocated large object can end up in the
425 // Zygote resulting in it being prematurely freed.
426 // We can only do this for primive objects since large objects will not be within the card table
427 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers22a20862013-03-16 16:34:57 -0700428 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700429 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700430 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700431 // Make sure that our large object didn't get placed anywhere within the space interval or else
432 // it breaks the immune range.
433 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700434 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
435 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700436 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700437 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700438
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700439 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700440 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700441 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700442 }
443
Mathieu Chartier037813d2012-08-23 16:44:59 -0700444 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700445 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700446
447 // Record allocation after since we want to use the atomic add for the atomic fence to guard
448 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700449 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700450
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700451 if (Dbg::IsAllocTrackingEnabled()) {
452 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700453 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700454 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700455 // We already have a request pending, no reason to start more until we update
456 // concurrent_start_bytes_.
457 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700458 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800459 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700460 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 }
462 VerifyObject(obj);
463
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700464 if (measure_allocation_time_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700465 total_allocation_time_ += NanoTime() / kTimeAdjust - allocation_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700466 }
467
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468 return obj;
469 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800470 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700471 int64_t total_bytes_free = GetFreeMemory();
Ian Rogers1d54e732013-05-02 21:10:01 -0700472 uint64_t alloc_space_size = alloc_space_->GetBytesAllocated();
473 uint64_t large_object_size = large_object_space_->GetObjectsAllocated();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800474 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
475 << " free bytes; allocation space size " << alloc_space_size
476 << "; large object space size " << large_object_size;
477 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
478 if (total_bytes_free >= byte_count) {
479 size_t max_contiguous_allocation = 0;
480 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700481 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
482 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
483 space::ContinuousSpace* space = *it;
484 if (space->IsDlMallocSpace()) {
485 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800486 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700487 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800488 oss << "; failed due to fragmentation (largest possible contiguous allocation "
489 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700490 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800491 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700492 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700493}
494
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800495bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700496 // Note: we deliberately don't take the lock here, and mustn't test anything that would
497 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700498 if (obj == NULL) {
499 return true;
500 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700501 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700502 return false;
503 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700504 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700505}
506
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800507bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700508 //Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
509 if (obj == NULL) {
510 return false;
511 }
512 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
513 return false;
514 }
515 space::ContinuousSpace* cont_space = FindContinuousSpaceFromObject(obj, true);
516 if (cont_space != NULL) {
517 if (cont_space->GetLiveBitmap()->Test(obj)) {
518 return true;
519 }
520 } else {
521 space::DiscontinuousSpace* disc_space = FindDiscontinuousSpaceFromObject(obj, true);
522 if (disc_space != NULL) {
523 if (disc_space->GetLiveObjects()->Test(obj)) {
524 return true;
525 }
526 }
527 }
528 for (size_t i = 0; i < 5; ++i) {
529 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
530 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
531 return true;
532 }
533 NanoSleep(MsToNs(10));
534 }
535 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700536}
537
Ian Rogers04d7aa92013-03-16 14:29:17 -0700538void Heap::VerifyObjectImpl(const mirror::Object* obj) {
539 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700540 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700541 return;
542 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700543 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700544}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700545
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700546void Heap::DumpSpaces() {
547 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700548 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
549 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
550 space::ContinuousSpace* space = *it;
551 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
552 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700553 LOG(INFO) << space << " " << *space << "\n"
554 << live_bitmap << " " << *live_bitmap << "\n"
555 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700556 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700557 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
558 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
559 space::DiscontinuousSpace* space = *it;
560 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700561 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700562}
563
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800564void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800565 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700566 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700567 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800568 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
569 return;
570 }
571 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
572 mirror::Object::ClassOffset().Int32Value();
573 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
574 if (UNLIKELY(c == NULL)) {
575 LOG(FATAL) << "Null class in object: " << obj;
576 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
577 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
578 }
579 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
580 // Note: we don't use the accessors here as they have internal sanity checks
581 // that we don't want to run
582 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
583 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
584 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
585 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
586 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700587
Ian Rogers62d6c772013-02-27 08:32:07 -0800588 if (verify_object_mode_ != kVerifyAllFast) {
589 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
590 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700591 if (!IsLiveObjectLocked(obj)) {
592 DumpSpaces();
593 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700594 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700595 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700596 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
597 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700598 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700599}
600
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800601void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700602 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700603 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700604}
605
606void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700607 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700608 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700609}
610
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800611void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700612 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700613 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700614 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700615
616 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700617 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700618 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700619 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700620
621 // TODO: Update these atomically.
622 RuntimeStats* global_stats = Runtime::Current()->GetStats();
623 ++global_stats->allocated_objects;
624 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700625 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700626
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700627 // This is safe to do since the GC will never free objects which are neither in the allocation
628 // stack or the live bitmap.
629 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700630 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700631 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700632}
633
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700634void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700635 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
636 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700637
638 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700639 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700640 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700641 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700642
643 // TODO: Do this concurrently.
644 RuntimeStats* global_stats = Runtime::Current()->GetStats();
645 global_stats->freed_objects += freed_objects;
646 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700647 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700648}
649
Ian Rogers1d54e732013-05-02 21:10:01 -0700650mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
651 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700652 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800653 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
654 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
655 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
656 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700657 return NULL;
658 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700659 }
660
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700661 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700662}
663
Ian Rogers1d54e732013-05-02 21:10:01 -0700664mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700665 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
666 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700667 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700668 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700669
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800670 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700671 if (ptr != NULL) {
672 return ptr;
673 }
674
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700675 // The allocation failed. If the GC is running, block until it completes, and then retry the
676 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700677 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
678 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700679 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700680 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700681 if (ptr != NULL) {
682 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700683 }
684 }
685
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700686 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700687 for (size_t i = static_cast<size_t>(last_gc) + 1;
688 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700689 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700690 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700691 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700692 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700693 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700694 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
695 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700696 break;
697 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700698 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700699 run_gc = have_zygote_space_;
700 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700701 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700702 run_gc = true;
703 break;
704 default:
705 break;
706 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700707
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700708 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700709 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700710 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800711 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700712 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700713
714 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700715 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700716 if (ptr != NULL) {
717 return ptr;
718 }
719 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700720 }
721
722 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700723 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700724 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700725 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700726 return ptr;
727 }
728
Elliott Hughes81ff3182012-03-23 20:35:56 -0700729 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
730 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
731 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700732
Elliott Hughes418dfe72011-10-06 18:56:27 -0700733 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700734 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
735 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700736
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700737 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700738 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700739 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700740}
741
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700742void Heap::SetTargetHeapUtilization(float target) {
743 DCHECK_GT(target, 0.0f); // asserted in Java code
744 DCHECK_LT(target, 1.0f);
745 target_utilization_ = target;
746}
747
Ian Rogers1d54e732013-05-02 21:10:01 -0700748size_t Heap::GetObjectsAllocated() const {
749 size_t total = 0;
750 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
751 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
752 space::ContinuousSpace* space = *it;
753 if (space->IsDlMallocSpace()) {
754 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700755 }
756 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700757 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
758 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
759 space::DiscontinuousSpace* space = *it;
760 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
761 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700762 return total;
763}
764
Ian Rogers1d54e732013-05-02 21:10:01 -0700765size_t Heap::GetObjectsAllocatedEver() const {
766 size_t total = 0;
767 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
768 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
769 space::ContinuousSpace* space = *it;
770 if (space->IsDlMallocSpace()) {
771 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700772 }
773 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700774 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
775 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
776 space::DiscontinuousSpace* space = *it;
777 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
778 }
779 return total;
780}
781
782size_t Heap::GetBytesAllocatedEver() const {
783 size_t total = 0;
784 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
785 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
786 space::ContinuousSpace* space = *it;
787 if (space->IsDlMallocSpace()) {
788 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
789 }
790 }
791 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
792 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
793 space::DiscontinuousSpace* space = *it;
794 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
795 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700796 return total;
797}
798
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700799class InstanceCounter {
800 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800801 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700802 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800803 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700804 }
805
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800806 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800807 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800808 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800809 if (use_is_assignable_from_) {
810 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
811 ++counts_[i];
812 }
813 } else {
814 if (instance_class == classes_[i]) {
815 ++counts_[i];
816 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700817 }
818 }
819 }
820
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700821 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800822 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800823 bool use_is_assignable_from_;
824 uint64_t* const counts_;
825
826 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700827};
828
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800829void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800830 uint64_t* counts) {
831 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
832 // is empty, so the live bitmap is the only place we need to look.
833 Thread* self = Thread::Current();
834 self->TransitionFromRunnableToSuspended(kNative);
835 CollectGarbage(false);
836 self->TransitionFromSuspendedToRunnable();
837
838 InstanceCounter counter(classes, use_is_assignable_from, counts);
839 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700840 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700841}
842
Elliott Hughes3b78c942013-01-15 17:35:41 -0800843class InstanceCollector {
844 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800845 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800846 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
847 : class_(c), max_count_(max_count), instances_(instances) {
848 }
849
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800850 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
851 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800852 if (instance_class == class_) {
853 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800854 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800855 }
856 }
857 }
858
859 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800860 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800861 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800862 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800863
864 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
865};
866
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800867void Heap::GetInstances(mirror::Class* c, int32_t max_count,
868 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800869 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
870 // is empty, so the live bitmap is the only place we need to look.
871 Thread* self = Thread::Current();
872 self->TransitionFromRunnableToSuspended(kNative);
873 CollectGarbage(false);
874 self->TransitionFromSuspendedToRunnable();
875
876 InstanceCollector collector(c, max_count, instances);
877 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
878 GetLiveBitmap()->Visit(collector);
879}
880
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800881class ReferringObjectsFinder {
882 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800883 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
884 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800885 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
886 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
887 }
888
889 // For bitmap Visit.
890 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
891 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800892 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -0700893 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800894 }
895
896 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800897 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
898 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800899 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800900 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800901 }
902 }
903
904 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800905 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800906 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800907 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800908
909 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
910};
911
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800912void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
913 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800914 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
915 // is empty, so the live bitmap is the only place we need to look.
916 Thread* self = Thread::Current();
917 self->TransitionFromRunnableToSuspended(kNative);
918 CollectGarbage(false);
919 self->TransitionFromSuspendedToRunnable();
920
921 ReferringObjectsFinder finder(o, max_count, referring_objects);
922 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
923 GetLiveBitmap()->Visit(finder);
924}
925
Ian Rogers30fab402012-01-23 15:43:46 -0800926void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700927 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
928 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700929 Thread* self = Thread::Current();
930 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700931 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700932}
933
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700934void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700935 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800936 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
937 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700938 Thread* self = Thread::Current();
939 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700940
941 // Try to see if we have any Zygote spaces.
942 if (have_zygote_space_) {
943 return;
944 }
945
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700946 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
947
948 {
949 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700950 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700951 FlushAllocStack();
952 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700953
Ian Rogers1d54e732013-05-02 21:10:01 -0700954 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
955 // of the remaining available heap memory.
956 space::DlMallocSpace* zygote_space = alloc_space_;
957 alloc_space_ = zygote_space->CreateZygoteSpace();
958 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700959
Ian Rogers1d54e732013-05-02 21:10:01 -0700960 // Change the GC retention policy of the zygote space to only collect when full.
961 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
962 AddContinuousSpace(alloc_space_);
963 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700964
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700965 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700966 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700967 typedef std::vector<collector::MarkSweep*>::const_iterator It;
968 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
969 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800970 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -0700971 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700972}
973
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700974void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700975 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
976 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700977 allocation_stack_->Reset();
978}
979
Ian Rogers1d54e732013-05-02 21:10:01 -0700980void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
981 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800982 mirror::Object** limit = stack->End();
983 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
984 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700985 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700986 if (LIKELY(bitmap->HasAddress(obj))) {
987 bitmap->Set(obj);
988 } else {
989 large_objects->Set(obj);
990 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700991 }
992}
993
Ian Rogers1d54e732013-05-02 21:10:01 -0700994void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
995 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800996 mirror::Object** limit = stack->End();
997 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
998 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700999 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001000 if (LIKELY(bitmap->HasAddress(obj))) {
1001 bitmap->Clear(obj);
1002 } else {
1003 large_objects->Clear(obj);
1004 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001005 }
1006}
1007
Ian Rogers1d54e732013-05-02 21:10:01 -07001008collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1009 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001010 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001011
1012 switch (gc_cause) {
1013 case kGcCauseForAlloc:
1014 ATRACE_BEGIN("GC (alloc)");
1015 break;
1016 case kGcCauseBackground:
1017 ATRACE_BEGIN("GC (background)");
1018 break;
1019 case kGcCauseExplicit:
1020 ATRACE_BEGIN("GC (explicit)");
1021 break;
1022 }
1023
Mathieu Chartier65db8802012-11-20 12:36:46 -08001024 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001025 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001026
Ian Rogers120f1c72012-09-28 17:17:10 -07001027 if (self->IsHandlingStackOverflow()) {
1028 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1029 }
1030
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001031 // Ensure there is only one GC at a time.
1032 bool start_collect = false;
1033 while (!start_collect) {
1034 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001035 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001036 if (!is_gc_running_) {
1037 is_gc_running_ = true;
1038 start_collect = true;
1039 }
1040 }
1041 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001042 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001043 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1044 // Not doing at the moment to ensure soft references are cleared.
1045 }
1046 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001047 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001048
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001049 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1050 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1051 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1052 }
1053
Ian Rogers1d54e732013-05-02 21:10:01 -07001054 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001055 uint64_t gc_start_size = GetBytesAllocated();
1056 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001057 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001058 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1059 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001060 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001061 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001062 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001063 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1064 }
1065
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001066 if (gc_type == collector::kGcTypeSticky &&
1067 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1068 gc_type = collector::kGcTypePartial;
1069 }
1070
Ian Rogers1d54e732013-05-02 21:10:01 -07001071 DCHECK_LT(gc_type, collector::kGcTypeMax);
1072 DCHECK_NE(gc_type, collector::kGcTypeNone);
1073 collector::MarkSweep* collector = NULL;
1074 typedef std::vector<collector::MarkSweep*>::iterator It;
1075 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1076 it != end; ++it) {
1077 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001078 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1079 collector = cur_collector;
1080 break;
1081 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001082 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001083 CHECK(collector != NULL)
1084 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1085 << " and type=" << gc_type;
1086 collector->clear_soft_references_ = clear_soft_references;
1087 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001088 total_objects_freed_ever_ += collector->GetFreedObjects();
1089 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001090
Ian Rogers1d54e732013-05-02 21:10:01 -07001091 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001092 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1093 bool was_slow = duration > kSlowGcThreshold ||
1094 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1095 for (size_t i = 0; i < pauses.size(); ++i) {
1096 if (pauses[i] > kLongGcPauseThreshold) {
1097 was_slow = true;
1098 }
1099 }
1100
1101 if (was_slow) {
1102 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001103 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001104 const size_t total_memory = GetTotalMemory();
1105 std::ostringstream pause_string;
1106 for (size_t i = 0; i < pauses.size(); ++i) {
1107 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1108 << ((i != pauses.size() - 1) ? ", " : "");
1109 }
1110 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001111 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1112 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1113 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1114 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001115 if (VLOG_IS_ON(heap)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001116 LOG(INFO) << Dumpable<base::NewTimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001117 }
1118 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001119
Ian Rogers15bf2d32012-08-28 17:33:04 -07001120 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001121 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001122 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001123 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001124 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001125 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001126 }
1127 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001128 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001129 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001130 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001131}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001132
Ian Rogers1d54e732013-05-02 21:10:01 -07001133void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::NewTimingLogger& timings,
1134 collector::GcType gc_type) {
1135 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001136 // 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 -07001137 // cards.
1138 return;
1139 }
1140
1141 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001142 if (gc_type == collector::kGcTypePartial) {
1143 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001144 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001145
Ian Rogers1d54e732013-05-02 21:10:01 -07001146 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001147 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001148 }
1149
1150 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001151 timings.NewSplit("UpdateModUnionTable");
1152 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001153
1154 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001155 timings.NewSplit("MarkImageToAllocSpaceReferences");
1156 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001157}
1158
Ian Rogers1d54e732013-05-02 21:10:01 -07001159static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001160 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001161 if (root == obj) {
1162 LOG(INFO) << "Object " << obj << " is a root";
1163 }
1164}
1165
1166class ScanVisitor {
1167 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001168 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001169 LOG(INFO) << "Would have rescanned object " << obj;
1170 }
1171};
1172
Ian Rogers1d54e732013-05-02 21:10:01 -07001173// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001174class VerifyReferenceVisitor {
1175 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001176 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001177 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001178 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001179
1180 bool Failed() const {
1181 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001182 }
1183
1184 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001185 // analysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001186 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
Ian Rogers1d54e732013-05-02 21:10:01 -07001187 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001188 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001189 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001190 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1191 accounting::CardTable* card_table = heap_->GetCardTable();
1192 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1193 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001194
Ian Rogers1d54e732013-05-02 21:10:01 -07001195 if (obj != NULL) {
1196 byte* card_addr = card_table->CardFromAddr(obj);
1197 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1198 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1199 << "\nObj type " << PrettyTypeOf(obj)
1200 << "\nRef type " << PrettyTypeOf(ref);
1201 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1202 void* cover_begin = card_table->AddrFromCard(card_addr);
1203 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1204 accounting::CardTable::kCardSize);
1205 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1206 << "-" << cover_end;
1207 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001208
Ian Rogers1d54e732013-05-02 21:10:01 -07001209 // Print out how the object is live.
1210 if (bitmap != NULL && bitmap->Test(obj)) {
1211 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1212 }
1213 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
1214 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1215 }
1216 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
1217 LOG(ERROR) << "Object " << obj << " found in live stack";
1218 }
1219 // Attempt to see if the card table missed the reference.
1220 ScanVisitor scan_visitor;
1221 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1222 card_table->Scan(bitmap, byte_cover_begin,
1223 byte_cover_begin + accounting::CardTable::kCardSize,
1224 scan_visitor, VoidFunctor());
1225
1226 // Search to see if any of the roots reference our object.
1227 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1228 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1229
1230 // Search to see if any of the roots reference our reference.
1231 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1232 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1233 } else {
1234 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001235 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001236 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1237 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001238 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001239 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001240 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001241 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001242 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1243 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1244 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001245 }
1246 }
1247
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001248 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001249 return heap_->IsLiveObjectLocked(obj);
1250 }
1251
1252 static void VerifyRoots(const mirror::Object* root, void* arg) {
1253 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1254 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001255 }
1256
1257 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001258 Heap* const heap_;
1259 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001260};
1261
Ian Rogers1d54e732013-05-02 21:10:01 -07001262// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001263class VerifyObjectVisitor {
1264 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001265 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001266
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001267 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001268 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001269 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1270 // be live or else how did we find it in the live bitmap?
1271 VerifyReferenceVisitor visitor(heap_);
1272 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1273 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001274 }
1275
1276 bool Failed() const {
1277 return failed_;
1278 }
1279
1280 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001281 Heap* const heap_;
1282 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001283};
1284
1285// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001286bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001287 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001288 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001289 allocation_stack_->Sort();
1290 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001291 // Perform the verification.
1292 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001293 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001294 GetLiveBitmap()->Visit(visitor);
1295 // We don't want to verify the objects in the allocation stack since they themselves may be
1296 // pointing to dead objects if they are not reachable.
1297 if (visitor.Failed()) {
1298 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001299 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001300 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001301 return true;
1302}
1303
1304class VerifyReferenceCardVisitor {
1305 public:
1306 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1307 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1308 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001309 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001310 }
1311
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001312 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1313 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001314 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1315 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001316 // Filter out class references since changing an object's class does not mark the card as dirty.
1317 // Also handles large objects, since the only reference they hold is a class reference.
1318 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001319 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001320 // If the object is not dirty and it is referencing something in the live stack other than
1321 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001322 if (!card_table->AddrIsInCardTable(obj)) {
1323 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1324 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001325 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001326 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1327 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001328 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
1329 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1330 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001331 LOG(ERROR) << "Object " << obj << " found in live stack";
1332 }
1333 if (heap_->GetLiveBitmap()->Test(obj)) {
1334 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1335 }
1336 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1337 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1338
1339 // Print which field of the object is dead.
1340 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001341 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001342 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001343 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1344 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001345 CHECK(fields != NULL);
1346 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001347 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001348 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1349 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1350 << PrettyField(cur);
1351 break;
1352 }
1353 }
1354 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001355 const mirror::ObjectArray<mirror::Object>* object_array =
1356 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001357 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1358 if (object_array->Get(i) == ref) {
1359 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1360 }
1361 }
1362 }
1363
1364 *failed_ = true;
1365 }
1366 }
1367 }
1368 }
1369
1370 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001371 Heap* const heap_;
1372 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001373};
1374
1375class VerifyLiveStackReferences {
1376 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001377 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001378 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001379 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001380
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001381 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001382 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1383 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001384 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001385 }
1386
1387 bool Failed() const {
1388 return failed_;
1389 }
1390
1391 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001392 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001393 bool failed_;
1394};
1395
1396bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001397 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001398
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001399 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001400 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001401 VerifyLiveStackReferences visitor(this);
1402 GetLiveBitmap()->Visit(visitor);
1403
1404 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001405 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001406 visitor(*it);
1407 }
1408
1409 if (visitor.Failed()) {
1410 DumpSpaces();
1411 return false;
1412 }
1413 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001414}
1415
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001416void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001417 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001418
1419 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001420 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001421 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001422 }
1423}
1424
Ian Rogers1d54e732013-05-02 21:10:01 -07001425void Heap::ProcessCards(base::NewTimingLogger& timings) {
1426 // Clear cards and keep track of cards cleared in the mod-union table.
1427 typedef std::vector<space::ContinuousSpace*>::iterator It;
1428 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1429 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001430 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001431 timings.NewSplit("ModUnionClearCards");
1432 image_mod_union_table_->ClearCards(space);
1433 } else if (space->IsZygoteSpace()) {
1434 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001435 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001436 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001437 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1438 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001439 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001440 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001441 }
1442 }
1443}
1444
Ian Rogers1d54e732013-05-02 21:10:01 -07001445void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001446 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1447 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001448
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001449 if (verify_pre_gc_heap_) {
1450 thread_list->SuspendAll();
1451 {
1452 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1453 if (!VerifyHeapReferences()) {
1454 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1455 }
1456 }
1457 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001458 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001459
1460 // Check that all objects which reference things in the live stack are on dirty cards.
1461 if (verify_missing_card_marks_) {
1462 thread_list->SuspendAll();
1463 {
1464 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1465 SwapStacks();
1466 // Sort the live stack so that we can quickly binary search it later.
1467 if (!VerifyMissingCardMarks()) {
1468 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1469 }
1470 SwapStacks();
1471 }
1472 thread_list->ResumeAll();
1473 }
1474
1475 if (verify_mod_union_table_) {
1476 thread_list->SuspendAll();
1477 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1478 zygote_mod_union_table_->Update();
1479 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001480 image_mod_union_table_->Update();
1481 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001482 thread_list->ResumeAll();
1483 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001484}
1485
Ian Rogers1d54e732013-05-02 21:10:01 -07001486void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001487 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001488
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001489 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1490 // reachable objects.
1491 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001492 Thread* self = Thread::Current();
1493 CHECK_NE(self->GetState(), kRunnable);
1494 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001495 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001496 {
1497 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1498 // Swapping bound bitmaps does nothing.
1499 gc->SwapBitmaps();
1500 if (!VerifyHeapReferences()) {
1501 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1502 }
1503 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001504 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001505 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001506 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001507 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001508}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001509
Ian Rogers1d54e732013-05-02 21:10:01 -07001510void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001511 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001512
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001513 if (verify_system_weaks_) {
1514 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001515 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001516 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001517 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001518}
1519
Ian Rogers1d54e732013-05-02 21:10:01 -07001520collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1521 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001522 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001523 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001524 bool do_wait;
1525 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001526 {
1527 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001528 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001529 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001530 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001531 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001532 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001533 // We must wait, change thread state then sleep on gc_complete_cond_;
1534 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1535 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001536 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001537 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001538 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001539 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001540 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001541 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001542 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001543 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001544 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001545 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1546 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001548 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001549 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001550 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001551}
1552
Elliott Hughesc967f782012-04-16 10:23:15 -07001553void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001554 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001555 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001556 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001557}
1558
1559size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001560 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001561}
1562
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001563void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001564 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001565 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001566 << PrettySize(GetMaxMemory());
1567 max_allowed_footprint = GetMaxMemory();
1568 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001569 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001570}
1571
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001572void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001573 // We know what our utilization is at this moment.
1574 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001575 const size_t bytes_allocated = GetBytesAllocated();
1576 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001577 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001578
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001579 size_t target_size;
1580 if (gc_type != collector::kGcTypeSticky) {
1581 // Grow the heap for non sticky GC.
1582 target_size = bytes_allocated / GetTargetHeapUtilization();
1583 if (target_size > bytes_allocated + max_free_) {
1584 target_size = bytes_allocated + max_free_;
1585 } else if (target_size < bytes_allocated + min_free_) {
1586 target_size = bytes_allocated + min_free_;
1587 }
1588 next_gc_type_ = collector::kGcTypeSticky;
1589 } else {
1590 // Based on how close the current heap size is to the target size, decide
1591 // whether or not to do a partial or sticky GC next.
1592 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1593 next_gc_type_ = collector::kGcTypeSticky;
1594 } else {
1595 next_gc_type_ = collector::kGcTypePartial;
1596 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001597
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001598 // If we have freed enough memory, shrink the heap back down.
1599 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1600 target_size = bytes_allocated + max_free_;
1601 } else {
1602 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1603 }
1604 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001605 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001606
Ian Rogers1d54e732013-05-02 21:10:01 -07001607 // Calculate when to perform the next ConcurrentGC.
1608 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001609 // Calculate the estimated GC duration.
1610 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1611 // Estimate how many remaining bytes we will have when we need to start the next GC.
1612 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001613 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1614 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1615 // A never going to happen situation that from the estimated allocation rate we will exceed
1616 // the applications entire footprint with the given estimated allocation rate. Schedule
1617 // another GC straight away.
1618 concurrent_start_bytes_ = bytes_allocated;
1619 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001620 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1621 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1622 // right away.
1623 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001624 }
1625 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1626 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1627 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001628}
1629
jeffhaoc1160702011-10-27 15:48:45 -07001630void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001631 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001632 alloc_space_->ClearGrowthLimit();
1633}
1634
Elliott Hughesadb460d2011-10-05 17:02:34 -07001635void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001636 MemberOffset reference_queue_offset,
1637 MemberOffset reference_queueNext_offset,
1638 MemberOffset reference_pendingNext_offset,
1639 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001640 reference_referent_offset_ = reference_referent_offset;
1641 reference_queue_offset_ = reference_queue_offset;
1642 reference_queueNext_offset_ = reference_queueNext_offset;
1643 reference_pendingNext_offset_ = reference_pendingNext_offset;
1644 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1645 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1646 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1647 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1648 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1649 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1650}
1651
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001652mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001653 DCHECK(reference != NULL);
1654 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001655 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001656}
1657
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001658void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001659 DCHECK(reference != NULL);
1660 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1661 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1662}
1663
1664// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001665bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001666 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001667 const mirror::Object* queue =
1668 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1669 const mirror::Object* queue_next =
1670 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001671 return (queue != NULL) && (queue_next == NULL);
1672}
1673
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001674void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001675 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001676 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1677 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001678 EnqueuePendingReference(ref, cleared_reference_list);
1679}
1680
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001681void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001682 DCHECK(ref != NULL);
1683 DCHECK(list != NULL);
1684
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001685 // TODO: Remove this lock, use atomic stacks for storing references.
1686 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001687 if (*list == NULL) {
1688 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1689 *list = ref;
1690 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001691 mirror::Object* head =
1692 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001693 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1694 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1695 }
1696}
1697
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001698mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001699 DCHECK(list != NULL);
1700 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001701 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1702 false);
1703 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001704
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001705 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1706 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001707 if (*list == head) {
1708 ref = *list;
1709 *list = NULL;
1710 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001711 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1712 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001713 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1714 ref = head;
1715 }
1716 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1717 return ref;
1718}
1719
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001720void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001721 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001722 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001723 ArgArray arg_array(NULL, 0);
1724 arg_array.Append(reinterpret_cast<uint32_t>(object));
1725 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001726 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001727}
1728
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001729void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001730 DCHECK(cleared != NULL);
1731 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001732 // When a runtime isn't started there are no reference queues to care about so ignore.
1733 if (LIKELY(Runtime::Current()->IsStarted())) {
1734 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001735 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001736 ArgArray arg_array(NULL, 0);
1737 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1738 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001739 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001740 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001741 *cleared = NULL;
1742 }
1743}
1744
Ian Rogers1f539342012-10-03 21:09:42 -07001745void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001746 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001747 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001748 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001749 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001750 !runtime->IsConcurrentGcEnabled()) {
1751 return;
1752 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001753 {
1754 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1755 if (runtime->IsShuttingDown()) {
1756 return;
1757 }
1758 }
1759 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001760 return;
1761 }
1762
Ian Rogers120f1c72012-09-28 17:17:10 -07001763 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001764 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1765 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001766 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1767 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001768 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001769}
1770
Ian Rogers81d425b2012-09-27 16:03:43 -07001771void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001772 {
1773 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001774 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001775 return;
1776 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001777 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001778
Mathieu Chartier65db8802012-11-20 12:36:46 -08001779 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001780 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001781 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001782 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001783}
1784
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001785void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001786 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1787 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1788 // a space it will hold its lock and can become a cause of jank.
1789 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1790 // forking.
1791
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001792 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1793 // because that only marks object heads, so a large array looks like lots of empty space. We
1794 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1795 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1796 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1797 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001798 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001799 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001800 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1801 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001802 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1803 // heap trim occurred in the last two seconds.
1804 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001805 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001806
1807 Thread* self = Thread::Current();
1808 {
1809 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1810 Runtime* runtime = Runtime::Current();
1811 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1812 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1813 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1814 // as we don't hold the lock while requesting the trim).
1815 return;
1816 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001817 }
Ian Rogers48931882013-01-22 14:35:16 -08001818
1819 SchedPolicy policy;
1820 get_sched_policy(self->GetTid(), &policy);
1821 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1822 // Don't trim the heap if we are a foreground or audio app.
1823 return;
1824 }
1825
Ian Rogers1d54e732013-05-02 21:10:01 -07001826 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001827 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001828 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1829 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001830 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1831 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001832 CHECK(!env->ExceptionCheck());
1833}
1834
Ian Rogers48931882013-01-22 14:35:16 -08001835size_t Heap::Trim() {
1836 // Handle a requested heap trim on a thread outside of the main GC thread.
1837 return alloc_space_->Trim();
1838}
1839
Ian Rogers1d54e732013-05-02 21:10:01 -07001840} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001841} // namespace art