blob: 20e791d9f2916dfb50bc7ef95abf1b2576b8c9c6 [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>
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Carl Shapiro58551df2011-07-24 03:09:51 -070024#include <vector>
25
Mathieu Chartierc7853442015-03-27 14:35:38 -070026#include "art_field-inl.h"
Mathieu Chartierbad02672014-08-25 13:08:22 -070027#include "base/allocator.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include "base/dumpable.h"
Mathieu Chartierb2f99362013-11-20 17:26:00 -080029#include "base/histogram-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080030#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010031#include "base/time_utils.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070032#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080033#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070034#include "debugger.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080035#include "dex_file-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070036#include "gc/accounting/atomic_stack.h"
37#include "gc/accounting/card_table-inl.h"
38#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070039#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/accounting/mod_union_table-inl.h"
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -080041#include "gc/accounting/remembered_set.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070042#include "gc/accounting/space_bitmap-inl.h"
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070043#include "gc/collector/concurrent_copying.h"
Mathieu Chartier52e4b432014-06-10 11:22:31 -070044#include "gc/collector/mark_compact.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070045#include "gc/collector/mark_sweep-inl.h"
46#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070047#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070048#include "gc/collector/sticky_mark_sweep.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070049#include "gc/reference_processor.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070050#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070051#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "gc/space/image_space.h"
53#include "gc/space/large_object_space.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080054#include "gc/space/region_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070055#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070056#include "gc/space/space-inl.h"
Mathieu Chartiera1602f22014-01-13 17:19:19 -080057#include "gc/space/zygote_space.h"
Mathieu Chartiera5eae692014-12-17 17:56:03 -080058#include "gc/task_processor.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080059#include "entrypoints/quick/quick_alloc_entrypoints.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070060#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070061#include "image.h"
Mathieu Chartiereb175f72014-10-31 11:49:27 -070062#include "intern_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080063#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "mirror/object.h"
65#include "mirror/object-inl.h"
66#include "mirror/object_array-inl.h"
Mathieu Chartier8fa2dad2014-03-13 12:22:56 -070067#include "mirror/reference-inl.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080068#include "os.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070069#include "reflection.h"
Mathieu Chartier0de9f732013-11-22 17:58:48 -080070#include "runtime.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070071#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070072#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070073#include "handle_scope-inl.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070074#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070075#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070076
77namespace art {
Mathieu Chartier50482232013-11-21 11:48:14 -080078
Ian Rogers1d54e732013-05-02 21:10:01 -070079namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070080
Mathieu Chartier91e30632014-03-25 15:58:50 -070081static constexpr size_t kCollectorTransitionStressIterations = 0;
82static constexpr size_t kCollectorTransitionStressWait = 10 * 1000; // Microseconds
Ian Rogers1d54e732013-05-02 21:10:01 -070083// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070084static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier74762802014-01-24 10:21:35 -080085static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -070086// Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
Mathieu Chartier73d1e172014-04-11 17:53:48 -070087// relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -070088// threads (lower pauses, use less memory bandwidth).
Mathieu Chartier73d1e172014-04-11 17:53:48 -070089static constexpr double kStickyGcThroughputAdjustment = 1.0;
Mathieu Chartierc1790162014-05-23 10:54:50 -070090// Whether or not we compact the zygote in PreZygoteFork.
Mathieu Chartier31f44142014-04-08 14:40:03 -070091static constexpr bool kCompactZygote = kMovingCollector;
Mathieu Chartierc1790162014-05-23 10:54:50 -070092// How many reserve entries are at the end of the allocation stack, these are only needed if the
93// allocation stack overflows.
94static constexpr size_t kAllocationStackReserveSize = 1024;
95// Default mark stack size in bytes.
96static const size_t kDefaultMarkStackSize = 64 * KB;
Zuo Wangf37a88b2014-07-10 04:26:41 -070097// Define space name.
98static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
99static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
100static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
Mathieu Chartier7247af52014-11-19 10:51:42 -0800101static const char* kNonMovingSpaceName = "non moving space";
102static const char* kZygoteSpaceName = "zygote space";
Mathieu Chartierb363f662014-07-16 13:28:58 -0700103static constexpr size_t kGSSBumpPointerSpaceCapacity = 32 * MB;
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800104static constexpr bool kGCALotMode = false;
105// GC alot mode uses a small allocation stack to stress test a lot of GC.
106static constexpr size_t kGcAlotAllocationStackSize = 4 * KB /
107 sizeof(mirror::HeapReference<mirror::Object>);
108// Verify objet has a small allocation stack size since searching the allocation stack is slow.
109static constexpr size_t kVerifyObjectAllocationStackSize = 16 * KB /
110 sizeof(mirror::HeapReference<mirror::Object>);
111static constexpr size_t kDefaultAllocationStackSize = 8 * MB /
112 sizeof(mirror::HeapReference<mirror::Object>);
Mathieu Chartier0051be62012-10-12 17:47:11 -0700113
Mathieu Chartier0051be62012-10-12 17:47:11 -0700114Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700115 double target_utilization, double foreground_heap_growth_multiplier,
116 size_t capacity, size_t non_moving_space_capacity, const std::string& image_file_name,
117 const InstructionSet image_instruction_set, CollectorType foreground_collector_type,
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700118 CollectorType background_collector_type,
119 space::LargeObjectSpaceType large_object_space_type, size_t large_object_threshold,
120 size_t parallel_gc_threads, size_t conc_gc_threads, bool low_memory_mode,
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800121 size_t long_pause_log_threshold, size_t long_gc_log_threshold,
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700122 bool ignore_max_footprint, bool use_tlab,
123 bool verify_pre_gc_heap, bool verify_pre_sweeping_heap, bool verify_post_gc_heap,
124 bool verify_pre_gc_rosalloc, bool verify_pre_sweeping_rosalloc,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700125 bool verify_post_gc_rosalloc, bool use_homogeneous_space_compaction_for_oom,
126 uint64_t min_interval_homogeneous_space_compaction_by_oom)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800127 : non_moving_space_(nullptr),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800128 rosalloc_space_(nullptr),
129 dlmalloc_space_(nullptr),
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800130 main_space_(nullptr),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800131 collector_type_(kCollectorTypeNone),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700132 foreground_collector_type_(foreground_collector_type),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800133 background_collector_type_(background_collector_type),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700134 desired_collector_type_(foreground_collector_type_),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800135 pending_task_lock_(nullptr),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700136 parallel_gc_threads_(parallel_gc_threads),
137 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -0700138 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700139 long_pause_log_threshold_(long_pause_log_threshold),
140 long_gc_log_threshold_(long_gc_log_threshold),
141 ignore_max_footprint_(ignore_max_footprint),
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -0700142 zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700143 zygote_space_(nullptr),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700144 large_object_threshold_(large_object_threshold),
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800145 collector_type_running_(kCollectorTypeNone),
Ian Rogers1d54e732013-05-02 21:10:01 -0700146 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700147 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800148 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700149 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700150 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700151 native_footprint_gc_watermark_(initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700152 native_need_to_run_finalization_(false),
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800153 // Initially assume we perceive jank in case the process state is never updated.
154 process_state_(kProcessStateJankPerceptible),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800155 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700156 total_bytes_freed_ever_(0),
157 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800158 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700159 native_bytes_allocated_(0),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700160 num_bytes_freed_revoke_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700161 verify_missing_card_marks_(false),
162 verify_system_weaks_(false),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800163 verify_pre_gc_heap_(verify_pre_gc_heap),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700164 verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800165 verify_post_gc_heap_(verify_post_gc_heap),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700166 verify_mod_union_table_(false),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800167 verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700168 verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800169 verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700170 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
171 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
172 * verification is enabled, we limit the size of allocation stacks to speed up their
173 * searching.
174 */
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800175 max_allocation_stack_size_(kGCALotMode ? kGcAlotAllocationStackSize
176 : (kVerifyObjectSupport > kVerifyObjectModeFast) ? kVerifyObjectAllocationStackSize :
177 kDefaultAllocationStackSize),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800178 current_allocator_(kAllocatorTypeDlMalloc),
179 current_non_moving_allocator_(kAllocatorTypeNonMoving),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700180 bump_pointer_space_(nullptr),
181 temp_space_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800182 region_space_(nullptr),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700183 min_free_(min_free),
184 max_free_(max_free),
185 target_utilization_(target_utilization),
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -0700186 foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700187 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700188 total_allocation_time_(0),
Mathieu Chartier4e305412014-02-19 10:54:44 -0800189 verify_object_mode_(kVerifyObjectModeDisabled),
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800190 disable_moving_gc_count_(0),
Mathieu Chartierda44d772014-04-01 15:01:46 -0700191 running_on_valgrind_(Runtime::Current()->RunningOnValgrind()),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700192 use_tlab_(use_tlab),
193 main_space_backup_(nullptr),
Mathieu Chartierb363f662014-07-16 13:28:58 -0700194 min_interval_homogeneous_space_compaction_by_oom_(
195 min_interval_homogeneous_space_compaction_by_oom),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700196 last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800197 pending_collector_transition_(nullptr),
198 pending_heap_trim_(nullptr),
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700199 use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom),
200 running_collection_is_blocking_(false),
201 blocking_gc_count_(0U),
202 blocking_gc_time_(0U),
203 last_update_time_gc_count_rate_histograms_( // Round down by the window duration.
204 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration),
205 gc_count_last_window_(0U),
206 blocking_gc_count_last_window_(0U),
207 gc_count_rate_histogram_("gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
208 blocking_gc_count_rate_histogram_("blocking gc count rate histogram", 1U,
209 kGcCountRateMaxBucketCount) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800210 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800211 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700212 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800213 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
214 // entrypoints.
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700215 const bool is_zygote = Runtime::Current()->IsZygote();
216 if (!is_zygote) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700217 // Background compaction is currently not supported for command line runs.
218 if (background_collector_type_ != foreground_collector_type_) {
Mathieu Chartier52ba1992014-05-07 14:39:21 -0700219 VLOG(heap) << "Disabling background compaction for non zygote";
Mathieu Chartier31f44142014-04-08 14:40:03 -0700220 background_collector_type_ = foreground_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800221 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800222 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800223 ChangeCollector(desired_collector_type_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700224 live_bitmap_.reset(new accounting::HeapBitmap(this));
225 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Ian Rogers30fab402012-01-23 15:43:46 -0800226 // Requested begin for the alloc space, to follow the mapped image and oat files
Ian Rogers13735952014-10-08 12:43:28 -0700227 uint8_t* requested_alloc_space_begin = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800228 if (foreground_collector_type_ == kCollectorTypeCC) {
229 // Need to use a low address so that we can allocate a contiguous
230 // 2 * Xmx space when there's no image (dex2oat for target).
231 CHECK_GE(300 * MB, non_moving_space_capacity);
232 requested_alloc_space_begin = reinterpret_cast<uint8_t*>(300 * MB) - non_moving_space_capacity;
233 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800234 if (!image_file_name.empty()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700235 std::string error_msg;
Narayan Kamath11d9f062014-04-23 20:24:57 +0100236 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str(),
Alex Light64ad14d2014-08-19 14:23:13 -0700237 image_instruction_set,
238 &error_msg);
239 if (image_space != nullptr) {
240 AddSpace(image_space);
241 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
242 // isn't going to get in the middle
Ian Rogers13735952014-10-08 12:43:28 -0700243 uint8_t* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
Alex Light64ad14d2014-08-19 14:23:13 -0700244 CHECK_GT(oat_file_end_addr, image_space->End());
245 requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
246 } else {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700247 LOG(ERROR) << "Could not create image space with image file '" << image_file_name << "'. "
Alex Light64ad14d2014-08-19 14:23:13 -0700248 << "Attempting to fall back to imageless running. Error was: " << error_msg;
249 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700250 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700251 /*
252 requested_alloc_space_begin -> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700253 +- nonmoving space (non_moving_space_capacity)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700254 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700255 +-????????????????????????????????????????????+-
256 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700257 +-main alloc space / bump space 1 (capacity_) +-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700258 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700259 +-????????????????????????????????????????????+-
260 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
261 +-main alloc space2 / bump space 2 (capacity_)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700262 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
263 */
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800264 // We don't have hspace compaction enabled with GSS or CC.
265 if (foreground_collector_type_ == kCollectorTypeGSS ||
266 foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800267 use_homogeneous_space_compaction_for_oom_ = false;
268 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700269 bool support_homogeneous_space_compaction =
Mathieu Chartier0deeb812014-08-21 18:28:20 -0700270 background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800271 use_homogeneous_space_compaction_for_oom_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700272 // We may use the same space the main space for the non moving space if we don't need to compact
273 // from the main space.
274 // This is not the case if we support homogeneous compaction or have a moving background
275 // collector type.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700276 bool separate_non_moving_space = is_zygote ||
277 support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
278 IsMovingGc(background_collector_type_);
279 if (foreground_collector_type == kCollectorTypeGSS) {
280 separate_non_moving_space = false;
281 }
282 std::unique_ptr<MemMap> main_mem_map_1;
283 std::unique_ptr<MemMap> main_mem_map_2;
Ian Rogers13735952014-10-08 12:43:28 -0700284 uint8_t* request_begin = requested_alloc_space_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700285 if (request_begin != nullptr && separate_non_moving_space) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700286 request_begin += non_moving_space_capacity;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700287 }
288 std::string error_str;
289 std::unique_ptr<MemMap> non_moving_space_mem_map;
290 if (separate_non_moving_space) {
Mathieu Chartier7247af52014-11-19 10:51:42 -0800291 // If we are the zygote, the non moving space becomes the zygote space when we run
292 // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
293 // rename the mem map later.
294 const char* space_name = is_zygote ? kZygoteSpaceName: kNonMovingSpaceName;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700295 // Reserve the non moving mem map before the other two since it needs to be at a specific
296 // address.
297 non_moving_space_mem_map.reset(
Mathieu Chartier7247af52014-11-19 10:51:42 -0800298 MemMap::MapAnonymous(space_name, requested_alloc_space_begin,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000299 non_moving_space_capacity, PROT_READ | PROT_WRITE, true, false,
300 &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700301 CHECK(non_moving_space_mem_map != nullptr) << error_str;
Mathieu Chartierc44ce2e2014-08-25 16:32:41 -0700302 // Try to reserve virtual memory at a lower address if we have a separate non moving space.
Ian Rogers13735952014-10-08 12:43:28 -0700303 request_begin = reinterpret_cast<uint8_t*>(300 * MB);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700304 }
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700305 // Attempt to create 2 mem maps at or after the requested begin.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800306 if (foreground_collector_type_ != kCollectorTypeCC) {
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700307 if (separate_non_moving_space) {
308 main_mem_map_1.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[0], request_begin,
309 capacity_, &error_str));
310 } else {
311 // If no separate non-moving space, the main space must come
312 // right after the image space to avoid a gap.
313 main_mem_map_1.reset(MemMap::MapAnonymous(kMemMapSpaceName[0], request_begin, capacity_,
314 PROT_READ | PROT_WRITE, true, false,
315 &error_str));
316 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800317 CHECK(main_mem_map_1.get() != nullptr) << error_str;
318 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700319 if (support_homogeneous_space_compaction ||
320 background_collector_type_ == kCollectorTypeSS ||
321 foreground_collector_type_ == kCollectorTypeSS) {
322 main_mem_map_2.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[1], main_mem_map_1->End(),
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700323 capacity_, &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700324 CHECK(main_mem_map_2.get() != nullptr) << error_str;
325 }
326 // Create the non moving space first so that bitmaps don't take up the address range.
327 if (separate_non_moving_space) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700328 // Non moving space is always dlmalloc since we currently don't have support for multiple
Zuo Wangf37a88b2014-07-10 04:26:41 -0700329 // active rosalloc spaces.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700330 const size_t size = non_moving_space_mem_map->Size();
331 non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700332 non_moving_space_mem_map.release(), "zygote / non moving space", kDefaultStartingSize,
Mathieu Chartierb363f662014-07-16 13:28:58 -0700333 initial_size, size, size, false);
Mathieu Chartier78408882014-04-11 18:06:01 -0700334 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Mathieu Chartierb363f662014-07-16 13:28:58 -0700335 CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
336 << requested_alloc_space_begin;
337 AddSpace(non_moving_space_);
338 }
339 // Create other spaces based on whether or not we have a moving GC.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800340 if (foreground_collector_type_ == kCollectorTypeCC) {
341 region_space_ = space::RegionSpace::Create("Region space", capacity_ * 2, request_begin);
342 AddSpace(region_space_);
343 } else if (IsMovingGc(foreground_collector_type_) && foreground_collector_type_ != kCollectorTypeGSS) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700344 // Create bump pointer spaces.
345 // We only to create the bump pointer if the foreground collector is a compacting GC.
346 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
347 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
348 main_mem_map_1.release());
349 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
350 AddSpace(bump_pointer_space_);
351 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
352 main_mem_map_2.release());
353 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
354 AddSpace(temp_space_);
355 CHECK(separate_non_moving_space);
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700356 } else {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700357 CreateMainMallocSpace(main_mem_map_1.release(), initial_size, growth_limit_, capacity_);
358 CHECK(main_space_ != nullptr);
359 AddSpace(main_space_);
360 if (!separate_non_moving_space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700361 non_moving_space_ = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700362 CHECK(!non_moving_space_->CanMoveObjects());
363 }
364 if (foreground_collector_type_ == kCollectorTypeGSS) {
365 CHECK_EQ(foreground_collector_type_, background_collector_type_);
366 // Create bump pointer spaces instead of a backup space.
367 main_mem_map_2.release();
368 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space 1",
369 kGSSBumpPointerSpaceCapacity, nullptr);
370 CHECK(bump_pointer_space_ != nullptr);
371 AddSpace(bump_pointer_space_);
372 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2",
373 kGSSBumpPointerSpaceCapacity, nullptr);
374 CHECK(temp_space_ != nullptr);
375 AddSpace(temp_space_);
376 } else if (main_mem_map_2.get() != nullptr) {
377 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
378 main_space_backup_.reset(CreateMallocSpaceFromMemMap(main_mem_map_2.release(), initial_size,
379 growth_limit_, capacity_, name, true));
380 CHECK(main_space_backup_.get() != nullptr);
381 // Add the space so its accounted for in the heap_begin and heap_end.
382 AddSpace(main_space_backup_.get());
Zuo Wangf37a88b2014-07-10 04:26:41 -0700383 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700384 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700385 CHECK(non_moving_space_ != nullptr);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700386 CHECK(!non_moving_space_->CanMoveObjects());
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700387 // Allocate the large object space.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800388 if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700389 large_object_space_ = space::FreeListSpace::Create("free list large object space", nullptr,
390 capacity_);
391 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800392 } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700393 large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
394 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700395 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700396 // Disable the large object space by making the cutoff excessively large.
397 large_object_threshold_ = std::numeric_limits<size_t>::max();
398 large_object_space_ = nullptr;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700399 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700400 if (large_object_space_ != nullptr) {
401 AddSpace(large_object_space_);
402 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700403 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700404 CHECK(!continuous_spaces_.empty());
405 // Relies on the spaces being sorted.
Ian Rogers13735952014-10-08 12:43:28 -0700406 uint8_t* heap_begin = continuous_spaces_.front()->Begin();
407 uint8_t* heap_end = continuous_spaces_.back()->Limit();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700408 size_t heap_capacity = heap_end - heap_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700409 // Remove the main backup space since it slows down the GC to have unused extra spaces.
Mathieu Chartier0310da52014-12-01 13:40:48 -0800410 // TODO: Avoid needing to do this.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700411 if (main_space_backup_.get() != nullptr) {
412 RemoveSpace(main_space_backup_.get());
413 }
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800414 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700415 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700416 CHECK(card_table_.get() != nullptr) << "Failed to create card table";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800417
418 if (foreground_collector_type_ == kCollectorTypeCC && kUseTableLookupReadBarrier) {
419 rb_table_.reset(new accounting::ReadBarrierTable());
420 DCHECK(rb_table_->IsAllCleared());
421 }
Mathieu Chartier4858a932015-01-23 13:18:53 -0800422 if (GetImageSpace() != nullptr) {
423 // Don't add the image mod union table if we are running without an image, this can crash if
424 // we use the CardCache implementation.
425 accounting::ModUnionTable* mod_union_table = new accounting::ModUnionTableToZygoteAllocspace(
426 "Image mod-union table", this, GetImageSpace());
427 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
428 AddModUnionTable(mod_union_table);
429 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700430 if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800431 accounting::RememberedSet* non_moving_space_rem_set =
432 new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
433 CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
434 AddRememberedSet(non_moving_space_rem_set);
435 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700436 // TODO: Count objects in the image space here?
Ian Rogers3e5cf302014-05-20 16:40:37 -0700437 num_bytes_allocated_.StoreRelaxed(0);
Mathieu Chartierc1790162014-05-23 10:54:50 -0700438 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
439 kDefaultMarkStackSize));
440 const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
441 allocation_stack_.reset(accounting::ObjectStack::Create(
442 "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
443 live_stack_.reset(accounting::ObjectStack::Create(
444 "live stack", max_allocation_stack_size_, alloc_stack_capacity));
Mathieu Chartier65db8802012-11-20 12:36:46 -0800445 // It's still too early to take a lock because there are no threads yet, but we can create locks
446 // now. We don't create it earlier to make it clear that you can't use locks during heap
447 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700448 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700449 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
450 *gc_complete_lock_));
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800451 task_processor_.reset(new TaskProcessor());
452 pending_task_lock_ = new Mutex("Pending task lock");
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700453 if (ignore_max_footprint_) {
454 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700455 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700456 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700457 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800458 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800459 for (size_t i = 0; i < 2; ++i) {
460 const bool concurrent = i != 0;
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800461 if ((MayUseCollector(kCollectorTypeCMS) && concurrent) ||
462 (MayUseCollector(kCollectorTypeMS) && !concurrent)) {
463 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
464 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
465 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
466 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800467 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800468 if (kMovingCollector) {
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800469 if (MayUseCollector(kCollectorTypeSS) || MayUseCollector(kCollectorTypeGSS) ||
470 MayUseCollector(kCollectorTypeHomogeneousSpaceCompact) ||
471 use_homogeneous_space_compaction_for_oom_) {
472 // TODO: Clean this up.
473 const bool generational = foreground_collector_type_ == kCollectorTypeGSS;
474 semi_space_collector_ = new collector::SemiSpace(this, generational,
475 generational ? "generational" : "");
476 garbage_collectors_.push_back(semi_space_collector_);
477 }
478 if (MayUseCollector(kCollectorTypeCC)) {
479 concurrent_copying_collector_ = new collector::ConcurrentCopying(this);
480 garbage_collectors_.push_back(concurrent_copying_collector_);
481 }
482 if (MayUseCollector(kCollectorTypeMC)) {
483 mark_compact_collector_ = new collector::MarkCompact(this);
484 garbage_collectors_.push_back(mark_compact_collector_);
485 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700486 }
Andreas Gampee1cb2982014-08-27 11:01:09 -0700487 if (GetImageSpace() != nullptr && non_moving_space_ != nullptr &&
488 (is_zygote || separate_non_moving_space || foreground_collector_type_ == kCollectorTypeGSS)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700489 // Check that there's no gap between the image space and the non moving space so that the
Andreas Gampee1cb2982014-08-27 11:01:09 -0700490 // immune region won't break (eg. due to a large object allocated in the gap). This is only
491 // required when we're the zygote or using GSS.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700492 bool no_gap = MemMap::CheckNoGaps(GetImageSpace()->GetMemMap(),
493 non_moving_space_->GetMemMap());
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700494 if (!no_gap) {
Vladimir Marko17a924a2015-05-08 15:17:32 +0100495 MemMap::DumpMaps(LOG(ERROR), true);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700496 LOG(FATAL) << "There's a gap between the image space and the non-moving space";
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700497 }
498 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700499 if (running_on_valgrind_) {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700500 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700501 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800502 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800503 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700504 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700505}
506
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700507MemMap* Heap::MapAnonymousPreferredAddress(const char* name, uint8_t* request_begin,
508 size_t capacity, std::string* out_error_str) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700509 while (true) {
Kyungmin Leeef32b8f2014-10-23 09:32:05 +0900510 MemMap* map = MemMap::MapAnonymous(name, request_begin, capacity,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000511 PROT_READ | PROT_WRITE, true, false, out_error_str);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700512 if (map != nullptr || request_begin == nullptr) {
513 return map;
514 }
515 // Retry a second time with no specified request begin.
516 request_begin = nullptr;
517 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700518}
519
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800520bool Heap::MayUseCollector(CollectorType type) const {
521 return foreground_collector_type_ == type || background_collector_type_ == type;
522}
523
Zuo Wangf37a88b2014-07-10 04:26:41 -0700524space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap* mem_map, size_t initial_size,
525 size_t growth_limit, size_t capacity,
526 const char* name, bool can_move_objects) {
527 space::MallocSpace* malloc_space = nullptr;
528 if (kUseRosAlloc) {
529 // Create rosalloc space.
530 malloc_space = space::RosAllocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
531 initial_size, growth_limit, capacity,
532 low_memory_mode_, can_move_objects);
533 } else {
534 malloc_space = space::DlMallocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
535 initial_size, growth_limit, capacity,
536 can_move_objects);
537 }
538 if (collector::SemiSpace::kUseRememberedSet) {
539 accounting::RememberedSet* rem_set =
540 new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
541 CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
542 AddRememberedSet(rem_set);
543 }
544 CHECK(malloc_space != nullptr) << "Failed to create " << name;
545 malloc_space->SetFootprintLimit(malloc_space->Capacity());
546 return malloc_space;
547}
548
Mathieu Chartier31f44142014-04-08 14:40:03 -0700549void Heap::CreateMainMallocSpace(MemMap* mem_map, size_t initial_size, size_t growth_limit,
550 size_t capacity) {
551 // Is background compaction is enabled?
552 bool can_move_objects = IsMovingGc(background_collector_type_) !=
Zuo Wangf37a88b2014-07-10 04:26:41 -0700553 IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700554 // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
555 // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
556 // from the main space to the zygote space. If background compaction is enabled, always pass in
557 // that we can move objets.
558 if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
559 // After the zygote we want this to be false if we don't have background compaction enabled so
560 // that getting primitive array elements is faster.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700561 // We never have homogeneous compaction with GSS and don't need a space with movable objects.
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700562 can_move_objects = !HasZygoteSpace() && foreground_collector_type_ != kCollectorTypeGSS;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700563 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700564 if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
565 RemoveRememberedSet(main_space_);
566 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700567 const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
568 main_space_ = CreateMallocSpaceFromMemMap(mem_map, initial_size, growth_limit, capacity, name,
569 can_move_objects);
570 SetSpaceAsDefault(main_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700571 VLOG(heap) << "Created main space " << main_space_;
572}
573
Mathieu Chartier50482232013-11-21 11:48:14 -0800574void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800575 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800576 // These two allocators are only used internally and don't have any entrypoints.
577 CHECK_NE(allocator, kAllocatorTypeLOS);
578 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800579 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800580 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800581 SetQuickAllocEntryPointsAllocator(current_allocator_);
582 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
583 }
584}
585
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700586void Heap::DisableMovingGc() {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700587 if (IsMovingGc(foreground_collector_type_)) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700588 foreground_collector_type_ = kCollectorTypeCMS;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800589 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700590 if (IsMovingGc(background_collector_type_)) {
591 background_collector_type_ = foreground_collector_type_;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800592 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700593 TransitionCollector(foreground_collector_type_);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700594 ThreadList* tl = Runtime::Current()->GetThreadList();
595 Thread* self = Thread::Current();
596 ScopedThreadStateChange tsc(self, kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700597 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700598 // Something may have caused the transition to fail.
Mathieu Chartiere4927f62014-08-23 13:56:03 -0700599 if (!IsMovingGc(collector_type_) && non_moving_space_ != main_space_) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700600 CHECK(main_space_ != nullptr);
601 // The allocation stack may have non movable objects in it. We need to flush it since the GC
602 // can't only handle marking allocation stack objects of one non moving space and one main
603 // space.
604 {
605 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
606 FlushAllocStack();
607 }
608 main_space_->DisableMovingObjects();
609 non_moving_space_ = main_space_;
610 CHECK(!non_moving_space_->CanMoveObjects());
611 }
612 tl->ResumeAll();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800613}
614
Mathieu Chartier15d34022014-02-26 17:16:38 -0800615std::string Heap::SafeGetClassDescriptor(mirror::Class* klass) {
616 if (!IsValidContinuousSpaceObjectAddress(klass)) {
617 return StringPrintf("<non heap address klass %p>", klass);
618 }
619 mirror::Class* component_type = klass->GetComponentType<kVerifyNone>();
620 if (IsValidContinuousSpaceObjectAddress(component_type) && klass->IsArrayClass<kVerifyNone>()) {
621 std::string result("[");
622 result += SafeGetClassDescriptor(component_type);
623 return result;
624 } else if (UNLIKELY(klass->IsPrimitive<kVerifyNone>())) {
625 return Primitive::Descriptor(klass->GetPrimitiveType<kVerifyNone>());
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800626 } else if (UNLIKELY(klass->IsProxyClass<kVerifyNone>())) {
Mathieu Chartier15d34022014-02-26 17:16:38 -0800627 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(klass);
628 } else {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800629 mirror::DexCache* dex_cache = klass->GetDexCache<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800630 if (!IsValidContinuousSpaceObjectAddress(dex_cache)) {
631 return StringPrintf("<non heap address dex_cache %p>", dex_cache);
632 }
633 const DexFile* dex_file = dex_cache->GetDexFile();
634 uint16_t class_def_idx = klass->GetDexClassDefIndex();
635 if (class_def_idx == DexFile::kDexNoIndex16) {
636 return "<class def not found>";
637 }
638 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
639 const DexFile::TypeId& type_id = dex_file->GetTypeId(class_def.class_idx_);
640 return dex_file->GetTypeDescriptor(type_id);
641 }
642}
643
644std::string Heap::SafePrettyTypeOf(mirror::Object* obj) {
645 if (obj == nullptr) {
646 return "null";
647 }
648 mirror::Class* klass = obj->GetClass<kVerifyNone>();
649 if (klass == nullptr) {
650 return "(class=null)";
651 }
652 std::string result(SafeGetClassDescriptor(klass));
653 if (obj->IsClass()) {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800654 result += "<" + SafeGetClassDescriptor(obj->AsClass<kVerifyNone>()) + ">";
Mathieu Chartier15d34022014-02-26 17:16:38 -0800655 }
656 return result;
657}
658
659void Heap::DumpObject(std::ostream& stream, mirror::Object* obj) {
660 if (obj == nullptr) {
661 stream << "(obj=null)";
662 return;
663 }
664 if (IsAligned<kObjectAlignment>(obj)) {
665 space::Space* space = nullptr;
666 // Don't use find space since it only finds spaces which actually contain objects instead of
667 // spaces which may contain objects (e.g. cleared bump pointer spaces).
668 for (const auto& cur_space : continuous_spaces_) {
669 if (cur_space->HasAddress(obj)) {
670 space = cur_space;
671 break;
672 }
673 }
Mathieu Chartier15d34022014-02-26 17:16:38 -0800674 // Unprotect all the spaces.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800675 for (const auto& con_space : continuous_spaces_) {
676 mprotect(con_space->Begin(), con_space->Capacity(), PROT_READ | PROT_WRITE);
Mathieu Chartier15d34022014-02-26 17:16:38 -0800677 }
678 stream << "Object " << obj;
679 if (space != nullptr) {
680 stream << " in space " << *space;
681 }
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800682 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800683 stream << "\nclass=" << klass;
684 if (klass != nullptr) {
685 stream << " type= " << SafePrettyTypeOf(obj);
686 }
687 // Re-protect the address we faulted on.
688 mprotect(AlignDown(obj, kPageSize), kPageSize, PROT_NONE);
689 }
690}
691
Mathieu Chartier590fee92013-09-13 13:46:47 -0700692bool Heap::IsCompilingBoot() const {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800693 if (!Runtime::Current()->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700694 return false;
695 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700696 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800697 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700698 return false;
699 }
700 }
701 return true;
702}
703
704bool Heap::HasImageSpace() const {
705 for (const auto& space : continuous_spaces_) {
706 if (space->IsImageSpace()) {
707 return true;
708 }
709 }
710 return false;
711}
712
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800713void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700714 // Need to do this holding the lock to prevent races where the GC is about to run / running when
715 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800716 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700717 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800718 ++disable_moving_gc_count_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700719 if (IsMovingGc(collector_type_running_)) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -0700720 WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800721 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700722}
723
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800724void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700725 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800726 CHECK_GE(disable_moving_gc_count_, 0U);
727 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700728}
729
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800730void Heap::UpdateProcessState(ProcessState process_state) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800731 if (process_state_ != process_state) {
732 process_state_ = process_state;
Mathieu Chartier91e30632014-03-25 15:58:50 -0700733 for (size_t i = 1; i <= kCollectorTransitionStressIterations; ++i) {
734 // Start at index 1 to avoid "is always false" warning.
735 // Have iteration 1 always transition the collector.
736 TransitionCollector((((i & 1) == 1) == (process_state_ == kProcessStateJankPerceptible))
Mathieu Chartier31f44142014-04-08 14:40:03 -0700737 ? foreground_collector_type_ : background_collector_type_);
Mathieu Chartier91e30632014-03-25 15:58:50 -0700738 usleep(kCollectorTransitionStressWait);
739 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800740 if (process_state_ == kProcessStateJankPerceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800741 // Transition back to foreground right away to prevent jank.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700742 RequestCollectorTransition(foreground_collector_type_, 0);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800743 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800744 // Don't delay for debug builds since we may want to stress test the GC.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700745 // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
746 // special handling which does a homogenous space compaction once but then doesn't transition
747 // the collector.
748 RequestCollectorTransition(background_collector_type_,
749 kIsDebugBuild ? 0 : kCollectorTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800750 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800751 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800752}
753
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700754void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700755 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
756 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800757 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700758 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700759}
760
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800761// Visit objects when threads aren't suspended. If concurrent moving
762// GC, disable moving GC and suspend threads and then visit objects.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800763void Heap::VisitObjects(ObjectCallback callback, void* arg) {
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800764 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800765 Locks::mutator_lock_->AssertSharedHeld(self);
766 DCHECK(!Locks::mutator_lock_->IsExclusiveHeld(self)) << "Call VisitObjectsPaused() instead";
767 if (IsGcConcurrentAndMoving()) {
768 // Concurrent moving GC. Just suspending threads isn't sufficient
769 // because a collection isn't one big pause and we could suspend
770 // threads in the middle (between phases) of a concurrent moving
771 // collection where it's not easily known which objects are alive
772 // (both the region space and the non-moving space) or which
773 // copies of objects to visit, and the to-space invariant could be
774 // easily broken. Visit objects while GC isn't running by using
775 // IncrementDisableMovingGC() and threads are suspended.
776 IncrementDisableMovingGC(self);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800777 self->TransitionFromRunnableToSuspended(kWaitingForVisitObjects);
778 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700779 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800780 VisitObjectsInternalRegionSpace(callback, arg);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800781 VisitObjectsInternal(callback, arg);
782 tl->ResumeAll();
783 self->TransitionFromSuspendedToRunnable();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800784 DecrementDisableMovingGC(self);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800785 } else {
786 // GCs can move objects, so don't allow this.
787 ScopedAssertNoThreadSuspension ants(self, "Visiting objects");
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800788 DCHECK(region_space_ == nullptr);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800789 VisitObjectsInternal(callback, arg);
790 }
791}
792
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800793// Visit objects when threads are already suspended.
794void Heap::VisitObjectsPaused(ObjectCallback callback, void* arg) {
795 Thread* self = Thread::Current();
796 Locks::mutator_lock_->AssertExclusiveHeld(self);
797 VisitObjectsInternalRegionSpace(callback, arg);
798 VisitObjectsInternal(callback, arg);
799}
800
801// Visit objects in the region spaces.
802void Heap::VisitObjectsInternalRegionSpace(ObjectCallback callback, void* arg) {
803 Thread* self = Thread::Current();
804 Locks::mutator_lock_->AssertExclusiveHeld(self);
805 if (region_space_ != nullptr) {
806 DCHECK(IsGcConcurrentAndMoving());
807 if (!zygote_creation_lock_.IsExclusiveHeld(self)) {
808 // Exclude the pre-zygote fork time where the semi-space collector
809 // calls VerifyHeapReferences() as part of the zygote compaction
810 // which then would call here without the moving GC disabled,
811 // which is fine.
812 DCHECK(IsMovingGCDisabled(self));
813 }
814 region_space_->Walk(callback, arg);
815 }
816}
817
818// Visit objects in the other spaces.
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800819void Heap::VisitObjectsInternal(ObjectCallback callback, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700820 if (bump_pointer_space_ != nullptr) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800821 // Visit objects in bump pointer space.
822 bump_pointer_space_->Walk(callback, arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700823 }
824 // TODO: Switch to standard begin and end to use ranged a based loop.
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800825 for (auto* it = allocation_stack_->Begin(), *end = allocation_stack_->End(); it < end; ++it) {
826 mirror::Object* const obj = it->AsMirrorPtr();
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800827 if (obj != nullptr && obj->GetClass() != nullptr) {
828 // Avoid the race condition caused by the object not yet being written into the allocation
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800829 // stack or the class not yet being written in the object. Or, if
830 // kUseThreadLocalAllocationStack, there can be nulls on the allocation stack.
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800831 callback(obj, arg);
832 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700833 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800834 {
835 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
836 GetLiveBitmap()->Walk(callback, arg);
837 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700838}
839
840void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartier00b59152014-07-25 10:13:51 -0700841 space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
842 space::ContinuousSpace* space2 = non_moving_space_;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800843 // TODO: Generalize this to n bitmaps?
Mathieu Chartier00b59152014-07-25 10:13:51 -0700844 CHECK(space1 != nullptr);
845 CHECK(space2 != nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800846 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700847 (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
848 stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700849}
850
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700851void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700852 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700853}
854
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700855void Heap::AddSpace(space::Space* space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700856 CHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700857 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
858 if (space->IsContinuousSpace()) {
859 DCHECK(!space->IsDiscontinuousSpace());
860 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
861 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700862 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
863 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700864 if (live_bitmap != nullptr) {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700865 CHECK(mark_bitmap != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700866 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
867 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700868 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700869 continuous_spaces_.push_back(continuous_space);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700870 // Ensure that spaces remain sorted in increasing order of start address.
871 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
872 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
873 return a->Begin() < b->Begin();
874 });
Mathieu Chartier590fee92013-09-13 13:46:47 -0700875 } else {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700876 CHECK(space->IsDiscontinuousSpace());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700877 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700878 live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
879 mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700880 discontinuous_spaces_.push_back(discontinuous_space);
881 }
882 if (space->IsAllocSpace()) {
883 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700884 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800885}
886
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700887void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
888 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
889 if (continuous_space->IsDlMallocSpace()) {
890 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
891 } else if (continuous_space->IsRosAllocSpace()) {
892 rosalloc_space_ = continuous_space->AsRosAllocSpace();
893 }
894}
895
896void Heap::RemoveSpace(space::Space* space) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800897 DCHECK(space != nullptr);
898 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
899 if (space->IsContinuousSpace()) {
900 DCHECK(!space->IsDiscontinuousSpace());
901 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
902 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700903 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
904 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800905 if (live_bitmap != nullptr) {
906 DCHECK(mark_bitmap != nullptr);
907 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
908 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
909 }
910 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
911 DCHECK(it != continuous_spaces_.end());
912 continuous_spaces_.erase(it);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800913 } else {
914 DCHECK(space->IsDiscontinuousSpace());
915 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700916 live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
917 mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800918 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
919 discontinuous_space);
920 DCHECK(it != discontinuous_spaces_.end());
921 discontinuous_spaces_.erase(it);
922 }
923 if (space->IsAllocSpace()) {
924 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
925 DCHECK(it != alloc_spaces_.end());
926 alloc_spaces_.erase(it);
927 }
928}
929
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700930void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700931 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700932 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700933 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800934 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800935 uint64_t total_paused_time = 0;
Mathieu Chartier5a487192014-04-08 11:14:54 -0700936 for (auto& collector : garbage_collectors_) {
Mathieu Chartier104fa0c2014-08-07 14:26:27 -0700937 total_duration += collector->GetCumulativeTimings().GetTotalNs();
938 total_paused_time += collector->GetTotalPausedTimeNs();
939 collector->DumpPerformanceInfo(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700940 }
Ian Rogers3e5cf302014-05-20 16:40:37 -0700941 uint64_t allocation_time =
942 static_cast<uint64_t>(total_allocation_time_.LoadRelaxed()) * kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700943 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700944 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700945 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
946 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700947 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700948 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700949 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700950 }
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700951 uint64_t total_objects_allocated = GetObjectsAllocatedEver();
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700952 os << "Total number of allocations " << total_objects_allocated << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700953 os << "Total bytes allocated " << PrettySize(GetBytesAllocatedEver()) << "\n";
954 os << "Total bytes freed " << PrettySize(GetBytesFreedEver()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700955 os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700956 os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
957 os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700958 os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
959 os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700960 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700961 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
962 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
963 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700964 }
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700965 if (HasZygoteSpace()) {
966 os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
967 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700968 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700969 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
970 os << "Total GC count: " << GetGcCount() << "\n";
971 os << "Total GC time: " << PrettyDuration(GetGcTime()) << "\n";
972 os << "Total blocking GC count: " << GetBlockingGcCount() << "\n";
973 os << "Total blocking GC time: " << PrettyDuration(GetBlockingGcTime()) << "\n";
974
975 {
976 MutexLock mu(Thread::Current(), *gc_complete_lock_);
977 if (gc_count_rate_histogram_.SampleSize() > 0U) {
978 os << "Histogram of GC count per " << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
979 gc_count_rate_histogram_.DumpBins(os);
980 os << "\n";
981 }
982 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
983 os << "Histogram of blocking GC count per "
984 << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
985 blocking_gc_count_rate_histogram_.DumpBins(os);
986 os << "\n";
987 }
988 }
989
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700990 BaseMutex::DumpAll(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700991}
992
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700993uint64_t Heap::GetGcCount() const {
994 uint64_t gc_count = 0U;
995 for (auto& collector : garbage_collectors_) {
996 gc_count += collector->GetCumulativeTimings().GetIterations();
997 }
998 return gc_count;
999}
1000
1001uint64_t Heap::GetGcTime() const {
1002 uint64_t gc_time = 0U;
1003 for (auto& collector : garbage_collectors_) {
1004 gc_time += collector->GetCumulativeTimings().GetTotalNs();
1005 }
1006 return gc_time;
1007}
1008
1009uint64_t Heap::GetBlockingGcCount() const {
1010 return blocking_gc_count_;
1011}
1012
1013uint64_t Heap::GetBlockingGcTime() const {
1014 return blocking_gc_time_;
1015}
1016
1017void Heap::DumpGcCountRateHistogram(std::ostream& os) const {
1018 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1019 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1020 gc_count_rate_histogram_.DumpBins(os);
1021 }
1022}
1023
1024void Heap::DumpBlockingGcCountRateHistogram(std::ostream& os) const {
1025 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1026 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1027 blocking_gc_count_rate_histogram_.DumpBins(os);
1028 }
1029}
1030
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001031Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001032 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001033 STLDeleteElements(&garbage_collectors_);
1034 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001035 allocation_stack_->Reset();
1036 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001037 STLDeleteValues(&mod_union_tables_);
Mathieu Chartier0767c9a2014-03-26 12:53:19 -07001038 STLDeleteValues(&remembered_sets_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001039 STLDeleteElements(&continuous_spaces_);
1040 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001041 delete gc_complete_lock_;
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001042 delete pending_task_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001043 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001044}
1045
Ian Rogers1d54e732013-05-02 21:10:01 -07001046space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
1047 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001048 for (const auto& space : continuous_spaces_) {
1049 if (space->Contains(obj)) {
1050 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001051 }
1052 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001053 if (!fail_ok) {
1054 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
1055 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001056 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001057}
1058
Ian Rogers1d54e732013-05-02 21:10:01 -07001059space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
1060 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001061 for (const auto& space : discontinuous_spaces_) {
1062 if (space->Contains(obj)) {
1063 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -07001064 }
1065 }
1066 if (!fail_ok) {
1067 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
1068 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001069 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001070}
1071
1072space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
1073 space::Space* result = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001074 if (result != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001075 return result;
1076 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001077 return FindDiscontinuousSpaceFromObject(obj, fail_ok);
Ian Rogers1d54e732013-05-02 21:10:01 -07001078}
1079
1080space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001081 for (const auto& space : continuous_spaces_) {
1082 if (space->IsImageSpace()) {
1083 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001084 }
1085 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001086 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001087}
1088
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001089void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001090 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001091 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001092 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001093 << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM";
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001094 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001095 if (total_bytes_free >= byte_count) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001096 space::AllocSpace* space = nullptr;
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001097 if (allocator_type == kAllocatorTypeNonMoving) {
1098 space = non_moving_space_;
1099 } else if (allocator_type == kAllocatorTypeRosAlloc ||
1100 allocator_type == kAllocatorTypeDlMalloc) {
1101 space = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -07001102 } else if (allocator_type == kAllocatorTypeBumpPointer ||
1103 allocator_type == kAllocatorTypeTLAB) {
1104 space = bump_pointer_space_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001105 } else if (allocator_type == kAllocatorTypeRegion ||
1106 allocator_type == kAllocatorTypeRegionTLAB) {
1107 space = region_space_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001108 }
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001109 if (space != nullptr) {
1110 space->LogFragmentationAllocFailure(oss, byte_count);
1111 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001112 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001113 self->ThrowOutOfMemoryError(oss.str().c_str());
1114}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001115
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001116void Heap::DoPendingCollectorTransition() {
1117 CollectorType desired_collector_type = desired_collector_type_;
Mathieu Chartierb2728552014-09-08 20:08:41 +00001118 // Launch homogeneous space compaction if it is desired.
1119 if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
1120 if (!CareAboutPauseTimes()) {
1121 PerformHomogeneousSpaceCompact();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001122 } else {
1123 VLOG(gc) << "Homogeneous compaction ignored due to jank perceptible process state";
Mathieu Chartierb2728552014-09-08 20:08:41 +00001124 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001125 } else {
1126 TransitionCollector(desired_collector_type);
Mathieu Chartierb2728552014-09-08 20:08:41 +00001127 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001128}
1129
1130void Heap::Trim(Thread* self) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001131 if (!CareAboutPauseTimes()) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001132 ATRACE_BEGIN("Deflating monitors");
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001133 // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
1134 // about pauses.
1135 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001136 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001137 uint64_t start_time = NanoTime();
1138 size_t count = runtime->GetMonitorList()->DeflateMonitors();
1139 VLOG(heap) << "Deflating " << count << " monitors took "
1140 << PrettyDuration(NanoTime() - start_time);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001141 runtime->GetThreadList()->ResumeAll();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001142 ATRACE_END();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001143 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001144 TrimIndirectReferenceTables(self);
1145 TrimSpaces(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001146}
1147
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001148class TrimIndirectReferenceTableClosure : public Closure {
1149 public:
1150 explicit TrimIndirectReferenceTableClosure(Barrier* barrier) : barrier_(barrier) {
1151 }
1152 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1153 ATRACE_BEGIN("Trimming reference table");
1154 thread->GetJniEnv()->locals.Trim();
1155 ATRACE_END();
Lei Lidd9943d2015-02-02 14:24:44 +08001156 // If thread is a running mutator, then act on behalf of the trim thread.
1157 // See the code in ThreadList::RunCheckpoint.
1158 if (thread->GetState() == kRunnable) {
1159 barrier_->Pass(Thread::Current());
1160 }
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001161 }
1162
1163 private:
1164 Barrier* const barrier_;
1165};
1166
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001167void Heap::TrimIndirectReferenceTables(Thread* self) {
1168 ScopedObjectAccess soa(self);
1169 ATRACE_BEGIN(__FUNCTION__);
1170 JavaVMExt* vm = soa.Vm();
1171 // Trim globals indirect reference table.
1172 vm->TrimGlobals();
1173 // Trim locals indirect reference tables.
1174 Barrier barrier(0);
1175 TrimIndirectReferenceTableClosure closure(&barrier);
1176 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1177 size_t barrier_count = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
Lei Lidd9943d2015-02-02 14:24:44 +08001178 if (barrier_count != 0) {
1179 barrier.Increment(self, barrier_count);
1180 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001181 ATRACE_END();
1182}
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001183
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001184void Heap::TrimSpaces(Thread* self) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001185 {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001186 // Need to do this before acquiring the locks since we don't want to get suspended while
1187 // holding any locks.
1188 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001189 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1190 // trimming.
1191 MutexLock mu(self, *gc_complete_lock_);
1192 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001193 WaitForGcToCompleteLocked(kGcCauseTrim, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001194 collector_type_running_ = kCollectorTypeHeapTrim;
1195 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001196 ATRACE_BEGIN(__FUNCTION__);
1197 const uint64_t start_ns = NanoTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001198 // Trim the managed spaces.
1199 uint64_t total_alloc_space_allocated = 0;
1200 uint64_t total_alloc_space_size = 0;
1201 uint64_t managed_reclaimed = 0;
1202 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001203 if (space->IsMallocSpace()) {
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001204 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1205 if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1206 // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1207 // for a long period of time.
1208 managed_reclaimed += malloc_space->Trim();
1209 }
1210 total_alloc_space_size += malloc_space->Size();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001211 }
1212 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001213 total_alloc_space_allocated = GetBytesAllocated();
1214 if (large_object_space_ != nullptr) {
1215 total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1216 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07001217 if (bump_pointer_space_ != nullptr) {
1218 total_alloc_space_allocated -= bump_pointer_space_->Size();
1219 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001220 if (region_space_ != nullptr) {
1221 total_alloc_space_allocated -= region_space_->GetBytesAllocated();
1222 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001223 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1224 static_cast<float>(total_alloc_space_size);
1225 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001226 // We never move things in the native heap, so we can finish the GC at this point.
1227 FinishGC(self, collector::kGcTypeNone);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001228 size_t native_reclaimed = 0;
Ian Rogers872dd822014-10-30 11:19:14 -07001229
1230#ifdef HAVE_ANDROID_OS
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001231 // Only trim the native heap if we don't care about pauses.
1232 if (!CareAboutPauseTimes()) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001233#if defined(USE_DLMALLOC)
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001234 // Trim the native heap.
1235 dlmalloc_trim(0);
1236 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001237#elif defined(USE_JEMALLOC)
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001238 // Jemalloc does it's own internal trimming.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001239#else
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001240 UNIMPLEMENTED(WARNING) << "Add trimming support";
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001241#endif
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001242 }
Ian Rogers872dd822014-10-30 11:19:14 -07001243#endif // HAVE_ANDROID_OS
Mathieu Chartier590fee92013-09-13 13:46:47 -07001244 uint64_t end_ns = NanoTime();
1245 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
1246 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
1247 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
1248 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
1249 << "%.";
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001250 ATRACE_END();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001251}
1252
1253bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
1254 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
1255 // taking the lock.
1256 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -07001257 return true;
1258 }
Mathieu Chartier15d34022014-02-26 17:16:38 -08001259 return IsAligned<kObjectAlignment>(obj) && FindSpaceFromObject(obj, true) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001260}
1261
Mathieu Chartierd68ac702014-02-11 14:50:51 -08001262bool Heap::IsNonDiscontinuousSpaceHeapAddress(const mirror::Object* obj) const {
1263 return FindContinuousSpaceFromObject(obj, true) != nullptr;
1264}
1265
Mathieu Chartier15d34022014-02-26 17:16:38 -08001266bool Heap::IsValidContinuousSpaceObjectAddress(const mirror::Object* obj) const {
1267 if (obj == nullptr || !IsAligned<kObjectAlignment>(obj)) {
1268 return false;
1269 }
1270 for (const auto& space : continuous_spaces_) {
1271 if (space->HasAddress(obj)) {
1272 return true;
1273 }
1274 }
1275 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -07001276}
1277
Ian Rogersef7d42f2014-01-06 12:55:46 -08001278bool Heap::IsLiveObjectLocked(mirror::Object* obj, bool search_allocation_stack,
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001279 bool search_live_stack, bool sorted) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001280 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
1281 return false;
1282 }
1283 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001284 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001285 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08001286 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001287 return true;
1288 }
1289 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1290 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001291 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1292 // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1293 return temp_space_->Contains(obj);
Ian Rogers1d54e732013-05-02 21:10:01 -07001294 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001295 if (region_space_ != nullptr && region_space_->HasAddress(obj)) {
1296 return true;
1297 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001298 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001299 space::DiscontinuousSpace* d_space = nullptr;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001300 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001301 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001302 return true;
1303 }
1304 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001305 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001306 if (d_space != nullptr) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001307 if (d_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001308 return true;
1309 }
1310 }
1311 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001312 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001313 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1314 if (i > 0) {
1315 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -07001316 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001317 if (search_allocation_stack) {
1318 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001319 if (allocation_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001320 return true;
1321 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001322 } else if (allocation_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001323 return true;
1324 }
1325 }
1326
1327 if (search_live_stack) {
1328 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001329 if (live_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001330 return true;
1331 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001332 } else if (live_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001333 return true;
1334 }
1335 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001336 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001337 // We need to check the bitmaps again since there is a race where we mark something as live and
1338 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001339 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001340 if (c_space->GetLiveBitmap()->Test(obj)) {
1341 return true;
1342 }
1343 } else {
1344 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001345 if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj)) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001346 return true;
1347 }
1348 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001349 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001350}
1351
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001352std::string Heap::DumpSpaces() const {
1353 std::ostringstream oss;
1354 DumpSpaces(oss);
1355 return oss.str();
1356}
1357
1358void Heap::DumpSpaces(std::ostream& stream) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001359 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001360 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1361 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001362 stream << space << " " << *space << "\n";
1363 if (live_bitmap != nullptr) {
1364 stream << live_bitmap << " " << *live_bitmap << "\n";
1365 }
1366 if (mark_bitmap != nullptr) {
1367 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1368 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001369 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001370 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001371 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001372 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001373}
1374
Ian Rogersef7d42f2014-01-06 12:55:46 -08001375void Heap::VerifyObjectBody(mirror::Object* obj) {
Stephen Hines22c6a812014-07-16 11:03:43 -07001376 if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1377 return;
1378 }
1379
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001380 // Ignore early dawn of the universe verifications.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001381 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.LoadRelaxed()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001382 return;
1383 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08001384 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001385 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
Mathieu Chartier4e305412014-02-19 10:54:44 -08001386 CHECK(c != nullptr) << "Null class in object " << obj;
1387 CHECK(IsAligned<kObjectAlignment>(c)) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001388 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001389
Mathieu Chartier4e305412014-02-19 10:54:44 -08001390 if (verify_object_mode_ > kVerifyObjectModeFast) {
1391 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001392 CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001393 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001394}
1395
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001396void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001397 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001398}
1399
1400void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001401 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001402 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001403}
1404
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001405void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
Mathieu Chartier601276a2014-03-20 15:12:30 -07001406 // Use signed comparison since freed bytes can be negative when background compaction foreground
1407 // transitions occurs. This is caused by the moving objects from a bump pointer space to a
1408 // free list backed space typically increasing memory footprint due to padding and binning.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001409 DCHECK_LE(freed_bytes, static_cast<int64_t>(num_bytes_allocated_.LoadRelaxed()));
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001410 // Note: This relies on 2s complement for handling negative freed_bytes.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001411 num_bytes_allocated_.FetchAndSubSequentiallyConsistent(static_cast<ssize_t>(freed_bytes));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001412 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001413 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001414 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001415 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001416 // TODO: Do this concurrently.
1417 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1418 global_stats->freed_objects += freed_objects;
1419 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001420 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001421}
1422
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001423void Heap::RecordFreeRevoke() {
1424 // Subtract num_bytes_freed_revoke_ from num_bytes_allocated_ to cancel out the
1425 // the ahead-of-time, bulk counting of bytes allocated in rosalloc thread-local buffers.
1426 // If there's a concurrent revoke, ok to not necessarily reset num_bytes_freed_revoke_
1427 // all the way to zero exactly as the remainder will be subtracted at the next GC.
1428 size_t bytes_freed = num_bytes_freed_revoke_.LoadSequentiallyConsistent();
1429 CHECK_GE(num_bytes_freed_revoke_.FetchAndSubSequentiallyConsistent(bytes_freed),
1430 bytes_freed) << "num_bytes_freed_revoke_ underflow";
1431 CHECK_GE(num_bytes_allocated_.FetchAndSubSequentiallyConsistent(bytes_freed),
1432 bytes_freed) << "num_bytes_allocated_ underflow";
1433 GetCurrentGcIteration()->SetFreedRevoke(bytes_freed);
1434}
1435
Zuo Wangf37a88b2014-07-10 04:26:41 -07001436space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
1437 for (const auto& space : continuous_spaces_) {
1438 if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1439 if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1440 return space->AsContinuousSpace()->AsRosAllocSpace();
1441 }
1442 }
1443 }
1444 return nullptr;
1445}
1446
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001447mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001448 size_t alloc_size, size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001449 size_t* usable_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001450 size_t* bytes_tl_bulk_allocated,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001451 mirror::Class** klass) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001452 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierf4f38432014-09-03 11:21:08 -07001453 // Make sure there is no pending exception since we may need to throw an OOME.
1454 self->AssertNoPendingException();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001455 DCHECK(klass != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001456 StackHandleScope<1> hs(self);
1457 HandleWrapper<mirror::Class> h(hs.NewHandleWrapper(klass));
1458 klass = nullptr; // Invalidate for safety.
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001459 // The allocation failed. If the GC is running, block until it completes, and then retry the
1460 // allocation.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001461 collector::GcType last_gc = WaitForGcToComplete(kGcCauseForAlloc, self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001462 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001463 // If we were the default allocator but the allocator changed while we were suspended,
1464 // abort the allocation.
1465 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001466 return nullptr;
1467 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001468 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001469 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001470 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001471 if (ptr != nullptr) {
1472 return ptr;
1473 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001474 }
1475
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001476 collector::GcType tried_type = next_gc_type_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001477 const bool gc_ran =
1478 CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1479 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1480 return nullptr;
1481 }
1482 if (gc_ran) {
1483 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001484 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001485 if (ptr != nullptr) {
1486 return ptr;
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001487 }
1488 }
1489
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001490 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001491 for (collector::GcType gc_type : gc_plan_) {
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001492 if (gc_type == tried_type) {
1493 continue;
1494 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001495 // Attempt to run the collector, if we succeed, re-try the allocation.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001496 const bool plan_gc_ran =
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001497 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1498 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001499 return nullptr;
1500 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001501 if (plan_gc_ran) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001502 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001503 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001504 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001505 if (ptr != nullptr) {
1506 return ptr;
1507 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001508 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001509 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001510 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001511 // Try harder, growing the heap if necessary.
1512 mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001513 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001514 if (ptr != nullptr) {
1515 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001516 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001517 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1518 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1519 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1520 // OOME.
1521 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1522 << " allocation";
1523 // TODO: Run finalization, but this may cause more allocations to occur.
1524 // We don't need a WaitForGcToComplete here either.
1525 DCHECK(!gc_plan_.empty());
1526 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
1527 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1528 return nullptr;
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001529 }
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001530 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size,
1531 bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001532 if (ptr == nullptr) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001533 const uint64_t current_time = NanoTime();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001534 switch (allocator) {
1535 case kAllocatorTypeRosAlloc:
1536 // Fall-through.
1537 case kAllocatorTypeDlMalloc: {
1538 if (use_homogeneous_space_compaction_for_oom_ &&
1539 current_time - last_time_homogeneous_space_compaction_by_oom_ >
1540 min_interval_homogeneous_space_compaction_by_oom_) {
1541 last_time_homogeneous_space_compaction_by_oom_ = current_time;
1542 HomogeneousSpaceCompactResult result = PerformHomogeneousSpaceCompact();
1543 switch (result) {
1544 case HomogeneousSpaceCompactResult::kSuccess:
1545 // If the allocation succeeded, we delayed an oom.
1546 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001547 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001548 if (ptr != nullptr) {
1549 count_delayed_oom_++;
1550 }
1551 break;
1552 case HomogeneousSpaceCompactResult::kErrorReject:
1553 // Reject due to disabled moving GC.
1554 break;
1555 case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1556 // Throw OOM by default.
1557 break;
1558 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07001559 UNIMPLEMENTED(FATAL) << "homogeneous space compaction result: "
1560 << static_cast<size_t>(result);
1561 UNREACHABLE();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001562 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001563 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001564 // Always print that we ran homogeneous space compation since this can cause jank.
1565 VLOG(heap) << "Ran heap homogeneous space compaction, "
1566 << " requested defragmentation "
1567 << count_requested_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1568 << " performed defragmentation "
1569 << count_performed_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1570 << " ignored homogeneous space compaction "
1571 << count_ignored_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1572 << " delayed count = "
1573 << count_delayed_oom_.LoadSequentiallyConsistent();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001574 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001575 break;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001576 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001577 case kAllocatorTypeNonMoving: {
1578 // Try to transition the heap if the allocation failure was due to the space being full.
1579 if (!IsOutOfMemoryOnAllocation<false>(allocator, alloc_size)) {
1580 // If we aren't out of memory then the OOM was probably from the non moving space being
1581 // full. Attempt to disable compaction and turn the main space into a non moving space.
1582 DisableMovingGc();
1583 // If we are still a moving GC then something must have caused the transition to fail.
1584 if (IsMovingGc(collector_type_)) {
1585 MutexLock mu(self, *gc_complete_lock_);
1586 // If we couldn't disable moving GC, just throw OOME and return null.
1587 LOG(WARNING) << "Couldn't disable moving GC with disable GC count "
1588 << disable_moving_gc_count_;
1589 } else {
1590 LOG(WARNING) << "Disabled moving GC due to the non moving space being full";
1591 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001592 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001593 }
1594 }
1595 break;
1596 }
1597 default: {
1598 // Do nothing for others allocators.
1599 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001600 }
1601 }
1602 // If the allocation hasn't succeeded by this point, throw an OOM error.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001603 if (ptr == nullptr) {
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001604 ThrowOutOfMemoryError(self, alloc_size, allocator);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001605 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001606 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001607}
1608
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001609void Heap::SetTargetHeapUtilization(float target) {
1610 DCHECK_GT(target, 0.0f); // asserted in Java code
1611 DCHECK_LT(target, 1.0f);
1612 target_utilization_ = target;
1613}
1614
Ian Rogers1d54e732013-05-02 21:10:01 -07001615size_t Heap::GetObjectsAllocated() const {
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001616 Thread* self = Thread::Current();
1617 ScopedThreadStateChange tsc(self, kWaitingForGetObjectsAllocated);
1618 auto* tl = Runtime::Current()->GetThreadList();
1619 // Need SuspendAll here to prevent lock violation if RosAlloc does it during InspectAll.
1620 tl->SuspendAll(__FUNCTION__);
Ian Rogers1d54e732013-05-02 21:10:01 -07001621 size_t total = 0;
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001622 {
1623 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1624 for (space::AllocSpace* space : alloc_spaces_) {
1625 total += space->GetObjectsAllocated();
1626 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001627 }
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001628 tl->ResumeAll();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001629 return total;
1630}
1631
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001632uint64_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier4edd8472015-06-01 10:47:36 -07001633 uint64_t total = GetObjectsFreedEver();
1634 // If we are detached, we can't use GetObjectsAllocated since we can't change thread states.
1635 if (Thread::Current() != nullptr) {
1636 total += GetObjectsAllocated();
1637 }
1638 return total;
Ian Rogers1d54e732013-05-02 21:10:01 -07001639}
1640
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001641uint64_t Heap::GetBytesAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001642 return GetBytesFreedEver() + GetBytesAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001643}
1644
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001645class InstanceCounter {
1646 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001647 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001648 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001649 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001650 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001651 static void Callback(mirror::Object* obj, void* arg)
1652 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1653 InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1654 mirror::Class* instance_class = obj->GetClass();
1655 CHECK(instance_class != nullptr);
1656 for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
1657 if (instance_counter->use_is_assignable_from_) {
1658 if (instance_counter->classes_[i]->IsAssignableFrom(instance_class)) {
1659 ++instance_counter->counts_[i];
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001660 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001661 } else if (instance_class == instance_counter->classes_[i]) {
1662 ++instance_counter->counts_[i];
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001663 }
1664 }
1665 }
1666
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001667 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001668 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001669 bool use_is_assignable_from_;
1670 uint64_t* const counts_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001671 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001672};
1673
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001674void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001675 uint64_t* counts) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001676 InstanceCounter counter(classes, use_is_assignable_from, counts);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001677 VisitObjects(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001678}
1679
Elliott Hughes3b78c942013-01-15 17:35:41 -08001680class InstanceCollector {
1681 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001682 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001683 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1684 : class_(c), max_count_(max_count), instances_(instances) {
1685 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001686 static void Callback(mirror::Object* obj, void* arg)
1687 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1688 DCHECK(arg != nullptr);
1689 InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001690 if (obj->GetClass() == instance_collector->class_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001691 if (instance_collector->max_count_ == 0 ||
1692 instance_collector->instances_.size() < instance_collector->max_count_) {
1693 instance_collector->instances_.push_back(obj);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001694 }
1695 }
1696 }
1697
1698 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001699 const mirror::Class* const class_;
1700 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001701 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001702 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1703};
1704
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001705void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1706 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001707 InstanceCollector collector(c, max_count, instances);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001708 VisitObjects(&InstanceCollector::Callback, &collector);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001709}
1710
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001711class ReferringObjectsFinder {
1712 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001713 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1714 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001715 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1716 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1717 }
1718
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001719 static void Callback(mirror::Object* obj, void* arg)
1720 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1721 reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1722 }
1723
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001724 // For bitmap Visit.
1725 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1726 // annotalysis on visitors.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001727 void operator()(mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001728 o->VisitReferences<true>(*this, VoidFunctor());
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001729 }
1730
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001731 // For Object::VisitReferences.
Mathieu Chartier407f7022014-02-18 14:37:05 -08001732 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1733 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001734 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08001735 if (ref == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1736 referring_objects_.push_back(obj);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001737 }
1738 }
1739
1740 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001741 const mirror::Object* const object_;
1742 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001743 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001744 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1745};
1746
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001747void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1748 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001749 ReferringObjectsFinder finder(o, max_count, referring_objects);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001750 VisitObjects(&ReferringObjectsFinder::Callback, &finder);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001751}
1752
Ian Rogers30fab402012-01-23 15:43:46 -08001753void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001754 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1755 // last GC will not have necessarily been cleared.
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001756 CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001757}
1758
Zuo Wangf37a88b2014-07-10 04:26:41 -07001759HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
1760 Thread* self = Thread::Current();
1761 // Inc requested homogeneous space compaction.
1762 count_requested_homogeneous_space_compaction_++;
1763 // Store performed homogeneous space compaction at a new request arrival.
1764 ThreadList* tl = Runtime::Current()->GetThreadList();
1765 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1766 Locks::mutator_lock_->AssertNotHeld(self);
1767 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001768 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001769 MutexLock mu(self, *gc_complete_lock_);
1770 // Ensure there is only one GC at a time.
1771 WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
1772 // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable count
1773 // is non zero.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001774 // If the collector type changed to something which doesn't benefit from homogeneous space compaction,
Zuo Wangf37a88b2014-07-10 04:26:41 -07001775 // exit.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001776 if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
1777 !main_space_->CanMoveObjects()) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001778 return HomogeneousSpaceCompactResult::kErrorReject;
1779 }
1780 collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
1781 }
1782 if (Runtime::Current()->IsShuttingDown(self)) {
1783 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1784 // cause objects to get finalized.
1785 FinishGC(self, collector::kGcTypeNone);
1786 return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
1787 }
1788 // Suspend all threads.
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001789 tl->SuspendAll(__FUNCTION__);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001790 uint64_t start_time = NanoTime();
1791 // Launch compaction.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001792 space::MallocSpace* to_space = main_space_backup_.release();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001793 space::MallocSpace* from_space = main_space_;
1794 to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1795 const uint64_t space_size_before_compaction = from_space->Size();
Mathieu Chartierb363f662014-07-16 13:28:58 -07001796 AddSpace(to_space);
Mathieu Chartier0310da52014-12-01 13:40:48 -08001797 // Make sure that we will have enough room to copy.
1798 CHECK_GE(to_space->GetFootprintLimit(), from_space->GetFootprintLimit());
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001799 collector::GarbageCollector* collector = Compact(to_space, from_space,
1800 kGcCauseHomogeneousSpaceCompact);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001801 const uint64_t space_size_after_compaction = to_space->Size();
Mathieu Chartierb363f662014-07-16 13:28:58 -07001802 main_space_ = to_space;
1803 main_space_backup_.reset(from_space);
1804 RemoveSpace(from_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001805 SetSpaceAsDefault(main_space_); // Set as default to reset the proper dlmalloc space.
1806 // Update performed homogeneous space compaction count.
1807 count_performed_homogeneous_space_compaction_++;
1808 // Print statics log and resume all threads.
1809 uint64_t duration = NanoTime() - start_time;
Mathieu Chartier98172a62014-09-02 12:33:25 -07001810 VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
1811 << PrettySize(space_size_before_compaction) << " -> "
1812 << PrettySize(space_size_after_compaction) << " compact-ratio: "
1813 << std::fixed << static_cast<double>(space_size_after_compaction) /
1814 static_cast<double>(space_size_before_compaction);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001815 tl->ResumeAll();
1816 // Finish GC.
1817 reference_processor_.EnqueueClearedReferences(self);
1818 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001819 LogGC(kGcCauseHomogeneousSpaceCompact, collector);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001820 FinishGC(self, collector::kGcTypeFull);
1821 return HomogeneousSpaceCompactResult::kSuccess;
1822}
1823
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001824void Heap::TransitionCollector(CollectorType collector_type) {
1825 if (collector_type == collector_type_) {
1826 return;
1827 }
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001828 VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1829 << " -> " << static_cast<int>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001830 uint64_t start_time = NanoTime();
Ian Rogers3e5cf302014-05-20 16:40:37 -07001831 uint32_t before_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001832 Runtime* const runtime = Runtime::Current();
1833 ThreadList* const tl = runtime->GetThreadList();
1834 Thread* const self = Thread::Current();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001835 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1836 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001837 // Busy wait until we can GC (StartGC can fail if we have a non-zero
1838 // compacting_gc_disable_count_, this should rarely occurs).
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001839 for (;;) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001840 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001841 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001842 MutexLock mu(self, *gc_complete_lock_);
1843 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001844 WaitForGcToCompleteLocked(kGcCauseCollectorTransition, self);
Mathieu Chartiere4927f62014-08-23 13:56:03 -07001845 // Currently we only need a heap transition if we switch from a moving collector to a
1846 // non-moving one, or visa versa.
1847 const bool copying_transition = IsMovingGc(collector_type_) != IsMovingGc(collector_type);
Mathieu Chartierb38d4832014-04-10 10:56:55 -07001848 // If someone else beat us to it and changed the collector before we could, exit.
1849 // This is safe to do before the suspend all since we set the collector_type_running_ before
1850 // we exit the loop. If another thread attempts to do the heap transition before we exit,
1851 // then it would get blocked on WaitForGcToCompleteLocked.
1852 if (collector_type == collector_type_) {
1853 return;
1854 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001855 // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1856 if (!copying_transition || disable_moving_gc_count_ == 0) {
1857 // TODO: Not hard code in semi-space collector?
1858 collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1859 break;
1860 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001861 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001862 usleep(1000);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001863 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001864 if (runtime->IsShuttingDown(self)) {
Hiroshi Yamauchia6a8d142014-05-12 16:57:33 -07001865 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1866 // cause objects to get finalized.
1867 FinishGC(self, collector::kGcTypeNone);
1868 return;
1869 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001870 collector::GarbageCollector* collector = nullptr;
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001871 tl->SuspendAll(__FUNCTION__);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001872 switch (collector_type) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001873 case kCollectorTypeSS: {
Mathieu Chartier31f44142014-04-08 14:40:03 -07001874 if (!IsMovingGc(collector_type_)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001875 // Create the bump pointer space from the backup space.
1876 CHECK(main_space_backup_ != nullptr);
1877 std::unique_ptr<MemMap> mem_map(main_space_backup_->ReleaseMemMap());
Mathieu Chartier31f44142014-04-08 14:40:03 -07001878 // We are transitioning from non moving GC -> moving GC, since we copied from the bump
1879 // pointer space last transition it will be protected.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001880 CHECK(mem_map != nullptr);
1881 mem_map->Protect(PROT_READ | PROT_WRITE);
1882 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space",
1883 mem_map.release());
1884 AddSpace(bump_pointer_space_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001885 collector = Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001886 // Use the now empty main space mem map for the bump pointer temp space.
1887 mem_map.reset(main_space_->ReleaseMemMap());
Mathieu Chartier00b59152014-07-25 10:13:51 -07001888 // Unset the pointers just in case.
1889 if (dlmalloc_space_ == main_space_) {
1890 dlmalloc_space_ = nullptr;
1891 } else if (rosalloc_space_ == main_space_) {
1892 rosalloc_space_ = nullptr;
1893 }
Mathieu Chartier2796a162014-07-25 11:50:47 -07001894 // Remove the main space so that we don't try to trim it, this doens't work for debug
1895 // builds since RosAlloc attempts to read the magic number from a protected page.
1896 RemoveSpace(main_space_);
Mathieu Chartierc5a83472014-07-23 18:45:17 -07001897 RemoveRememberedSet(main_space_);
Mathieu Chartier2796a162014-07-25 11:50:47 -07001898 delete main_space_; // Delete the space since it has been removed.
Mathieu Chartierc5a83472014-07-23 18:45:17 -07001899 main_space_ = nullptr;
Mathieu Chartier2796a162014-07-25 11:50:47 -07001900 RemoveRememberedSet(main_space_backup_.get());
1901 main_space_backup_.reset(nullptr); // Deletes the space.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001902 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
1903 mem_map.release());
1904 AddSpace(temp_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07001905 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001906 break;
1907 }
1908 case kCollectorTypeMS:
1909 // Fall through.
1910 case kCollectorTypeCMS: {
Mathieu Chartier31f44142014-04-08 14:40:03 -07001911 if (IsMovingGc(collector_type_)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001912 CHECK(temp_space_ != nullptr);
1913 std::unique_ptr<MemMap> mem_map(temp_space_->ReleaseMemMap());
1914 RemoveSpace(temp_space_);
1915 temp_space_ = nullptr;
Mathieu Chartier36dab362014-07-30 14:59:56 -07001916 mem_map->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier0310da52014-12-01 13:40:48 -08001917 CreateMainMallocSpace(mem_map.get(), kDefaultInitialSize,
1918 std::min(mem_map->Size(), growth_limit_), mem_map->Size());
Mathieu Chartierb363f662014-07-16 13:28:58 -07001919 mem_map.release();
Mathieu Chartier31f44142014-04-08 14:40:03 -07001920 // Compact to the main space from the bump pointer space, don't need to swap semispaces.
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001921 AddSpace(main_space_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001922 collector = Compact(main_space_, bump_pointer_space_, kGcCauseCollectorTransition);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001923 mem_map.reset(bump_pointer_space_->ReleaseMemMap());
1924 RemoveSpace(bump_pointer_space_);
1925 bump_pointer_space_ = nullptr;
1926 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07001927 // Temporarily unprotect the backup mem map so rosalloc can write the debug magic number.
1928 if (kIsDebugBuild && kUseRosAlloc) {
1929 mem_map->Protect(PROT_READ | PROT_WRITE);
1930 }
Mathieu Chartier0310da52014-12-01 13:40:48 -08001931 main_space_backup_.reset(CreateMallocSpaceFromMemMap(
1932 mem_map.get(), kDefaultInitialSize, std::min(mem_map->Size(), growth_limit_),
1933 mem_map->Size(), name, true));
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07001934 if (kIsDebugBuild && kUseRosAlloc) {
1935 mem_map->Protect(PROT_NONE);
1936 }
Mathieu Chartierb363f662014-07-16 13:28:58 -07001937 mem_map.release();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001938 }
1939 break;
1940 }
1941 default: {
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001942 LOG(FATAL) << "Attempted to transition to invalid collector type "
1943 << static_cast<size_t>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001944 break;
1945 }
1946 }
1947 ChangeCollector(collector_type);
1948 tl->ResumeAll();
1949 // Can't call into java code with all threads suspended.
Mathieu Chartier308351a2014-06-15 12:39:02 -07001950 reference_processor_.EnqueueClearedReferences(self);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001951 uint64_t duration = NanoTime() - start_time;
Mathieu Chartierafe49982014-03-27 10:55:04 -07001952 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001953 DCHECK(collector != nullptr);
1954 LogGC(kGcCauseCollectorTransition, collector);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001955 FinishGC(self, collector::kGcTypeFull);
Ian Rogers3e5cf302014-05-20 16:40:37 -07001956 int32_t after_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001957 int32_t delta_allocated = before_allocated - after_allocated;
Mathieu Chartier19d46b42014-06-17 15:04:40 -07001958 std::string saved_str;
1959 if (delta_allocated >= 0) {
1960 saved_str = " saved at least " + PrettySize(delta_allocated);
1961 } else {
1962 saved_str = " expanded " + PrettySize(-delta_allocated);
1963 }
Mathieu Chartier98172a62014-09-02 12:33:25 -07001964 VLOG(heap) << "Heap transition to " << process_state_ << " took "
Mathieu Chartier19d46b42014-06-17 15:04:40 -07001965 << PrettyDuration(duration) << saved_str;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001966}
1967
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001968void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001969 // TODO: Only do this with all mutators suspended to avoid races.
1970 if (collector_type != collector_type_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001971 if (collector_type == kCollectorTypeMC) {
1972 // Don't allow mark compact unless support is compiled in.
1973 CHECK(kMarkCompactSupport);
1974 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001975 collector_type_ = collector_type;
1976 gc_plan_.clear();
1977 switch (collector_type_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001978 case kCollectorTypeCC: {
1979 gc_plan_.push_back(collector::kGcTypeFull);
1980 if (use_tlab_) {
1981 ChangeAllocator(kAllocatorTypeRegionTLAB);
1982 } else {
1983 ChangeAllocator(kAllocatorTypeRegion);
1984 }
1985 break;
1986 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001987 case kCollectorTypeMC: // Fall-through.
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07001988 case kCollectorTypeSS: // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001989 case kCollectorTypeGSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001990 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001991 if (use_tlab_) {
1992 ChangeAllocator(kAllocatorTypeTLAB);
1993 } else {
1994 ChangeAllocator(kAllocatorTypeBumpPointer);
1995 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001996 break;
1997 }
1998 case kCollectorTypeMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001999 gc_plan_.push_back(collector::kGcTypeSticky);
2000 gc_plan_.push_back(collector::kGcTypePartial);
2001 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002002 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002003 break;
2004 }
2005 case kCollectorTypeCMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002006 gc_plan_.push_back(collector::kGcTypeSticky);
2007 gc_plan_.push_back(collector::kGcTypePartial);
2008 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002009 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002010 break;
2011 }
2012 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07002013 UNIMPLEMENTED(FATAL);
2014 UNREACHABLE();
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002015 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002016 }
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002017 if (IsGcConcurrent()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002018 concurrent_start_bytes_ =
2019 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
2020 } else {
2021 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002022 }
2023 }
2024}
2025
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002026// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Ian Rogers6fac4472014-02-25 17:01:10 -08002027class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002028 public:
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002029 explicit ZygoteCompactingCollector(gc::Heap* heap) : SemiSpace(heap, false, "zygote collector"),
Ian Rogers6fac4472014-02-25 17:01:10 -08002030 bin_live_bitmap_(nullptr), bin_mark_bitmap_(nullptr) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002031 }
2032
2033 void BuildBins(space::ContinuousSpace* space) {
2034 bin_live_bitmap_ = space->GetLiveBitmap();
2035 bin_mark_bitmap_ = space->GetMarkBitmap();
2036 BinContext context;
2037 context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
2038 context.collector_ = this;
2039 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2040 // Note: This requires traversing the space in increasing order of object addresses.
2041 bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
2042 // Add the last bin which spans after the last object to the end of the space.
2043 AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
2044 }
2045
2046 private:
2047 struct BinContext {
2048 uintptr_t prev_; // The end of the previous object.
2049 ZygoteCompactingCollector* collector_;
2050 };
2051 // Maps from bin sizes to locations.
2052 std::multimap<size_t, uintptr_t> bins_;
2053 // Live bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002054 accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002055 // Mark bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002056 accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002057
2058 static void Callback(mirror::Object* obj, void* arg)
2059 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2060 DCHECK(arg != nullptr);
2061 BinContext* context = reinterpret_cast<BinContext*>(arg);
2062 ZygoteCompactingCollector* collector = context->collector_;
2063 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
2064 size_t bin_size = object_addr - context->prev_;
2065 // Add the bin consisting of the end of the previous object to the start of the current object.
2066 collector->AddBin(bin_size, context->prev_);
2067 context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
2068 }
2069
2070 void AddBin(size_t size, uintptr_t position) {
2071 if (size != 0) {
2072 bins_.insert(std::make_pair(size, position));
2073 }
2074 }
2075
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002076 virtual bool ShouldSweepSpace(space::ContinuousSpace* space) const {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002077 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
2078 // allocator.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002079 UNUSED(space);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002080 return false;
2081 }
2082
2083 virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
2084 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002085 size_t obj_size = obj->SizeOf();
2086 size_t alloc_size = RoundUp(obj_size, kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08002087 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002088 // Find the smallest bin which we can move obj in.
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002089 auto it = bins_.lower_bound(alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002090 if (it == bins_.end()) {
2091 // No available space in the bins, place it in the target space instead (grows the zygote
2092 // space).
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002093 size_t bytes_allocated, dummy;
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002094 forward_address = to_space_->Alloc(self_, alloc_size, &bytes_allocated, nullptr, &dummy);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002095 if (to_space_live_bitmap_ != nullptr) {
2096 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002097 } else {
2098 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
2099 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002100 }
2101 } else {
2102 size_t size = it->first;
2103 uintptr_t pos = it->second;
2104 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
2105 forward_address = reinterpret_cast<mirror::Object*>(pos);
2106 // Set the live and mark bits so that sweeping system weaks works properly.
2107 bin_live_bitmap_->Set(forward_address);
2108 bin_mark_bitmap_->Set(forward_address);
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002109 DCHECK_GE(size, alloc_size);
2110 // Add a new bin with the remaining space.
2111 AddBin(size - alloc_size, pos + alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002112 }
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002113 // Copy the object over to its new location. Don't use alloc_size to avoid valgrind error.
2114 memcpy(reinterpret_cast<void*>(forward_address), obj, obj_size);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002115 if (kUseBakerOrBrooksReadBarrier) {
2116 obj->AssertReadBarrierPointer();
2117 if (kUseBrooksReadBarrier) {
2118 DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
2119 forward_address->SetReadBarrierPointer(forward_address);
2120 }
2121 forward_address->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002122 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002123 return forward_address;
2124 }
2125};
2126
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002127void Heap::UnBindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002128 TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002129 for (const auto& space : GetContinuousSpaces()) {
2130 if (space->IsContinuousMemMapAllocSpace()) {
2131 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2132 if (alloc_space->HasBoundBitmaps()) {
2133 alloc_space->UnBindBitmaps();
2134 }
2135 }
2136 }
2137}
2138
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002139void Heap::PreZygoteFork() {
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002140 if (!HasZygoteSpace()) {
2141 // We still want to GC in case there is some unreachable non moving objects that could cause a
2142 // suboptimal bin packing when we compact the zygote space.
2143 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
2144 }
Ian Rogers81d425b2012-09-27 16:03:43 -07002145 Thread* self = Thread::Current();
2146 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002147 // Try to see if we have any Zygote spaces.
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002148 if (HasZygoteSpace()) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002149 return;
2150 }
Mathieu Chartiereb175f72014-10-31 11:49:27 -07002151 Runtime::Current()->GetInternTable()->SwapPostZygoteWithPreZygote();
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002152 Runtime::Current()->GetClassLinker()->MoveClassTableToPreZygote();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002153 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier590fee92013-09-13 13:46:47 -07002154 // Trim the pages at the end of the non moving space.
2155 non_moving_space_->Trim();
Mathieu Chartier31f44142014-04-08 14:40:03 -07002156 // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
2157 // there.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002158 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002159 const bool same_space = non_moving_space_ == main_space_;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002160 if (kCompactZygote) {
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002161 // Temporarily disable rosalloc verification because the zygote
2162 // compaction will mess up the rosalloc internal metadata.
2163 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002164 ZygoteCompactingCollector zygote_collector(this);
2165 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08002166 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002167 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
2168 non_moving_space_->Limit());
2169 // Compact the bump pointer space to a new zygote bump pointer space.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002170 bool reset_main_space = false;
2171 if (IsMovingGc(collector_type_)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002172 if (collector_type_ == kCollectorTypeCC) {
2173 zygote_collector.SetFromSpace(region_space_);
2174 } else {
2175 zygote_collector.SetFromSpace(bump_pointer_space_);
2176 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002177 } else {
2178 CHECK(main_space_ != nullptr);
Hiroshi Yamauchid04495e2015-03-11 19:09:07 -07002179 CHECK_NE(main_space_, non_moving_space_)
2180 << "Does not make sense to compact within the same space";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002181 // Copy from the main space.
2182 zygote_collector.SetFromSpace(main_space_);
2183 reset_main_space = true;
2184 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002185 zygote_collector.SetToSpace(&target_space);
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07002186 zygote_collector.SetSwapSemiSpaces(false);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002187 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002188 if (reset_main_space) {
2189 main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2190 madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
2191 MemMap* mem_map = main_space_->ReleaseMemMap();
2192 RemoveSpace(main_space_);
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002193 space::Space* old_main_space = main_space_;
Mathieu Chartier0310da52014-12-01 13:40:48 -08002194 CreateMainMallocSpace(mem_map, kDefaultInitialSize, std::min(mem_map->Size(), growth_limit_),
2195 mem_map->Size());
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002196 delete old_main_space;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002197 AddSpace(main_space_);
2198 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002199 if (collector_type_ == kCollectorTypeCC) {
2200 region_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2201 } else {
2202 bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2203 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002204 }
2205 if (temp_space_ != nullptr) {
2206 CHECK(temp_space_->IsEmpty());
2207 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002208 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2209 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002210 // Update the end and write out image.
2211 non_moving_space_->SetEnd(target_space.End());
2212 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002213 VLOG(heap) << "Create zygote space with size=" << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002214 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002215 // Change the collector to the post zygote one.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002216 ChangeCollector(foreground_collector_type_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002217 // Save the old space so that we can remove it after we complete creating the zygote space.
2218 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002219 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002220 // the remaining available space.
2221 // Remove the old space before creating the zygote space since creating the zygote space sets
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002222 // the old alloc space's bitmaps to null.
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002223 RemoveSpace(old_alloc_space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002224 if (collector::SemiSpace::kUseRememberedSet) {
2225 // Sanity bound check.
2226 FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
2227 // Remove the remembered set for the now zygote space (the old
2228 // non-moving space). Note now that we have compacted objects into
2229 // the zygote space, the data in the remembered set is no longer
2230 // needed. The zygote space will instead have a mod-union table
2231 // from this point on.
2232 RemoveRememberedSet(old_alloc_space);
2233 }
Mathieu Chartier7247af52014-11-19 10:51:42 -08002234 // Remaining space becomes the new non moving space.
2235 zygote_space_ = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName, low_memory_mode_,
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002236 &non_moving_space_);
Mathieu Chartierb363f662014-07-16 13:28:58 -07002237 CHECK(!non_moving_space_->CanMoveObjects());
2238 if (same_space) {
2239 main_space_ = non_moving_space_;
2240 SetSpaceAsDefault(main_space_);
2241 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002242 delete old_alloc_space;
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002243 CHECK(HasZygoteSpace()) << "Failed creating zygote space";
2244 AddSpace(zygote_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002245 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2246 AddSpace(non_moving_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002247 // Create the zygote space mod union table.
2248 accounting::ModUnionTable* mod_union_table =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002249 new accounting::ModUnionTableCardCache("zygote space mod-union table", this,
2250 zygote_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002251 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002252 // Set all the cards in the mod-union table since we don't know which objects contain references
2253 // to large objects.
2254 mod_union_table->SetCards();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002255 AddModUnionTable(mod_union_table);
Mathieu Chartierf6c2a272015-06-03 17:32:42 -07002256 large_object_space_->SetAllLargeObjectsAsZygoteObjects(self);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002257 if (collector::SemiSpace::kUseRememberedSet) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002258 // Add a new remembered set for the post-zygote non-moving space.
2259 accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2260 new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2261 non_moving_space_);
2262 CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2263 << "Failed to create post-zygote non-moving space remembered set";
2264 AddRememberedSet(post_zygote_non_moving_space_rem_set);
2265 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002266}
2267
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002268void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002269 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002270 allocation_stack_->Reset();
2271}
2272
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002273void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2274 accounting::ContinuousSpaceBitmap* bitmap2,
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07002275 accounting::LargeObjectBitmap* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07002276 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002277 DCHECK(bitmap1 != nullptr);
2278 DCHECK(bitmap2 != nullptr);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002279 const auto* limit = stack->End();
2280 for (auto* it = stack->Begin(); it != limit; ++it) {
2281 const mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002282 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2283 if (bitmap1->HasAddress(obj)) {
2284 bitmap1->Set(obj);
2285 } else if (bitmap2->HasAddress(obj)) {
2286 bitmap2->Set(obj);
2287 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07002288 DCHECK(large_objects != nullptr);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002289 large_objects->Set(obj);
2290 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07002291 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002292 }
2293}
2294
Mathieu Chartier590fee92013-09-13 13:46:47 -07002295void Heap::SwapSemiSpaces() {
Mathieu Chartier31f44142014-04-08 14:40:03 -07002296 CHECK(bump_pointer_space_ != nullptr);
2297 CHECK(temp_space_ != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002298 std::swap(bump_pointer_space_, temp_space_);
2299}
2300
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002301collector::GarbageCollector* Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2302 space::ContinuousMemMapAllocSpace* source_space,
2303 GcCause gc_cause) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002304 CHECK(kMovingCollector);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002305 if (target_space != source_space) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002306 // Don't swap spaces since this isn't a typical semi space collection.
2307 semi_space_collector_->SetSwapSemiSpaces(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002308 semi_space_collector_->SetFromSpace(source_space);
2309 semi_space_collector_->SetToSpace(target_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002310 semi_space_collector_->Run(gc_cause, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002311 return semi_space_collector_;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002312 } else {
2313 CHECK(target_space->IsBumpPointerSpace())
2314 << "In-place compaction is only supported for bump pointer spaces";
2315 mark_compact_collector_->SetSpace(target_space->AsBumpPointerSpace());
2316 mark_compact_collector_->Run(kGcCauseCollectorTransition, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002317 return mark_compact_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002318 }
2319}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002320
Ian Rogers1d54e732013-05-02 21:10:01 -07002321collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
2322 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002323 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002324 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002325 // If the heap can't run the GC, silently fail and return that no GC was run.
2326 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002327 case collector::kGcTypePartial: {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002328 if (!HasZygoteSpace()) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002329 return collector::kGcTypeNone;
2330 }
2331 break;
2332 }
2333 default: {
2334 // Other GC types don't have any special cases which makes them not runnable. The main case
2335 // here is full GC.
2336 }
2337 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002338 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07002339 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002340 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier50c138f2015-01-07 16:00:03 -08002341 // If we are throwing a stack overflow error we probably don't have enough remaining stack
2342 // space to run the GC.
2343 return collector::kGcTypeNone;
Ian Rogers120f1c72012-09-28 17:17:10 -07002344 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002345 bool compacting_gc;
2346 {
2347 gc_complete_lock_->AssertNotHeld(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002348 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002349 MutexLock mu(self, *gc_complete_lock_);
2350 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002351 WaitForGcToCompleteLocked(gc_cause, self);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002352 compacting_gc = IsMovingGc(collector_type_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002353 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2354 if (compacting_gc && disable_moving_gc_count_ != 0) {
2355 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2356 return collector::kGcTypeNone;
2357 }
2358 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002359 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002360 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2361 ++runtime->GetStats()->gc_for_alloc_count;
2362 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002363 }
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002364 const uint64_t bytes_allocated_before_gc = GetBytesAllocated();
2365 // Approximate heap size.
2366 ATRACE_INT("Heap size (KB)", bytes_allocated_before_gc / KB);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002367
Ian Rogers1d54e732013-05-02 21:10:01 -07002368 DCHECK_LT(gc_type, collector::kGcTypeMax);
2369 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002370
Mathieu Chartier590fee92013-09-13 13:46:47 -07002371 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08002372 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002373 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002374 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002375 current_allocator_ == kAllocatorTypeTLAB ||
2376 current_allocator_ == kAllocatorTypeRegion ||
2377 current_allocator_ == kAllocatorTypeRegionTLAB);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002378 switch (collector_type_) {
2379 case kCollectorTypeSS:
2380 // Fall-through.
2381 case kCollectorTypeGSS:
2382 semi_space_collector_->SetFromSpace(bump_pointer_space_);
2383 semi_space_collector_->SetToSpace(temp_space_);
2384 semi_space_collector_->SetSwapSemiSpaces(true);
2385 collector = semi_space_collector_;
2386 break;
2387 case kCollectorTypeCC:
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002388 concurrent_copying_collector_->SetRegionSpace(region_space_);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002389 collector = concurrent_copying_collector_;
2390 break;
2391 case kCollectorTypeMC:
2392 mark_compact_collector_->SetSpace(bump_pointer_space_);
2393 collector = mark_compact_collector_;
2394 break;
2395 default:
2396 LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002397 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002398 if (collector != mark_compact_collector_ && collector != concurrent_copying_collector_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002399 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2400 CHECK(temp_space_->IsEmpty());
2401 }
2402 gc_type = collector::kGcTypeFull; // TODO: Not hard code this in.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002403 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2404 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002405 collector = FindCollectorByGcType(gc_type);
Mathieu Chartier50482232013-11-21 11:48:14 -08002406 } else {
2407 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002408 }
Mathieu Chartier08cef222014-10-22 17:18:34 -07002409 if (IsGcConcurrent()) {
2410 // Disable concurrent GC check so that we don't have spammy JNI requests.
2411 // This gets recalculated in GrowForUtilization. It is important that it is disabled /
2412 // calculated in the same thread so that there aren't any races that can cause it to become
2413 // permanantly disabled. b/17942071
2414 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2415 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002416 CHECK(collector != nullptr)
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002417 << "Could not find garbage collector with collector_type="
2418 << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002419 collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002420 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2421 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08002422 RequestTrim(self);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002423 // Enqueue cleared references.
Mathieu Chartier308351a2014-06-15 12:39:02 -07002424 reference_processor_.EnqueueClearedReferences(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002425 // Grow the heap so that we know when to perform the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002426 GrowForUtilization(collector, bytes_allocated_before_gc);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002427 LogGC(gc_cause, collector);
2428 FinishGC(self, gc_type);
2429 // Inform DDMS that a GC completed.
2430 Dbg::GcDidFinish();
2431 return gc_type;
2432}
2433
2434void Heap::LogGC(GcCause gc_cause, collector::GarbageCollector* collector) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002435 const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2436 const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002437 // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002438 // (mutator time blocked >= long_pause_log_threshold_).
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002439 bool log_gc = gc_cause == kGcCauseExplicit;
2440 if (!log_gc && CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002441 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002442 log_gc = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002443 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002444 for (uint64_t pause : pause_times) {
2445 log_gc = log_gc || pause >= long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002446 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002447 }
2448 if (log_gc) {
2449 const size_t percent_free = GetPercentFree();
2450 const size_t current_heap_size = GetBytesAllocated();
2451 const size_t total_memory = GetTotalMemory();
2452 std::ostringstream pause_string;
2453 for (size_t i = 0; i < pause_times.size(); ++i) {
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002454 pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2455 << ((i != pause_times.size() - 1) ? "," : "");
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002456 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002457 LOG(INFO) << gc_cause << " " << collector->GetName()
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002458 << " GC freed " << current_gc_iteration_.GetFreedObjects() << "("
2459 << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2460 << current_gc_iteration_.GetFreedLargeObjects() << "("
2461 << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002462 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2463 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2464 << " total " << PrettyDuration((duration / 1000) * 1000);
Ian Rogersc7dd2952014-10-21 23:31:19 -07002465 VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002466 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002467}
Mathieu Chartiera6399032012-06-11 18:49:50 -07002468
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002469void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2470 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002471 collector_type_running_ = kCollectorTypeNone;
2472 if (gc_type != collector::kGcTypeNone) {
2473 last_gc_type_ = gc_type;
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002474
2475 // Update stats.
2476 ++gc_count_last_window_;
2477 if (running_collection_is_blocking_) {
2478 // If the currently running collection was a blocking one,
2479 // increment the counters and reset the flag.
2480 ++blocking_gc_count_;
2481 blocking_gc_time_ += GetCurrentGcIteration()->GetDurationNs();
2482 ++blocking_gc_count_last_window_;
2483 }
2484 // Update the gc count rate histograms if due.
2485 UpdateGcCountRateHistograms();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002486 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002487 // Reset.
2488 running_collection_is_blocking_ = false;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002489 // Wake anyone who may have been waiting for the GC to complete.
2490 gc_complete_cond_->Broadcast(self);
2491}
2492
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002493void Heap::UpdateGcCountRateHistograms() {
2494 // Invariant: if the time since the last update includes more than
2495 // one windows, all the GC runs (if > 0) must have happened in first
2496 // window because otherwise the update must have already taken place
2497 // at an earlier GC run. So, we report the non-first windows with
2498 // zero counts to the histograms.
2499 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2500 uint64_t now = NanoTime();
2501 DCHECK_GE(now, last_update_time_gc_count_rate_histograms_);
2502 uint64_t time_since_last_update = now - last_update_time_gc_count_rate_histograms_;
2503 uint64_t num_of_windows = time_since_last_update / kGcCountRateHistogramWindowDuration;
2504 if (time_since_last_update >= kGcCountRateHistogramWindowDuration) {
2505 // Record the first window.
2506 gc_count_rate_histogram_.AddValue(gc_count_last_window_ - 1); // Exclude the current run.
2507 blocking_gc_count_rate_histogram_.AddValue(running_collection_is_blocking_ ?
2508 blocking_gc_count_last_window_ - 1 : blocking_gc_count_last_window_);
2509 // Record the other windows (with zero counts).
2510 for (uint64_t i = 0; i < num_of_windows - 1; ++i) {
2511 gc_count_rate_histogram_.AddValue(0);
2512 blocking_gc_count_rate_histogram_.AddValue(0);
2513 }
2514 // Update the last update time and reset the counters.
2515 last_update_time_gc_count_rate_histograms_ =
2516 (now / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
2517 gc_count_last_window_ = 1; // Include the current run.
2518 blocking_gc_count_last_window_ = running_collection_is_blocking_ ? 1 : 0;
2519 }
2520 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2521}
2522
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002523class RootMatchesObjectVisitor : public SingleRootVisitor {
2524 public:
2525 explicit RootMatchesObjectVisitor(const mirror::Object* obj) : obj_(obj) { }
2526
2527 void VisitRoot(mirror::Object* root, const RootInfo& info)
2528 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2529 if (root == obj_) {
2530 LOG(INFO) << "Object " << obj_ << " is a root " << info.ToString();
2531 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002532 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002533
2534 private:
2535 const mirror::Object* const obj_;
2536};
2537
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002538
2539class ScanVisitor {
2540 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07002541 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002542 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002543 }
2544};
2545
Ian Rogers1d54e732013-05-02 21:10:01 -07002546// Verify a reference from an object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002547class VerifyReferenceVisitor : public SingleRootVisitor {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002548 public:
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002549 explicit VerifyReferenceVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
Ian Rogers1d54e732013-05-02 21:10:01 -07002550 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002551 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07002552
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002553 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002554 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002555 }
2556
Mathieu Chartier407f7022014-02-18 14:37:05 -08002557 void operator()(mirror::Class* klass, mirror::Reference* ref) const
2558 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002559 UNUSED(klass);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002560 if (verify_referent_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002561 VerifyReference(ref, ref->GetReferent(), mirror::Reference::ReferentOffset());
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002562 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08002563 }
2564
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07002565 void operator()(mirror::Object* obj, MemberOffset offset, bool /*is_static*/) const
Mathieu Chartier407f7022014-02-18 14:37:05 -08002566 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002567 VerifyReference(obj, obj->GetFieldObject<mirror::Object>(offset), offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08002568 }
2569
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002570 bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
2571 return heap_->IsLiveObjectLocked(obj, true, false, true);
2572 }
2573
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002574 void VisitRoot(mirror::Object* root, const RootInfo& root_info) OVERRIDE
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002575 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002576 if (root == nullptr) {
2577 LOG(ERROR) << "Root is null with info " << root_info.GetType();
2578 } else if (!VerifyReference(nullptr, root, MemberOffset(0))) {
2579 LOG(ERROR) << "Root " << root << " is dead with type " << PrettyTypeOf(root)
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002580 << " thread_id= " << root_info.GetThreadId() << " root_type= " << root_info.GetType();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002581 }
2582 }
2583
2584 private:
Mathieu Chartier407f7022014-02-18 14:37:05 -08002585 // TODO: Fix the no thread safety analysis.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002586 // Returns false on failure.
2587 bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002588 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002589 if (ref == nullptr || IsLive(ref)) {
2590 // Verify that the reference is live.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002591 return true;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002592 }
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002593 if (fail_count_->FetchAndAddSequentiallyConsistent(1) == 0) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002594 // Print message on only on first failure to prevent spam.
2595 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002596 }
2597 if (obj != nullptr) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002598 // Only do this part for non roots.
Ian Rogers1d54e732013-05-02 21:10:01 -07002599 accounting::CardTable* card_table = heap_->GetCardTable();
2600 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2601 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Ian Rogers13735952014-10-08 12:43:28 -07002602 uint8_t* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002603 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2604 << offset << "\n card value = " << static_cast<int>(*card_addr);
2605 if (heap_->IsValidObjectAddress(obj->GetClass())) {
2606 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
2607 } else {
2608 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002609 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002610
Mathieu Chartierb363f662014-07-16 13:28:58 -07002611 // Attempt to find the class inside of the recently freed objects.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002612 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2613 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2614 space::MallocSpace* space = ref_space->AsMallocSpace();
2615 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2616 if (ref_class != nullptr) {
2617 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
2618 << PrettyClass(ref_class);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002619 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002620 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002621 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002622 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002623
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002624 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2625 ref->GetClass()->IsClass()) {
2626 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
2627 } else {
2628 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2629 << ") is not a valid heap address";
2630 }
2631
Ian Rogers13735952014-10-08 12:43:28 -07002632 card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002633 void* cover_begin = card_table->AddrFromCard(card_addr);
2634 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2635 accounting::CardTable::kCardSize);
2636 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2637 << "-" << cover_end;
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002638 accounting::ContinuousSpaceBitmap* bitmap =
2639 heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002640
2641 if (bitmap == nullptr) {
2642 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08002643 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002644 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002645 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002646 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07002647 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002648 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002649 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2650 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002651 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002652 LOG(ERROR) << "Object " << obj << " found in allocation stack";
2653 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002654 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002655 LOG(ERROR) << "Object " << obj << " found in live stack";
2656 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002657 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2658 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2659 }
2660 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2661 LOG(ERROR) << "Ref " << ref << " found in live stack";
2662 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002663 // Attempt to see if the card table missed the reference.
2664 ScanVisitor scan_visitor;
Ian Rogers13735952014-10-08 12:43:28 -07002665 uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
Lei Li727b2942015-01-15 11:26:34 +08002666 card_table->Scan<false>(bitmap, byte_cover_begin,
2667 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002668 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002669
2670 // Search to see if any of the roots reference our object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002671 RootMatchesObjectVisitor visitor1(obj);
2672 Runtime::Current()->VisitRoots(&visitor1);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002673 // Search to see if any of the roots reference our reference.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002674 RootMatchesObjectVisitor visitor2(ref);
2675 Runtime::Current()->VisitRoots(&visitor2);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002676 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002677 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002678 }
2679
Ian Rogers1d54e732013-05-02 21:10:01 -07002680 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002681 Atomic<size_t>* const fail_count_;
2682 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002683};
2684
Ian Rogers1d54e732013-05-02 21:10:01 -07002685// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002686class VerifyObjectVisitor {
2687 public:
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002688 explicit VerifyObjectVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
2689 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002690 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002691
Mathieu Chartier590fee92013-09-13 13:46:47 -07002692 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07002693 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002694 // Note: we are verifying the references in obj but not obj itself, this is because obj must
2695 // be live or else how did we find it in the live bitmap?
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002696 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002697 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002698 obj->VisitReferences<true>(visitor, visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002699 }
2700
Mathieu Chartier590fee92013-09-13 13:46:47 -07002701 static void VisitCallback(mirror::Object* obj, void* arg)
2702 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2703 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
2704 visitor->operator()(obj);
2705 }
2706
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002707 void VerifyRoots() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
2708 LOCKS_EXCLUDED(Locks::heap_bitmap_lock_) {
2709 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2710 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
2711 Runtime::Current()->VisitRoots(&visitor);
2712 }
2713
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002714 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002715 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002716 }
2717
2718 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002719 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002720 Atomic<size_t>* const fail_count_;
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002721 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002722};
2723
Mathieu Chartierc1790162014-05-23 10:54:50 -07002724void Heap::PushOnAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2725 // Slow path, the allocation stack push back must have already failed.
2726 DCHECK(!allocation_stack_->AtomicPushBack(*obj));
2727 do {
2728 // TODO: Add handle VerifyObject.
2729 StackHandleScope<1> hs(self);
2730 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2731 // Push our object into the reserve region of the allocaiton stack. This is only required due
2732 // to heap verification requiring that roots are live (either in the live bitmap or in the
2733 // allocation stack).
2734 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2735 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2736 } while (!allocation_stack_->AtomicPushBack(*obj));
2737}
2738
2739void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2740 // Slow path, the allocation stack push back must have already failed.
2741 DCHECK(!self->PushOnThreadLocalAllocationStack(*obj));
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002742 StackReference<mirror::Object>* start_address;
2743 StackReference<mirror::Object>* end_address;
Mathieu Chartierc1790162014-05-23 10:54:50 -07002744 while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
2745 &end_address)) {
2746 // TODO: Add handle VerifyObject.
2747 StackHandleScope<1> hs(self);
2748 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2749 // Push our object into the reserve region of the allocaiton stack. This is only required due
2750 // to heap verification requiring that roots are live (either in the live bitmap or in the
2751 // allocation stack).
2752 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2753 // Push into the reserve allocation stack.
2754 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2755 }
2756 self->SetThreadLocalAllocationStack(start_address, end_address);
2757 // Retry on the new thread-local allocation stack.
2758 CHECK(self->PushOnThreadLocalAllocationStack(*obj)); // Must succeed.
2759}
2760
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002761// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002762size_t Heap::VerifyHeapReferences(bool verify_referents) {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002763 Thread* self = Thread::Current();
2764 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002765 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07002766 allocation_stack_->Sort();
2767 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002768 // Since we sorted the allocation stack content, need to revoke all
2769 // thread-local allocation stacks.
2770 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002771 Atomic<size_t> fail_count_(0);
2772 VerifyObjectVisitor visitor(this, &fail_count_, verify_referents);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002773 // Verify objects in the allocation stack since these will be objects which were:
2774 // 1. Allocated prior to the GC (pre GC verification).
2775 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002776 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002777 // pointing to dead objects if they are not reachable.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002778 VisitObjectsPaused(VerifyObjectVisitor::VisitCallback, &visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002779 // Verify the roots:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002780 visitor.VerifyRoots();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002781 if (visitor.GetFailureCount() > 0) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002782 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002783 for (const auto& table_pair : mod_union_tables_) {
2784 accounting::ModUnionTable* mod_union_table = table_pair.second;
2785 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
2786 }
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002787 // Dump remembered sets.
2788 for (const auto& table_pair : remembered_sets_) {
2789 accounting::RememberedSet* remembered_set = table_pair.second;
2790 remembered_set->Dump(LOG(ERROR) << remembered_set->GetName() << ": ");
2791 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07002792 DumpSpaces(LOG(ERROR));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002793 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002794 return visitor.GetFailureCount();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002795}
2796
2797class VerifyReferenceCardVisitor {
2798 public:
2799 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
2800 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
2801 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07002802 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002803 }
2804
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002805 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
2806 // annotalysis on visitors.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002807 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
2808 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07002809 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002810 // Filter out class references since changing an object's class does not mark the card as dirty.
2811 // Also handles large objects, since the only reference they hold is a class reference.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002812 if (ref != nullptr && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002813 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002814 // If the object is not dirty and it is referencing something in the live stack other than
2815 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002816 if (!card_table->AddrIsInCardTable(obj)) {
2817 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
2818 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002819 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002820 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002821 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
2822 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002823 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier407f7022014-02-18 14:37:05 -08002824 if (live_stack->ContainsSorted(ref)) {
2825 if (live_stack->ContainsSorted(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002826 LOG(ERROR) << "Object " << obj << " found in live stack";
2827 }
2828 if (heap_->GetLiveBitmap()->Test(obj)) {
2829 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2830 }
2831 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
2832 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
2833
2834 // Print which field of the object is dead.
2835 if (!obj->IsObjectArray()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002836 mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002837 CHECK(klass != nullptr);
2838 auto* fields = is_static ? klass->GetSFields() : klass->GetIFields();
2839 auto num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
2840 CHECK_EQ(fields == nullptr, num_fields == 0u);
2841 for (size_t i = 0; i < num_fields; ++i) {
2842 ArtField* cur = &fields[i];
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002843 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
2844 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
2845 << PrettyField(cur);
2846 break;
2847 }
2848 }
2849 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002850 mirror::ObjectArray<mirror::Object>* object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002851 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002852 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
2853 if (object_array->Get(i) == ref) {
2854 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
2855 }
2856 }
2857 }
2858
2859 *failed_ = true;
2860 }
2861 }
2862 }
2863 }
2864
2865 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002866 Heap* const heap_;
2867 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002868};
2869
2870class VerifyLiveStackReferences {
2871 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002872 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002873 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002874 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002875
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002876 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002877 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2878 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07002879 obj->VisitReferences<true>(visitor, VoidFunctor());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002880 }
2881
2882 bool Failed() const {
2883 return failed_;
2884 }
2885
2886 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002887 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002888 bool failed_;
2889};
2890
2891bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002892 Thread* self = Thread::Current();
2893 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002894 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002895 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002896 // Since we sorted the allocation stack content, need to revoke all
2897 // thread-local allocation stacks.
2898 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002899 VerifyLiveStackReferences visitor(this);
2900 GetLiveBitmap()->Visit(visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002901 // We can verify objects in the live stack since none of these should reference dead objects.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002902 for (auto* it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
2903 if (!kUseThreadLocalAllocationStack || it->AsMirrorPtr() != nullptr) {
2904 visitor(it->AsMirrorPtr());
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002905 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002906 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07002907 return !visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002908}
2909
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002910void Heap::SwapStacks(Thread* self) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002911 UNUSED(self);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002912 if (kUseThreadLocalAllocationStack) {
2913 live_stack_->AssertAllZero();
2914 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002915 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002916}
2917
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002918void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002919 // This must be called only during the pause.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002920 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002921 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2922 MutexLock mu2(self, *Locks::thread_list_lock_);
2923 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
2924 for (Thread* t : thread_list) {
2925 t->RevokeThreadLocalAllocationStack();
2926 }
2927}
2928
Ian Rogers68d8b422014-07-17 11:09:10 -07002929void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
2930 if (kIsDebugBuild) {
2931 if (rosalloc_space_ != nullptr) {
2932 rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
2933 }
2934 if (bump_pointer_space_ != nullptr) {
2935 bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
2936 }
2937 }
2938}
2939
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002940void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
2941 if (kIsDebugBuild) {
2942 if (bump_pointer_space_ != nullptr) {
2943 bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
2944 }
2945 }
2946}
2947
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002948accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
2949 auto it = mod_union_tables_.find(space);
2950 if (it == mod_union_tables_.end()) {
2951 return nullptr;
2952 }
2953 return it->second;
2954}
2955
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002956accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
2957 auto it = remembered_sets_.find(space);
2958 if (it == remembered_sets_.end()) {
2959 return nullptr;
2960 }
2961 return it->second;
2962}
2963
Lei Li4add3b42015-01-15 11:55:26 +08002964void Heap::ProcessCards(TimingLogger* timings, bool use_rem_sets, bool process_alloc_space_cards,
2965 bool clear_alloc_space_cards) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002966 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07002967 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07002968 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002969 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002970 accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002971 if (table != nullptr) {
2972 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
2973 "ImageModUnionClearCards";
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002974 TimingLogger::ScopedTiming t2(name, timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002975 table->ClearCards();
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002976 } else if (use_rem_sets && rem_set != nullptr) {
2977 DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
2978 << static_cast<int>(collector_type_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002979 TimingLogger::ScopedTiming t2("AllocSpaceRemSetClearCards", timings);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002980 rem_set->ClearCards();
Lei Li4add3b42015-01-15 11:55:26 +08002981 } else if (process_alloc_space_cards) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002982 TimingLogger::ScopedTiming t2("AllocSpaceClearCards", timings);
Lei Li4add3b42015-01-15 11:55:26 +08002983 if (clear_alloc_space_cards) {
2984 card_table_->ClearCardRange(space->Begin(), space->End());
2985 } else {
2986 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these
2987 // cards were dirty before the GC started.
2988 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
2989 // -> clean(cleaning thread).
2990 // The races are we either end up with: Aged card, unaged card. Since we have the
2991 // checkpoint roots and then we scan / update mod union tables after. We will always
2992 // scan either card. If we end up with the non aged card, we scan it it in the pause.
2993 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
2994 VoidFunctor());
2995 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002996 }
2997 }
2998}
2999
Mathieu Chartier407f7022014-02-18 14:37:05 -08003000static void IdentityMarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>*, void*) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003001}
3002
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003003void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
3004 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003005 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003006 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003007 if (verify_pre_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003008 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003009 size_t failures = VerifyHeapReferences();
3010 if (failures > 0) {
3011 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3012 << " failures";
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003013 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003014 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003015 // Check that all objects which reference things in the live stack are on dirty cards.
3016 if (verify_missing_card_marks_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003017 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyMissingCardMarks", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003018 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
3019 SwapStacks(self);
3020 // Sort the live stack so that we can quickly binary search it later.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003021 CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
3022 << " missing card mark verification failed\n" << DumpSpaces();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003023 SwapStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003024 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003025 if (verify_mod_union_table_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003026 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyModUnionTables", timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003027 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003028 for (const auto& table_pair : mod_union_tables_) {
3029 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier407f7022014-02-18 14:37:05 -08003030 mod_union_table->UpdateAndMarkReferences(IdentityMarkHeapReferenceCallback, nullptr);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003031 mod_union_table->Verify();
3032 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003033 }
3034}
3035
3036void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier0651d412014-04-29 14:37:57 -07003037 if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003038 collector::GarbageCollector::ScopedPause pause(gc);
3039 PreGcVerificationPaused(gc);
3040 }
3041}
3042
3043void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003044 UNUSED(gc);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003045 // TODO: Add a new runtime option for this?
3046 if (verify_pre_gc_rosalloc_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003047 RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003048 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003049}
3050
Ian Rogers1d54e732013-05-02 21:10:01 -07003051void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003052 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003053 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003054 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003055 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
3056 // reachable objects.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003057 if (verify_pre_sweeping_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003058 TimingLogger::ScopedTiming t2("(Paused)PostSweepingVerifyHeapReferences", timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003059 CHECK_NE(self->GetState(), kRunnable);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003060 {
3061 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3062 // Swapping bound bitmaps does nothing.
3063 gc->SwapBitmaps();
3064 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07003065 // Pass in false since concurrent reference processing can mean that the reference referents
3066 // may point to dead objects at the point which PreSweepingGcVerification is called.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003067 size_t failures = VerifyHeapReferences(false);
3068 if (failures > 0) {
3069 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
3070 << " failures";
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003071 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003072 {
3073 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3074 gc->SwapBitmaps();
3075 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003076 }
3077 if (verify_pre_sweeping_rosalloc_) {
3078 RosAllocVerification(timings, "PreSweepingRosAllocVerification");
3079 }
3080}
3081
3082void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
3083 // Only pause if we have to do some verification.
3084 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003085 TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003086 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003087 if (verify_system_weaks_) {
3088 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3089 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
3090 mark_sweep->VerifySystemWeaks();
3091 }
3092 if (verify_post_gc_rosalloc_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003093 RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003094 }
3095 if (verify_post_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003096 TimingLogger::ScopedTiming t2("(Paused)PostGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003097 size_t failures = VerifyHeapReferences();
3098 if (failures > 0) {
3099 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3100 << " failures";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003101 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003102 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003103}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003104
Ian Rogers1d54e732013-05-02 21:10:01 -07003105void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003106 if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
3107 collector::GarbageCollector::ScopedPause pause(gc);
Mathieu Chartierd35326f2014-08-18 15:02:59 -07003108 PostGcVerificationPaused(gc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003109 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003110}
3111
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003112void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003113 TimingLogger::ScopedTiming t(name, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003114 for (const auto& space : continuous_spaces_) {
3115 if (space->IsRosAllocSpace()) {
3116 VLOG(heap) << name << " : " << space->GetName();
3117 space->AsRosAllocSpace()->Verify();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08003118 }
3119 }
3120}
3121
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003122collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08003123 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003124 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003125 return WaitForGcToCompleteLocked(cause, self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003126}
3127
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003128collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003129 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003130 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08003131 while (collector_type_running_ != kCollectorTypeNone) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003132 if (self != task_processor_->GetRunningThread()) {
3133 // The current thread is about to wait for a currently running
3134 // collection to finish. If the waiting thread is not the heap
3135 // task daemon thread, the currently running collection is
3136 // considered as a blocking GC.
3137 running_collection_is_blocking_ = true;
3138 VLOG(gc) << "Waiting for a blocking GC " << cause;
3139 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003140 ATRACE_BEGIN("GC: Wait For Completion");
3141 // We must wait, change thread state then sleep on gc_complete_cond_;
3142 gc_complete_cond_->Wait(self);
3143 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07003144 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003145 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003146 uint64_t wait_time = NanoTime() - wait_start;
3147 total_wait_time_ += wait_time;
3148 if (wait_time > long_pause_log_threshold_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003149 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time)
3150 << " for cause " << cause;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003151 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003152 if (self != task_processor_->GetRunningThread()) {
3153 // The current thread is about to run a collection. If the thread
3154 // is not the heap task daemon thread, it's considered as a
3155 // blocking GC (i.e., blocking itself).
3156 running_collection_is_blocking_ = true;
3157 VLOG(gc) << "Starting a blocking GC " << cause;
3158 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07003159 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07003160}
3161
Elliott Hughesc967f782012-04-16 10:23:15 -07003162void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003163 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003164 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07003165 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07003166}
3167
3168size_t Heap::GetPercentFree() {
Mathieu Chartierd30e1d62014-06-09 13:25:22 -07003169 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / max_allowed_footprint_);
Elliott Hughesc967f782012-04-16 10:23:15 -07003170}
3171
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003172void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003173 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003174 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003175 << PrettySize(GetMaxMemory());
3176 max_allowed_footprint = GetMaxMemory();
3177 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07003178 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07003179}
3180
Mathieu Chartier590fee92013-09-13 13:46:47 -07003181bool Heap::IsMovableObject(const mirror::Object* obj) const {
3182 if (kMovingCollector) {
Mathieu Chartier31f44142014-04-08 14:40:03 -07003183 space::Space* space = FindContinuousSpaceFromObject(obj, true);
3184 if (space != nullptr) {
3185 // TODO: Check large object?
3186 return space->CanMoveObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003187 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003188 }
3189 return false;
3190}
3191
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003192void Heap::UpdateMaxNativeFootprint() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07003193 size_t native_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003194 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
3195 size_t target_size = native_size / GetTargetHeapUtilization();
3196 if (target_size > native_size + max_free_) {
3197 target_size = native_size + max_free_;
3198 } else if (target_size < native_size + min_free_) {
3199 target_size = native_size + min_free_;
3200 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003201 native_footprint_gc_watermark_ = std::min(growth_limit_, target_size);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003202}
3203
Mathieu Chartierafe49982014-03-27 10:55:04 -07003204collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
3205 for (const auto& collector : garbage_collectors_) {
3206 if (collector->GetCollectorType() == collector_type_ &&
3207 collector->GetGcType() == gc_type) {
3208 return collector;
3209 }
3210 }
3211 return nullptr;
3212}
3213
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003214double Heap::HeapGrowthMultiplier() const {
3215 // If we don't care about pause times we are background, so return 1.0.
3216 if (!CareAboutPauseTimes() || IsLowMemoryMode()) {
3217 return 1.0;
3218 }
3219 return foreground_heap_growth_multiplier_;
3220}
3221
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003222void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran,
3223 uint64_t bytes_allocated_before_gc) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003224 // We know what our utilization is at this moment.
3225 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003226 const uint64_t bytes_allocated = GetBytesAllocated();
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003227 uint64_t target_size;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003228 collector::GcType gc_type = collector_ran->GetGcType();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003229 const double multiplier = HeapGrowthMultiplier(); // Use the multiplier to grow more for
3230 // foreground.
3231 const uint64_t adjusted_min_free = static_cast<uint64_t>(min_free_ * multiplier);
3232 const uint64_t adjusted_max_free = static_cast<uint64_t>(max_free_ * multiplier);
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003233 if (gc_type != collector::kGcTypeSticky) {
3234 // Grow the heap for non sticky GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003235 ssize_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003236 CHECK_GE(delta, 0);
3237 target_size = bytes_allocated + delta * multiplier;
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003238 target_size = std::min(target_size, bytes_allocated + adjusted_max_free);
3239 target_size = std::max(target_size, bytes_allocated + adjusted_min_free);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003240 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003241 next_gc_type_ = collector::kGcTypeSticky;
3242 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003243 collector::GcType non_sticky_gc_type =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07003244 HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003245 // Find what the next non sticky collector will be.
3246 collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
3247 // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
3248 // do another sticky collection next.
3249 // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
3250 // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
3251 // if the sticky GC throughput always remained >= the full/partial throughput.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003252 if (current_gc_iteration_.GetEstimatedThroughput() * kStickyGcThroughputAdjustment >=
Mathieu Chartierafe49982014-03-27 10:55:04 -07003253 non_sticky_collector->GetEstimatedMeanThroughput() &&
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003254 non_sticky_collector->NumberOfIterations() > 0 &&
Mathieu Chartierafe49982014-03-27 10:55:04 -07003255 bytes_allocated <= max_allowed_footprint_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003256 next_gc_type_ = collector::kGcTypeSticky;
3257 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003258 next_gc_type_ = non_sticky_gc_type;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003259 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003260 // If we have freed enough memory, shrink the heap back down.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003261 if (bytes_allocated + adjusted_max_free < max_allowed_footprint_) {
3262 target_size = bytes_allocated + adjusted_max_free;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003263 } else {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003264 target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003265 }
3266 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003267 if (!ignore_max_footprint_) {
3268 SetIdealFootprint(target_size);
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003269 if (IsGcConcurrent()) {
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003270 const uint64_t freed_bytes = current_gc_iteration_.GetFreedBytes() +
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003271 current_gc_iteration_.GetFreedLargeObjectBytes() +
3272 current_gc_iteration_.GetFreedRevokeBytes();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003273 // Bytes allocated will shrink by freed_bytes after the GC runs, so if we want to figure out
3274 // how many bytes were allocated during the GC we need to add freed_bytes back on.
3275 CHECK_GE(bytes_allocated + freed_bytes, bytes_allocated_before_gc);
3276 const uint64_t bytes_allocated_during_gc = bytes_allocated + freed_bytes -
3277 bytes_allocated_before_gc;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003278 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003279 // Calculate the estimated GC duration.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003280 const double gc_duration_seconds = NsToMs(current_gc_iteration_.GetDurationNs()) / 1000.0;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003281 // Estimate how many remaining bytes we will have when we need to start the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003282 size_t remaining_bytes = bytes_allocated_during_gc * gc_duration_seconds;
Mathieu Chartier74762802014-01-24 10:21:35 -08003283 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003284 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
3285 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
3286 // A never going to happen situation that from the estimated allocation rate we will exceed
3287 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08003288 // another GC nearly straight away.
3289 remaining_bytes = kMinConcurrentRemainingBytes;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003290 }
Mathieu Chartier74762802014-01-24 10:21:35 -08003291 DCHECK_LE(remaining_bytes, max_allowed_footprint_);
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003292 DCHECK_LE(max_allowed_footprint_, GetMaxMemory());
Mathieu Chartier74762802014-01-24 10:21:35 -08003293 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
3294 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
3295 // right away.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003296 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
3297 static_cast<size_t>(bytes_allocated));
Mathieu Chartier65db8802012-11-20 12:36:46 -08003298 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08003299 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003300}
3301
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003302void Heap::ClampGrowthLimit() {
Mathieu Chartierddac4232015-04-02 10:08:03 -07003303 // Use heap bitmap lock to guard against races with BindLiveToMarkBitmap.
3304 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003305 capacity_ = growth_limit_;
3306 for (const auto& space : continuous_spaces_) {
3307 if (space->IsMallocSpace()) {
3308 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3309 malloc_space->ClampGrowthLimit();
3310 }
3311 }
3312 // This space isn't added for performance reasons.
3313 if (main_space_backup_.get() != nullptr) {
3314 main_space_backup_->ClampGrowthLimit();
3315 }
3316}
3317
jeffhaoc1160702011-10-27 15:48:45 -07003318void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08003319 growth_limit_ = capacity_;
Mathieu Chartier0310da52014-12-01 13:40:48 -08003320 for (const auto& space : continuous_spaces_) {
3321 if (space->IsMallocSpace()) {
3322 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3323 malloc_space->ClearGrowthLimit();
3324 malloc_space->SetFootprintLimit(malloc_space->Capacity());
3325 }
3326 }
3327 // This space isn't added for performance reasons.
3328 if (main_space_backup_.get() != nullptr) {
3329 main_space_backup_->ClearGrowthLimit();
3330 main_space_backup_->SetFootprintLimit(main_space_backup_->Capacity());
3331 }
jeffhaoc1160702011-10-27 15:48:45 -07003332}
3333
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003334void Heap::AddFinalizerReference(Thread* self, mirror::Object** object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003335 ScopedObjectAccess soa(self);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003336 ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
Ian Rogers53b8b092014-03-13 23:45:53 -07003337 jvalue args[1];
3338 args[0].l = arg.get();
3339 InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003340 // Restore object in case it gets moved.
3341 *object = soa.Decode<mirror::Object*>(arg.get());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003342}
3343
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003344void Heap::RequestConcurrentGCAndSaveObject(Thread* self, bool force_full, mirror::Object** obj) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003345 StackHandleScope<1> hs(self);
3346 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003347 RequestConcurrentGC(self, force_full);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003348}
3349
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003350class Heap::ConcurrentGCTask : public HeapTask {
3351 public:
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003352 explicit ConcurrentGCTask(uint64_t target_time, bool force_full)
3353 : HeapTask(target_time), force_full_(force_full) { }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003354 virtual void Run(Thread* self) OVERRIDE {
3355 gc::Heap* heap = Runtime::Current()->GetHeap();
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003356 heap->ConcurrentGC(self, force_full_);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003357 heap->ClearConcurrentGCRequest();
Ian Rogers120f1c72012-09-28 17:17:10 -07003358 }
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003359
3360 private:
3361 const bool force_full_; // If true, force full (or partial) collection.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003362};
3363
3364static bool CanAddHeapTask(Thread* self) LOCKS_EXCLUDED(Locks::runtime_shutdown_lock_) {
3365 Runtime* runtime = Runtime::Current();
3366 return runtime != nullptr && runtime->IsFinishedStarting() && !runtime->IsShuttingDown(self) &&
3367 !self->IsHandlingStackOverflow();
3368}
3369
3370void Heap::ClearConcurrentGCRequest() {
3371 concurrent_gc_pending_.StoreRelaxed(false);
3372}
3373
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003374void Heap::RequestConcurrentGC(Thread* self, bool force_full) {
Mathieu Chartierac195162015-02-20 18:44:28 +00003375 if (CanAddHeapTask(self) &&
3376 concurrent_gc_pending_.CompareExchangeStrongSequentiallyConsistent(false, true)) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003377 task_processor_->AddTask(self, new ConcurrentGCTask(NanoTime(), // Start straight away.
3378 force_full));
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003379 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003380}
3381
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003382void Heap::ConcurrentGC(Thread* self, bool force_full) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003383 if (!Runtime::Current()->IsShuttingDown(self)) {
3384 // Wait for any GCs currently running to finish.
3385 if (WaitForGcToComplete(kGcCauseBackground, self) == collector::kGcTypeNone) {
3386 // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
3387 // instead. E.g. can't do partial, so do full instead.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003388 collector::GcType next_gc_type = next_gc_type_;
3389 // If forcing full and next gc type is sticky, override with a non-sticky type.
3390 if (force_full && next_gc_type == collector::kGcTypeSticky) {
3391 next_gc_type = HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
3392 }
3393 if (CollectGarbageInternal(next_gc_type, kGcCauseBackground, false) ==
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003394 collector::kGcTypeNone) {
3395 for (collector::GcType gc_type : gc_plan_) {
3396 // Attempt to run the collector, if we succeed, we are done.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003397 if (gc_type > next_gc_type &&
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003398 CollectGarbageInternal(gc_type, kGcCauseBackground, false) !=
3399 collector::kGcTypeNone) {
3400 break;
3401 }
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08003402 }
3403 }
3404 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07003405 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003406}
3407
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003408class Heap::CollectorTransitionTask : public HeapTask {
3409 public:
3410 explicit CollectorTransitionTask(uint64_t target_time) : HeapTask(target_time) { }
3411 virtual void Run(Thread* self) OVERRIDE {
3412 gc::Heap* heap = Runtime::Current()->GetHeap();
3413 heap->DoPendingCollectorTransition();
3414 heap->ClearPendingCollectorTransition(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003415 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003416};
3417
3418void Heap::ClearPendingCollectorTransition(Thread* self) {
3419 MutexLock mu(self, *pending_task_lock_);
3420 pending_collector_transition_ = nullptr;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003421}
3422
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003423void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
3424 Thread* self = Thread::Current();
3425 desired_collector_type_ = desired_collector_type;
3426 if (desired_collector_type_ == collector_type_ || !CanAddHeapTask(self)) {
3427 return;
3428 }
3429 CollectorTransitionTask* added_task = nullptr;
3430 const uint64_t target_time = NanoTime() + delta_time;
3431 {
3432 MutexLock mu(self, *pending_task_lock_);
3433 // If we have an existing collector transition, update the targe time to be the new target.
3434 if (pending_collector_transition_ != nullptr) {
3435 task_processor_->UpdateTargetRunTime(self, pending_collector_transition_, target_time);
3436 return;
3437 }
3438 added_task = new CollectorTransitionTask(target_time);
3439 pending_collector_transition_ = added_task;
3440 }
3441 task_processor_->AddTask(self, added_task);
3442}
3443
3444class Heap::HeapTrimTask : public HeapTask {
3445 public:
3446 explicit HeapTrimTask(uint64_t delta_time) : HeapTask(NanoTime() + delta_time) { }
3447 virtual void Run(Thread* self) OVERRIDE {
3448 gc::Heap* heap = Runtime::Current()->GetHeap();
3449 heap->Trim(self);
3450 heap->ClearPendingTrim(self);
3451 }
3452};
3453
3454void Heap::ClearPendingTrim(Thread* self) {
3455 MutexLock mu(self, *pending_task_lock_);
3456 pending_heap_trim_ = nullptr;
3457}
3458
3459void Heap::RequestTrim(Thread* self) {
3460 if (!CanAddHeapTask(self)) {
3461 return;
3462 }
Ian Rogers48931882013-01-22 14:35:16 -08003463 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3464 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3465 // a space it will hold its lock and can become a cause of jank.
3466 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3467 // forking.
3468
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08003469 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3470 // because that only marks object heads, so a large array looks like lots of empty space. We
3471 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3472 // to utilization (which is probably inversely proportional to how much benefit we can expect).
3473 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3474 // not how much use we're making of those pages.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003475 HeapTrimTask* added_task = nullptr;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003476 {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003477 MutexLock mu(self, *pending_task_lock_);
3478 if (pending_heap_trim_ != nullptr) {
3479 // Already have a heap trim request in task processor, ignore this request.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003480 return;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003481 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003482 added_task = new HeapTrimTask(kHeapTrimWait);
3483 pending_heap_trim_ = added_task;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07003484 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003485 task_processor_->AddTask(self, added_task);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003486}
3487
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003488void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003489 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003490 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3491 if (freed_bytes_revoke > 0U) {
3492 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3493 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3494 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003495 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003496 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003497 CHECK_EQ(bump_pointer_space_->RevokeThreadLocalBuffers(thread), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003498 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003499 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003500 CHECK_EQ(region_space_->RevokeThreadLocalBuffers(thread), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003501 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003502}
3503
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003504void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3505 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003506 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3507 if (freed_bytes_revoke > 0U) {
3508 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3509 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3510 }
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003511 }
3512}
3513
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003514void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003515 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003516 size_t freed_bytes_revoke = rosalloc_space_->RevokeAllThreadLocalBuffers();
3517 if (freed_bytes_revoke > 0U) {
3518 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3519 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3520 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003521 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003522 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003523 CHECK_EQ(bump_pointer_space_->RevokeAllThreadLocalBuffers(), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003524 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003525 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003526 CHECK_EQ(region_space_->RevokeAllThreadLocalBuffers(), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003527 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003528}
3529
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003530bool Heap::IsGCRequestPending() const {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003531 return concurrent_gc_pending_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003532}
3533
Mathieu Chartier590fee92013-09-13 13:46:47 -07003534void Heap::RunFinalization(JNIEnv* env) {
3535 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
3536 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
3537 CHECK(WellKnownClasses::java_lang_System != nullptr);
3538 WellKnownClasses::java_lang_System_runFinalization =
3539 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
3540 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
3541 }
3542 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
3543 WellKnownClasses::java_lang_System_runFinalization);
3544}
3545
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003546void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003547 Thread* self = ThreadForEnv(env);
3548 if (native_need_to_run_finalization_) {
3549 RunFinalization(env);
3550 UpdateMaxNativeFootprint();
3551 native_need_to_run_finalization_ = false;
3552 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003553 // Total number of native bytes allocated.
Ian Rogers3e5cf302014-05-20 16:40:37 -07003554 size_t new_native_bytes_allocated = native_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes);
3555 new_native_bytes_allocated += bytes;
3556 if (new_native_bytes_allocated > native_footprint_gc_watermark_) {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07003557 collector::GcType gc_type = HasZygoteSpace() ? collector::kGcTypePartial :
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08003558 collector::kGcTypeFull;
3559
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003560 // The second watermark is higher than the gc watermark. If you hit this it means you are
3561 // allocating native objects faster than the GC can keep up with.
Mathieu Chartier08487452014-09-02 16:21:01 -07003562 if (new_native_bytes_allocated > growth_limit_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003563 if (WaitForGcToComplete(kGcCauseForNativeAlloc, self) != collector::kGcTypeNone) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003564 // Just finished a GC, attempt to run finalizers.
3565 RunFinalization(env);
3566 CHECK(!env->ExceptionCheck());
Lin Zang60e27162015-03-10 18:53:21 +08003567 // Native bytes allocated may be updated by finalization, refresh it.
3568 new_native_bytes_allocated = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003569 }
3570 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
Mathieu Chartier08487452014-09-02 16:21:01 -07003571 if (new_native_bytes_allocated > growth_limit_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08003572 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003573 RunFinalization(env);
3574 native_need_to_run_finalization_ = false;
3575 CHECK(!env->ExceptionCheck());
3576 }
3577 // We have just run finalizers, update the native watermark since it is very likely that
3578 // finalizers released native managed allocations.
3579 UpdateMaxNativeFootprint();
3580 } else if (!IsGCRequestPending()) {
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003581 if (IsGcConcurrent()) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003582 RequestConcurrentGC(self, true); // Request non-sticky type.
Mathieu Chartier590fee92013-09-13 13:46:47 -07003583 } else {
Hiroshi Yamauchid20aba12014-04-11 15:31:09 -07003584 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003585 }
3586 }
3587 }
3588}
3589
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003590void Heap::RegisterNativeFree(JNIEnv* env, size_t bytes) {
3591 size_t expected_size;
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003592 do {
Ian Rogers3e5cf302014-05-20 16:40:37 -07003593 expected_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003594 if (UNLIKELY(bytes > expected_size)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003595 ScopedObjectAccess soa(env);
3596 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003597 StringPrintf("Attempted to free %zd native bytes with only %zd native bytes "
Mathieu Chartier590fee92013-09-13 13:46:47 -07003598 "registered as allocated", bytes, expected_size).c_str());
3599 break;
3600 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003601 } while (!native_bytes_allocated_.CompareExchangeWeakRelaxed(expected_size,
3602 expected_size - bytes));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003603}
3604
Ian Rogersef7d42f2014-01-06 12:55:46 -08003605size_t Heap::GetTotalMemory() const {
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003606 return std::max(max_allowed_footprint_, GetBytesAllocated());
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07003607}
3608
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003609void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3610 DCHECK(mod_union_table != nullptr);
3611 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3612}
3613
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003614void Heap::CheckPreconditionsForAllocObject(mirror::Class* c, size_t byte_count) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003615 CHECK(c == nullptr || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers1ff3c982014-08-12 02:30:58 -07003616 (c->IsVariableSize() || c->GetObjectSize() == byte_count));
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003617 CHECK_GE(byte_count, sizeof(mirror::Object));
3618}
3619
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003620void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
3621 CHECK(remembered_set != nullptr);
3622 space::Space* space = remembered_set->GetSpace();
3623 CHECK(space != nullptr);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003624 CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003625 remembered_sets_.Put(space, remembered_set);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003626 CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003627}
3628
3629void Heap::RemoveRememberedSet(space::Space* space) {
3630 CHECK(space != nullptr);
3631 auto it = remembered_sets_.find(space);
3632 CHECK(it != remembered_sets_.end());
Mathieu Chartier5189e242014-07-24 11:11:05 -07003633 delete it->second;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003634 remembered_sets_.erase(it);
3635 CHECK(remembered_sets_.find(space) == remembered_sets_.end());
3636}
3637
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003638void Heap::ClearMarkedObjects() {
3639 // Clear all of the spaces' mark bitmaps.
3640 for (const auto& space : GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07003641 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003642 if (space->GetLiveBitmap() != mark_bitmap) {
3643 mark_bitmap->Clear();
3644 }
3645 }
3646 // Clear the marked objects in the discontinous space object sets.
3647 for (const auto& space : GetDiscontinuousSpaces()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07003648 space->GetMarkBitmap()->Clear();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003649 }
3650}
3651
Ian Rogers1d54e732013-05-02 21:10:01 -07003652} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07003653} // namespace art