blob: aeab7d80b474726400668c79fd7930487925334e [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 Chartierb5de3bb2015-06-05 13:21:05 -0700113// System.runFinalization can deadlock with native allocations, to deal with this, we have a
114// timeout on how long we wait for finalizers to run. b/21544853
115static constexpr uint64_t kNativeAllocationFinalizeTimeout = MsToNs(250u);
Mathieu Chartier0051be62012-10-12 17:47:11 -0700116
Mathieu Chartier0051be62012-10-12 17:47:11 -0700117Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700118 double target_utilization, double foreground_heap_growth_multiplier,
119 size_t capacity, size_t non_moving_space_capacity, const std::string& image_file_name,
120 const InstructionSet image_instruction_set, CollectorType foreground_collector_type,
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700121 CollectorType background_collector_type,
122 space::LargeObjectSpaceType large_object_space_type, size_t large_object_threshold,
123 size_t parallel_gc_threads, size_t conc_gc_threads, bool low_memory_mode,
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800124 size_t long_pause_log_threshold, size_t long_gc_log_threshold,
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700125 bool ignore_max_footprint, bool use_tlab,
126 bool verify_pre_gc_heap, bool verify_pre_sweeping_heap, bool verify_post_gc_heap,
127 bool verify_pre_gc_rosalloc, bool verify_pre_sweeping_rosalloc,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700128 bool verify_post_gc_rosalloc, bool use_homogeneous_space_compaction_for_oom,
129 uint64_t min_interval_homogeneous_space_compaction_by_oom)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800130 : non_moving_space_(nullptr),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800131 rosalloc_space_(nullptr),
132 dlmalloc_space_(nullptr),
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800133 main_space_(nullptr),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800134 collector_type_(kCollectorTypeNone),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700135 foreground_collector_type_(foreground_collector_type),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800136 background_collector_type_(background_collector_type),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700137 desired_collector_type_(foreground_collector_type_),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800138 pending_task_lock_(nullptr),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700139 parallel_gc_threads_(parallel_gc_threads),
140 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -0700141 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700142 long_pause_log_threshold_(long_pause_log_threshold),
143 long_gc_log_threshold_(long_gc_log_threshold),
144 ignore_max_footprint_(ignore_max_footprint),
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -0700145 zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700146 zygote_space_(nullptr),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700147 large_object_threshold_(large_object_threshold),
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800148 collector_type_running_(kCollectorTypeNone),
Ian Rogers1d54e732013-05-02 21:10:01 -0700149 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700150 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800151 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700152 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700153 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700154 native_footprint_gc_watermark_(initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700155 native_need_to_run_finalization_(false),
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800156 // Initially assume we perceive jank in case the process state is never updated.
157 process_state_(kProcessStateJankPerceptible),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800158 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700159 total_bytes_freed_ever_(0),
160 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800161 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700162 native_bytes_allocated_(0),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700163 num_bytes_freed_revoke_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700164 verify_missing_card_marks_(false),
165 verify_system_weaks_(false),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800166 verify_pre_gc_heap_(verify_pre_gc_heap),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700167 verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800168 verify_post_gc_heap_(verify_post_gc_heap),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700169 verify_mod_union_table_(false),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800170 verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700171 verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800172 verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700173 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
174 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
175 * verification is enabled, we limit the size of allocation stacks to speed up their
176 * searching.
177 */
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800178 max_allocation_stack_size_(kGCALotMode ? kGcAlotAllocationStackSize
179 : (kVerifyObjectSupport > kVerifyObjectModeFast) ? kVerifyObjectAllocationStackSize :
180 kDefaultAllocationStackSize),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800181 current_allocator_(kAllocatorTypeDlMalloc),
182 current_non_moving_allocator_(kAllocatorTypeNonMoving),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700183 bump_pointer_space_(nullptr),
184 temp_space_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800185 region_space_(nullptr),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700186 min_free_(min_free),
187 max_free_(max_free),
188 target_utilization_(target_utilization),
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -0700189 foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700190 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700191 total_allocation_time_(0),
Mathieu Chartier4e305412014-02-19 10:54:44 -0800192 verify_object_mode_(kVerifyObjectModeDisabled),
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800193 disable_moving_gc_count_(0),
Mathieu Chartierda44d772014-04-01 15:01:46 -0700194 running_on_valgrind_(Runtime::Current()->RunningOnValgrind()),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700195 use_tlab_(use_tlab),
196 main_space_backup_(nullptr),
Mathieu Chartierb363f662014-07-16 13:28:58 -0700197 min_interval_homogeneous_space_compaction_by_oom_(
198 min_interval_homogeneous_space_compaction_by_oom),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700199 last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800200 pending_collector_transition_(nullptr),
201 pending_heap_trim_(nullptr),
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700202 use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom),
203 running_collection_is_blocking_(false),
204 blocking_gc_count_(0U),
205 blocking_gc_time_(0U),
206 last_update_time_gc_count_rate_histograms_( // Round down by the window duration.
207 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration),
208 gc_count_last_window_(0U),
209 blocking_gc_count_last_window_(0U),
210 gc_count_rate_histogram_("gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
211 blocking_gc_count_rate_histogram_("blocking gc count rate histogram", 1U,
212 kGcCountRateMaxBucketCount) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800213 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800214 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700215 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800216 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
217 // entrypoints.
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700218 const bool is_zygote = Runtime::Current()->IsZygote();
219 if (!is_zygote) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700220 // Background compaction is currently not supported for command line runs.
221 if (background_collector_type_ != foreground_collector_type_) {
Mathieu Chartier52ba1992014-05-07 14:39:21 -0700222 VLOG(heap) << "Disabling background compaction for non zygote";
Mathieu Chartier31f44142014-04-08 14:40:03 -0700223 background_collector_type_ = foreground_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800224 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800225 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800226 ChangeCollector(desired_collector_type_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700227 live_bitmap_.reset(new accounting::HeapBitmap(this));
228 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Ian Rogers30fab402012-01-23 15:43:46 -0800229 // Requested begin for the alloc space, to follow the mapped image and oat files
Ian Rogers13735952014-10-08 12:43:28 -0700230 uint8_t* requested_alloc_space_begin = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800231 if (foreground_collector_type_ == kCollectorTypeCC) {
232 // Need to use a low address so that we can allocate a contiguous
233 // 2 * Xmx space when there's no image (dex2oat for target).
234 CHECK_GE(300 * MB, non_moving_space_capacity);
235 requested_alloc_space_begin = reinterpret_cast<uint8_t*>(300 * MB) - non_moving_space_capacity;
236 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800237 if (!image_file_name.empty()) {
Richard Uhler054a0782015-04-07 10:56:50 -0700238 ATRACE_BEGIN("ImageSpace::Create");
Alex Light64ad14d2014-08-19 14:23:13 -0700239 std::string error_msg;
Richard Uhler054a0782015-04-07 10:56:50 -0700240 auto* image_space = space::ImageSpace::Create(image_file_name.c_str(), image_instruction_set,
241 &error_msg);
242 ATRACE_END();
Alex Light64ad14d2014-08-19 14:23:13 -0700243 if (image_space != nullptr) {
244 AddSpace(image_space);
245 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
246 // isn't going to get in the middle
Ian Rogers13735952014-10-08 12:43:28 -0700247 uint8_t* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
Alex Light64ad14d2014-08-19 14:23:13 -0700248 CHECK_GT(oat_file_end_addr, image_space->End());
249 requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
250 } else {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700251 LOG(ERROR) << "Could not create image space with image file '" << image_file_name << "'. "
Alex Light64ad14d2014-08-19 14:23:13 -0700252 << "Attempting to fall back to imageless running. Error was: " << error_msg;
253 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700254 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700255 /*
256 requested_alloc_space_begin -> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700257 +- nonmoving space (non_moving_space_capacity)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700258 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700259 +-????????????????????????????????????????????+-
260 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700261 +-main alloc space / bump space 1 (capacity_) +-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700262 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700263 +-????????????????????????????????????????????+-
264 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
265 +-main alloc space2 / bump space 2 (capacity_)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700266 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
267 */
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800268 // We don't have hspace compaction enabled with GSS or CC.
269 if (foreground_collector_type_ == kCollectorTypeGSS ||
270 foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800271 use_homogeneous_space_compaction_for_oom_ = false;
272 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700273 bool support_homogeneous_space_compaction =
Mathieu Chartier0deeb812014-08-21 18:28:20 -0700274 background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800275 use_homogeneous_space_compaction_for_oom_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700276 // We may use the same space the main space for the non moving space if we don't need to compact
277 // from the main space.
278 // This is not the case if we support homogeneous compaction or have a moving background
279 // collector type.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700280 bool separate_non_moving_space = is_zygote ||
281 support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
282 IsMovingGc(background_collector_type_);
283 if (foreground_collector_type == kCollectorTypeGSS) {
284 separate_non_moving_space = false;
285 }
286 std::unique_ptr<MemMap> main_mem_map_1;
287 std::unique_ptr<MemMap> main_mem_map_2;
Ian Rogers13735952014-10-08 12:43:28 -0700288 uint8_t* request_begin = requested_alloc_space_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700289 if (request_begin != nullptr && separate_non_moving_space) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700290 request_begin += non_moving_space_capacity;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700291 }
292 std::string error_str;
293 std::unique_ptr<MemMap> non_moving_space_mem_map;
Richard Uhler054a0782015-04-07 10:56:50 -0700294 ATRACE_BEGIN("Create heap maps");
Mathieu Chartierb363f662014-07-16 13:28:58 -0700295 if (separate_non_moving_space) {
Mathieu Chartier7247af52014-11-19 10:51:42 -0800296 // If we are the zygote, the non moving space becomes the zygote space when we run
297 // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
298 // rename the mem map later.
299 const char* space_name = is_zygote ? kZygoteSpaceName: kNonMovingSpaceName;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700300 // Reserve the non moving mem map before the other two since it needs to be at a specific
301 // address.
302 non_moving_space_mem_map.reset(
Mathieu Chartier7247af52014-11-19 10:51:42 -0800303 MemMap::MapAnonymous(space_name, requested_alloc_space_begin,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000304 non_moving_space_capacity, PROT_READ | PROT_WRITE, true, false,
305 &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700306 CHECK(non_moving_space_mem_map != nullptr) << error_str;
Mathieu Chartierc44ce2e2014-08-25 16:32:41 -0700307 // Try to reserve virtual memory at a lower address if we have a separate non moving space.
Ian Rogers13735952014-10-08 12:43:28 -0700308 request_begin = reinterpret_cast<uint8_t*>(300 * MB);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700309 }
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700310 // Attempt to create 2 mem maps at or after the requested begin.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800311 if (foreground_collector_type_ != kCollectorTypeCC) {
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700312 if (separate_non_moving_space) {
313 main_mem_map_1.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[0], request_begin,
314 capacity_, &error_str));
315 } else {
316 // If no separate non-moving space, the main space must come
317 // right after the image space to avoid a gap.
318 main_mem_map_1.reset(MemMap::MapAnonymous(kMemMapSpaceName[0], request_begin, capacity_,
319 PROT_READ | PROT_WRITE, true, false,
320 &error_str));
321 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800322 CHECK(main_mem_map_1.get() != nullptr) << error_str;
323 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700324 if (support_homogeneous_space_compaction ||
325 background_collector_type_ == kCollectorTypeSS ||
326 foreground_collector_type_ == kCollectorTypeSS) {
327 main_mem_map_2.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[1], main_mem_map_1->End(),
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700328 capacity_, &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700329 CHECK(main_mem_map_2.get() != nullptr) << error_str;
330 }
Richard Uhler054a0782015-04-07 10:56:50 -0700331 ATRACE_END();
332 ATRACE_BEGIN("Create spaces");
Mathieu Chartierb363f662014-07-16 13:28:58 -0700333 // Create the non moving space first so that bitmaps don't take up the address range.
334 if (separate_non_moving_space) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700335 // Non moving space is always dlmalloc since we currently don't have support for multiple
Zuo Wangf37a88b2014-07-10 04:26:41 -0700336 // active rosalloc spaces.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700337 const size_t size = non_moving_space_mem_map->Size();
338 non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700339 non_moving_space_mem_map.release(), "zygote / non moving space", kDefaultStartingSize,
Mathieu Chartierb363f662014-07-16 13:28:58 -0700340 initial_size, size, size, false);
Mathieu Chartier78408882014-04-11 18:06:01 -0700341 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Mathieu Chartierb363f662014-07-16 13:28:58 -0700342 CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
343 << requested_alloc_space_begin;
344 AddSpace(non_moving_space_);
345 }
346 // Create other spaces based on whether or not we have a moving GC.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800347 if (foreground_collector_type_ == kCollectorTypeCC) {
348 region_space_ = space::RegionSpace::Create("Region space", capacity_ * 2, request_begin);
349 AddSpace(region_space_);
Richard Uhler054a0782015-04-07 10:56:50 -0700350 } else if (IsMovingGc(foreground_collector_type_) &&
351 foreground_collector_type_ != kCollectorTypeGSS) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700352 // Create bump pointer spaces.
353 // We only to create the bump pointer if the foreground collector is a compacting GC.
354 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
355 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
356 main_mem_map_1.release());
357 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
358 AddSpace(bump_pointer_space_);
359 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
360 main_mem_map_2.release());
361 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
362 AddSpace(temp_space_);
363 CHECK(separate_non_moving_space);
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700364 } else {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700365 CreateMainMallocSpace(main_mem_map_1.release(), initial_size, growth_limit_, capacity_);
366 CHECK(main_space_ != nullptr);
367 AddSpace(main_space_);
368 if (!separate_non_moving_space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700369 non_moving_space_ = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700370 CHECK(!non_moving_space_->CanMoveObjects());
371 }
372 if (foreground_collector_type_ == kCollectorTypeGSS) {
373 CHECK_EQ(foreground_collector_type_, background_collector_type_);
374 // Create bump pointer spaces instead of a backup space.
375 main_mem_map_2.release();
376 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space 1",
377 kGSSBumpPointerSpaceCapacity, nullptr);
378 CHECK(bump_pointer_space_ != nullptr);
379 AddSpace(bump_pointer_space_);
380 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2",
381 kGSSBumpPointerSpaceCapacity, nullptr);
382 CHECK(temp_space_ != nullptr);
383 AddSpace(temp_space_);
384 } else if (main_mem_map_2.get() != nullptr) {
385 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
386 main_space_backup_.reset(CreateMallocSpaceFromMemMap(main_mem_map_2.release(), initial_size,
387 growth_limit_, capacity_, name, true));
388 CHECK(main_space_backup_.get() != nullptr);
389 // Add the space so its accounted for in the heap_begin and heap_end.
390 AddSpace(main_space_backup_.get());
Zuo Wangf37a88b2014-07-10 04:26:41 -0700391 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700392 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700393 CHECK(non_moving_space_ != nullptr);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700394 CHECK(!non_moving_space_->CanMoveObjects());
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700395 // Allocate the large object space.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800396 if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700397 large_object_space_ = space::FreeListSpace::Create("free list large object space", nullptr,
398 capacity_);
399 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800400 } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700401 large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
402 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700403 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700404 // Disable the large object space by making the cutoff excessively large.
405 large_object_threshold_ = std::numeric_limits<size_t>::max();
406 large_object_space_ = nullptr;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700407 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700408 if (large_object_space_ != nullptr) {
409 AddSpace(large_object_space_);
410 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700411 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700412 CHECK(!continuous_spaces_.empty());
413 // Relies on the spaces being sorted.
Ian Rogers13735952014-10-08 12:43:28 -0700414 uint8_t* heap_begin = continuous_spaces_.front()->Begin();
415 uint8_t* heap_end = continuous_spaces_.back()->Limit();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700416 size_t heap_capacity = heap_end - heap_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700417 // Remove the main backup space since it slows down the GC to have unused extra spaces.
Mathieu Chartier0310da52014-12-01 13:40:48 -0800418 // TODO: Avoid needing to do this.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700419 if (main_space_backup_.get() != nullptr) {
420 RemoveSpace(main_space_backup_.get());
421 }
Richard Uhler054a0782015-04-07 10:56:50 -0700422 ATRACE_END();
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800423 // Allocate the card table.
Richard Uhler054a0782015-04-07 10:56:50 -0700424 ATRACE_BEGIN("Create card table");
Ian Rogers1d54e732013-05-02 21:10:01 -0700425 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700426 CHECK(card_table_.get() != nullptr) << "Failed to create card table";
Richard Uhler054a0782015-04-07 10:56:50 -0700427 ATRACE_END();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800428 if (foreground_collector_type_ == kCollectorTypeCC && kUseTableLookupReadBarrier) {
429 rb_table_.reset(new accounting::ReadBarrierTable());
430 DCHECK(rb_table_->IsAllCleared());
431 }
Mathieu Chartier4858a932015-01-23 13:18:53 -0800432 if (GetImageSpace() != nullptr) {
433 // Don't add the image mod union table if we are running without an image, this can crash if
434 // we use the CardCache implementation.
435 accounting::ModUnionTable* mod_union_table = new accounting::ModUnionTableToZygoteAllocspace(
436 "Image mod-union table", this, GetImageSpace());
437 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
438 AddModUnionTable(mod_union_table);
439 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700440 if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800441 accounting::RememberedSet* non_moving_space_rem_set =
442 new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
443 CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
444 AddRememberedSet(non_moving_space_rem_set);
445 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700446 // TODO: Count objects in the image space here?
Ian Rogers3e5cf302014-05-20 16:40:37 -0700447 num_bytes_allocated_.StoreRelaxed(0);
Mathieu Chartierc1790162014-05-23 10:54:50 -0700448 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
449 kDefaultMarkStackSize));
450 const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
451 allocation_stack_.reset(accounting::ObjectStack::Create(
452 "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
453 live_stack_.reset(accounting::ObjectStack::Create(
454 "live stack", max_allocation_stack_size_, alloc_stack_capacity));
Mathieu Chartier65db8802012-11-20 12:36:46 -0800455 // It's still too early to take a lock because there are no threads yet, but we can create locks
456 // now. We don't create it earlier to make it clear that you can't use locks during heap
457 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700458 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700459 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
460 *gc_complete_lock_));
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800461 task_processor_.reset(new TaskProcessor());
462 pending_task_lock_ = new Mutex("Pending task lock");
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700463 if (ignore_max_footprint_) {
464 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700465 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700466 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700467 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800468 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800469 for (size_t i = 0; i < 2; ++i) {
470 const bool concurrent = i != 0;
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800471 if ((MayUseCollector(kCollectorTypeCMS) && concurrent) ||
472 (MayUseCollector(kCollectorTypeMS) && !concurrent)) {
473 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
474 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
475 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
476 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800477 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800478 if (kMovingCollector) {
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800479 if (MayUseCollector(kCollectorTypeSS) || MayUseCollector(kCollectorTypeGSS) ||
480 MayUseCollector(kCollectorTypeHomogeneousSpaceCompact) ||
481 use_homogeneous_space_compaction_for_oom_) {
482 // TODO: Clean this up.
483 const bool generational = foreground_collector_type_ == kCollectorTypeGSS;
484 semi_space_collector_ = new collector::SemiSpace(this, generational,
485 generational ? "generational" : "");
486 garbage_collectors_.push_back(semi_space_collector_);
487 }
488 if (MayUseCollector(kCollectorTypeCC)) {
489 concurrent_copying_collector_ = new collector::ConcurrentCopying(this);
490 garbage_collectors_.push_back(concurrent_copying_collector_);
491 }
492 if (MayUseCollector(kCollectorTypeMC)) {
493 mark_compact_collector_ = new collector::MarkCompact(this);
494 garbage_collectors_.push_back(mark_compact_collector_);
495 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700496 }
Andreas Gampee1cb2982014-08-27 11:01:09 -0700497 if (GetImageSpace() != nullptr && non_moving_space_ != nullptr &&
498 (is_zygote || separate_non_moving_space || foreground_collector_type_ == kCollectorTypeGSS)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700499 // 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 -0700500 // immune region won't break (eg. due to a large object allocated in the gap). This is only
501 // required when we're the zygote or using GSS.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700502 bool no_gap = MemMap::CheckNoGaps(GetImageSpace()->GetMemMap(),
503 non_moving_space_->GetMemMap());
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700504 if (!no_gap) {
Vladimir Marko17a924a2015-05-08 15:17:32 +0100505 MemMap::DumpMaps(LOG(ERROR), true);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700506 LOG(FATAL) << "There's a gap between the image space and the non-moving space";
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700507 }
508 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700509 if (running_on_valgrind_) {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700510 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700511 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800512 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800513 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700514 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700515}
516
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700517MemMap* Heap::MapAnonymousPreferredAddress(const char* name, uint8_t* request_begin,
518 size_t capacity, std::string* out_error_str) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700519 while (true) {
Kyungmin Leeef32b8f2014-10-23 09:32:05 +0900520 MemMap* map = MemMap::MapAnonymous(name, request_begin, capacity,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000521 PROT_READ | PROT_WRITE, true, false, out_error_str);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700522 if (map != nullptr || request_begin == nullptr) {
523 return map;
524 }
525 // Retry a second time with no specified request begin.
526 request_begin = nullptr;
527 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700528}
529
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800530bool Heap::MayUseCollector(CollectorType type) const {
531 return foreground_collector_type_ == type || background_collector_type_ == type;
532}
533
Zuo Wangf37a88b2014-07-10 04:26:41 -0700534space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap* mem_map, size_t initial_size,
535 size_t growth_limit, size_t capacity,
536 const char* name, bool can_move_objects) {
537 space::MallocSpace* malloc_space = nullptr;
538 if (kUseRosAlloc) {
539 // Create rosalloc space.
540 malloc_space = space::RosAllocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
541 initial_size, growth_limit, capacity,
542 low_memory_mode_, can_move_objects);
543 } else {
544 malloc_space = space::DlMallocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
545 initial_size, growth_limit, capacity,
546 can_move_objects);
547 }
548 if (collector::SemiSpace::kUseRememberedSet) {
549 accounting::RememberedSet* rem_set =
550 new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
551 CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
552 AddRememberedSet(rem_set);
553 }
554 CHECK(malloc_space != nullptr) << "Failed to create " << name;
555 malloc_space->SetFootprintLimit(malloc_space->Capacity());
556 return malloc_space;
557}
558
Mathieu Chartier31f44142014-04-08 14:40:03 -0700559void Heap::CreateMainMallocSpace(MemMap* mem_map, size_t initial_size, size_t growth_limit,
560 size_t capacity) {
561 // Is background compaction is enabled?
562 bool can_move_objects = IsMovingGc(background_collector_type_) !=
Zuo Wangf37a88b2014-07-10 04:26:41 -0700563 IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700564 // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
565 // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
566 // from the main space to the zygote space. If background compaction is enabled, always pass in
567 // that we can move objets.
568 if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
569 // After the zygote we want this to be false if we don't have background compaction enabled so
570 // that getting primitive array elements is faster.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700571 // We never have homogeneous compaction with GSS and don't need a space with movable objects.
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700572 can_move_objects = !HasZygoteSpace() && foreground_collector_type_ != kCollectorTypeGSS;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700573 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700574 if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
575 RemoveRememberedSet(main_space_);
576 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700577 const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
578 main_space_ = CreateMallocSpaceFromMemMap(mem_map, initial_size, growth_limit, capacity, name,
579 can_move_objects);
580 SetSpaceAsDefault(main_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700581 VLOG(heap) << "Created main space " << main_space_;
582}
583
Mathieu Chartier50482232013-11-21 11:48:14 -0800584void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800585 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800586 // These two allocators are only used internally and don't have any entrypoints.
587 CHECK_NE(allocator, kAllocatorTypeLOS);
588 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800589 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800590 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800591 SetQuickAllocEntryPointsAllocator(current_allocator_);
592 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
593 }
594}
595
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700596void Heap::DisableMovingGc() {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700597 if (IsMovingGc(foreground_collector_type_)) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700598 foreground_collector_type_ = kCollectorTypeCMS;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800599 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700600 if (IsMovingGc(background_collector_type_)) {
601 background_collector_type_ = foreground_collector_type_;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800602 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700603 TransitionCollector(foreground_collector_type_);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700604 ThreadList* tl = Runtime::Current()->GetThreadList();
605 Thread* self = Thread::Current();
606 ScopedThreadStateChange tsc(self, kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700607 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700608 // Something may have caused the transition to fail.
Mathieu Chartiere4927f62014-08-23 13:56:03 -0700609 if (!IsMovingGc(collector_type_) && non_moving_space_ != main_space_) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700610 CHECK(main_space_ != nullptr);
611 // The allocation stack may have non movable objects in it. We need to flush it since the GC
612 // can't only handle marking allocation stack objects of one non moving space and one main
613 // space.
614 {
615 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
616 FlushAllocStack();
617 }
618 main_space_->DisableMovingObjects();
619 non_moving_space_ = main_space_;
620 CHECK(!non_moving_space_->CanMoveObjects());
621 }
622 tl->ResumeAll();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800623}
624
Mathieu Chartier15d34022014-02-26 17:16:38 -0800625std::string Heap::SafeGetClassDescriptor(mirror::Class* klass) {
626 if (!IsValidContinuousSpaceObjectAddress(klass)) {
627 return StringPrintf("<non heap address klass %p>", klass);
628 }
629 mirror::Class* component_type = klass->GetComponentType<kVerifyNone>();
630 if (IsValidContinuousSpaceObjectAddress(component_type) && klass->IsArrayClass<kVerifyNone>()) {
631 std::string result("[");
632 result += SafeGetClassDescriptor(component_type);
633 return result;
634 } else if (UNLIKELY(klass->IsPrimitive<kVerifyNone>())) {
635 return Primitive::Descriptor(klass->GetPrimitiveType<kVerifyNone>());
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800636 } else if (UNLIKELY(klass->IsProxyClass<kVerifyNone>())) {
Mathieu Chartier15d34022014-02-26 17:16:38 -0800637 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(klass);
638 } else {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800639 mirror::DexCache* dex_cache = klass->GetDexCache<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800640 if (!IsValidContinuousSpaceObjectAddress(dex_cache)) {
641 return StringPrintf("<non heap address dex_cache %p>", dex_cache);
642 }
643 const DexFile* dex_file = dex_cache->GetDexFile();
644 uint16_t class_def_idx = klass->GetDexClassDefIndex();
645 if (class_def_idx == DexFile::kDexNoIndex16) {
646 return "<class def not found>";
647 }
648 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
649 const DexFile::TypeId& type_id = dex_file->GetTypeId(class_def.class_idx_);
650 return dex_file->GetTypeDescriptor(type_id);
651 }
652}
653
654std::string Heap::SafePrettyTypeOf(mirror::Object* obj) {
655 if (obj == nullptr) {
656 return "null";
657 }
658 mirror::Class* klass = obj->GetClass<kVerifyNone>();
659 if (klass == nullptr) {
660 return "(class=null)";
661 }
662 std::string result(SafeGetClassDescriptor(klass));
663 if (obj->IsClass()) {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800664 result += "<" + SafeGetClassDescriptor(obj->AsClass<kVerifyNone>()) + ">";
Mathieu Chartier15d34022014-02-26 17:16:38 -0800665 }
666 return result;
667}
668
669void Heap::DumpObject(std::ostream& stream, mirror::Object* obj) {
670 if (obj == nullptr) {
671 stream << "(obj=null)";
672 return;
673 }
674 if (IsAligned<kObjectAlignment>(obj)) {
675 space::Space* space = nullptr;
676 // Don't use find space since it only finds spaces which actually contain objects instead of
677 // spaces which may contain objects (e.g. cleared bump pointer spaces).
678 for (const auto& cur_space : continuous_spaces_) {
679 if (cur_space->HasAddress(obj)) {
680 space = cur_space;
681 break;
682 }
683 }
Mathieu Chartier15d34022014-02-26 17:16:38 -0800684 // Unprotect all the spaces.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800685 for (const auto& con_space : continuous_spaces_) {
686 mprotect(con_space->Begin(), con_space->Capacity(), PROT_READ | PROT_WRITE);
Mathieu Chartier15d34022014-02-26 17:16:38 -0800687 }
688 stream << "Object " << obj;
689 if (space != nullptr) {
690 stream << " in space " << *space;
691 }
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800692 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800693 stream << "\nclass=" << klass;
694 if (klass != nullptr) {
695 stream << " type= " << SafePrettyTypeOf(obj);
696 }
697 // Re-protect the address we faulted on.
698 mprotect(AlignDown(obj, kPageSize), kPageSize, PROT_NONE);
699 }
700}
701
Mathieu Chartier590fee92013-09-13 13:46:47 -0700702bool Heap::IsCompilingBoot() const {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800703 if (!Runtime::Current()->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700704 return false;
705 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700706 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800707 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700708 return false;
709 }
710 }
711 return true;
712}
713
714bool Heap::HasImageSpace() const {
715 for (const auto& space : continuous_spaces_) {
716 if (space->IsImageSpace()) {
717 return true;
718 }
719 }
720 return false;
721}
722
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800723void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700724 // Need to do this holding the lock to prevent races where the GC is about to run / running when
725 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800726 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700727 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800728 ++disable_moving_gc_count_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700729 if (IsMovingGc(collector_type_running_)) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -0700730 WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800731 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700732}
733
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800734void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700735 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800736 CHECK_GE(disable_moving_gc_count_, 0U);
737 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700738}
739
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800740void Heap::UpdateProcessState(ProcessState process_state) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800741 if (process_state_ != process_state) {
742 process_state_ = process_state;
Mathieu Chartier91e30632014-03-25 15:58:50 -0700743 for (size_t i = 1; i <= kCollectorTransitionStressIterations; ++i) {
744 // Start at index 1 to avoid "is always false" warning.
745 // Have iteration 1 always transition the collector.
746 TransitionCollector((((i & 1) == 1) == (process_state_ == kProcessStateJankPerceptible))
Mathieu Chartier31f44142014-04-08 14:40:03 -0700747 ? foreground_collector_type_ : background_collector_type_);
Mathieu Chartier91e30632014-03-25 15:58:50 -0700748 usleep(kCollectorTransitionStressWait);
749 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800750 if (process_state_ == kProcessStateJankPerceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800751 // Transition back to foreground right away to prevent jank.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700752 RequestCollectorTransition(foreground_collector_type_, 0);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800753 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800754 // Don't delay for debug builds since we may want to stress test the GC.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700755 // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
756 // special handling which does a homogenous space compaction once but then doesn't transition
757 // the collector.
758 RequestCollectorTransition(background_collector_type_,
759 kIsDebugBuild ? 0 : kCollectorTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800760 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800761 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800762}
763
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700764void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700765 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
766 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800767 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700768 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700769}
770
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800771// Visit objects when threads aren't suspended. If concurrent moving
772// GC, disable moving GC and suspend threads and then visit objects.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800773void Heap::VisitObjects(ObjectCallback callback, void* arg) {
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800774 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800775 Locks::mutator_lock_->AssertSharedHeld(self);
776 DCHECK(!Locks::mutator_lock_->IsExclusiveHeld(self)) << "Call VisitObjectsPaused() instead";
777 if (IsGcConcurrentAndMoving()) {
778 // Concurrent moving GC. Just suspending threads isn't sufficient
779 // because a collection isn't one big pause and we could suspend
780 // threads in the middle (between phases) of a concurrent moving
781 // collection where it's not easily known which objects are alive
782 // (both the region space and the non-moving space) or which
783 // copies of objects to visit, and the to-space invariant could be
784 // easily broken. Visit objects while GC isn't running by using
785 // IncrementDisableMovingGC() and threads are suspended.
786 IncrementDisableMovingGC(self);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800787 self->TransitionFromRunnableToSuspended(kWaitingForVisitObjects);
788 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700789 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800790 VisitObjectsInternalRegionSpace(callback, arg);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800791 VisitObjectsInternal(callback, arg);
792 tl->ResumeAll();
793 self->TransitionFromSuspendedToRunnable();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800794 DecrementDisableMovingGC(self);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800795 } else {
796 // GCs can move objects, so don't allow this.
797 ScopedAssertNoThreadSuspension ants(self, "Visiting objects");
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800798 DCHECK(region_space_ == nullptr);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800799 VisitObjectsInternal(callback, arg);
800 }
801}
802
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800803// Visit objects when threads are already suspended.
804void Heap::VisitObjectsPaused(ObjectCallback callback, void* arg) {
805 Thread* self = Thread::Current();
806 Locks::mutator_lock_->AssertExclusiveHeld(self);
807 VisitObjectsInternalRegionSpace(callback, arg);
808 VisitObjectsInternal(callback, arg);
809}
810
811// Visit objects in the region spaces.
812void Heap::VisitObjectsInternalRegionSpace(ObjectCallback callback, void* arg) {
813 Thread* self = Thread::Current();
814 Locks::mutator_lock_->AssertExclusiveHeld(self);
815 if (region_space_ != nullptr) {
816 DCHECK(IsGcConcurrentAndMoving());
817 if (!zygote_creation_lock_.IsExclusiveHeld(self)) {
818 // Exclude the pre-zygote fork time where the semi-space collector
819 // calls VerifyHeapReferences() as part of the zygote compaction
820 // which then would call here without the moving GC disabled,
821 // which is fine.
822 DCHECK(IsMovingGCDisabled(self));
823 }
824 region_space_->Walk(callback, arg);
825 }
826}
827
828// Visit objects in the other spaces.
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800829void Heap::VisitObjectsInternal(ObjectCallback callback, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700830 if (bump_pointer_space_ != nullptr) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800831 // Visit objects in bump pointer space.
832 bump_pointer_space_->Walk(callback, arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700833 }
834 // TODO: Switch to standard begin and end to use ranged a based loop.
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800835 for (auto* it = allocation_stack_->Begin(), *end = allocation_stack_->End(); it < end; ++it) {
836 mirror::Object* const obj = it->AsMirrorPtr();
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800837 if (obj != nullptr && obj->GetClass() != nullptr) {
838 // Avoid the race condition caused by the object not yet being written into the allocation
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800839 // stack or the class not yet being written in the object. Or, if
840 // kUseThreadLocalAllocationStack, there can be nulls on the allocation stack.
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800841 callback(obj, arg);
842 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700843 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800844 {
845 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
846 GetLiveBitmap()->Walk(callback, arg);
847 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700848}
849
850void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartier00b59152014-07-25 10:13:51 -0700851 space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
852 space::ContinuousSpace* space2 = non_moving_space_;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800853 // TODO: Generalize this to n bitmaps?
Mathieu Chartier00b59152014-07-25 10:13:51 -0700854 CHECK(space1 != nullptr);
855 CHECK(space2 != nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800856 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700857 (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
858 stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700859}
860
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700861void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700862 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700863}
864
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700865void Heap::AddSpace(space::Space* space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700866 CHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700867 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
868 if (space->IsContinuousSpace()) {
869 DCHECK(!space->IsDiscontinuousSpace());
870 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
871 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700872 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
873 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700874 if (live_bitmap != nullptr) {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700875 CHECK(mark_bitmap != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700876 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
877 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700878 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700879 continuous_spaces_.push_back(continuous_space);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700880 // Ensure that spaces remain sorted in increasing order of start address.
881 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
882 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
883 return a->Begin() < b->Begin();
884 });
Mathieu Chartier590fee92013-09-13 13:46:47 -0700885 } else {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700886 CHECK(space->IsDiscontinuousSpace());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700887 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700888 live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
889 mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700890 discontinuous_spaces_.push_back(discontinuous_space);
891 }
892 if (space->IsAllocSpace()) {
893 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700894 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800895}
896
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700897void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
898 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
899 if (continuous_space->IsDlMallocSpace()) {
900 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
901 } else if (continuous_space->IsRosAllocSpace()) {
902 rosalloc_space_ = continuous_space->AsRosAllocSpace();
903 }
904}
905
906void Heap::RemoveSpace(space::Space* space) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800907 DCHECK(space != nullptr);
908 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
909 if (space->IsContinuousSpace()) {
910 DCHECK(!space->IsDiscontinuousSpace());
911 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
912 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700913 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
914 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800915 if (live_bitmap != nullptr) {
916 DCHECK(mark_bitmap != nullptr);
917 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
918 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
919 }
920 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
921 DCHECK(it != continuous_spaces_.end());
922 continuous_spaces_.erase(it);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800923 } else {
924 DCHECK(space->IsDiscontinuousSpace());
925 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700926 live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
927 mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800928 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
929 discontinuous_space);
930 DCHECK(it != discontinuous_spaces_.end());
931 discontinuous_spaces_.erase(it);
932 }
933 if (space->IsAllocSpace()) {
934 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
935 DCHECK(it != alloc_spaces_.end());
936 alloc_spaces_.erase(it);
937 }
938}
939
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700940void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700941 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700942 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700943 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800944 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800945 uint64_t total_paused_time = 0;
Mathieu Chartier5a487192014-04-08 11:14:54 -0700946 for (auto& collector : garbage_collectors_) {
Mathieu Chartier104fa0c2014-08-07 14:26:27 -0700947 total_duration += collector->GetCumulativeTimings().GetTotalNs();
948 total_paused_time += collector->GetTotalPausedTimeNs();
949 collector->DumpPerformanceInfo(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700950 }
Ian Rogers3e5cf302014-05-20 16:40:37 -0700951 uint64_t allocation_time =
952 static_cast<uint64_t>(total_allocation_time_.LoadRelaxed()) * kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700953 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700954 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700955 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
956 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700957 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700958 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700959 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700960 }
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700961 uint64_t total_objects_allocated = GetObjectsAllocatedEver();
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700962 os << "Total number of allocations " << total_objects_allocated << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700963 os << "Total bytes allocated " << PrettySize(GetBytesAllocatedEver()) << "\n";
964 os << "Total bytes freed " << PrettySize(GetBytesFreedEver()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700965 os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700966 os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
967 os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700968 os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
969 os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700970 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700971 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
972 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
973 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700974 }
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700975 if (HasZygoteSpace()) {
976 os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
977 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700978 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700979 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
980 os << "Total GC count: " << GetGcCount() << "\n";
981 os << "Total GC time: " << PrettyDuration(GetGcTime()) << "\n";
982 os << "Total blocking GC count: " << GetBlockingGcCount() << "\n";
983 os << "Total blocking GC time: " << PrettyDuration(GetBlockingGcTime()) << "\n";
984
985 {
986 MutexLock mu(Thread::Current(), *gc_complete_lock_);
987 if (gc_count_rate_histogram_.SampleSize() > 0U) {
988 os << "Histogram of GC count per " << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
989 gc_count_rate_histogram_.DumpBins(os);
990 os << "\n";
991 }
992 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
993 os << "Histogram of blocking GC count per "
994 << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
995 blocking_gc_count_rate_histogram_.DumpBins(os);
996 os << "\n";
997 }
998 }
999
Mathieu Chartier73d1e172014-04-11 17:53:48 -07001000 BaseMutex::DumpAll(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001001}
1002
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001003uint64_t Heap::GetGcCount() const {
1004 uint64_t gc_count = 0U;
1005 for (auto& collector : garbage_collectors_) {
1006 gc_count += collector->GetCumulativeTimings().GetIterations();
1007 }
1008 return gc_count;
1009}
1010
1011uint64_t Heap::GetGcTime() const {
1012 uint64_t gc_time = 0U;
1013 for (auto& collector : garbage_collectors_) {
1014 gc_time += collector->GetCumulativeTimings().GetTotalNs();
1015 }
1016 return gc_time;
1017}
1018
1019uint64_t Heap::GetBlockingGcCount() const {
1020 return blocking_gc_count_;
1021}
1022
1023uint64_t Heap::GetBlockingGcTime() const {
1024 return blocking_gc_time_;
1025}
1026
1027void Heap::DumpGcCountRateHistogram(std::ostream& os) const {
1028 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1029 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1030 gc_count_rate_histogram_.DumpBins(os);
1031 }
1032}
1033
1034void Heap::DumpBlockingGcCountRateHistogram(std::ostream& os) const {
1035 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1036 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1037 blocking_gc_count_rate_histogram_.DumpBins(os);
1038 }
1039}
1040
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001041Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001042 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001043 STLDeleteElements(&garbage_collectors_);
1044 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001045 allocation_stack_->Reset();
1046 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001047 STLDeleteValues(&mod_union_tables_);
Mathieu Chartier0767c9a2014-03-26 12:53:19 -07001048 STLDeleteValues(&remembered_sets_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001049 STLDeleteElements(&continuous_spaces_);
1050 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001051 delete gc_complete_lock_;
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001052 delete pending_task_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001053 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001054}
1055
Ian Rogers1d54e732013-05-02 21:10:01 -07001056space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
1057 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001058 for (const auto& space : continuous_spaces_) {
1059 if (space->Contains(obj)) {
1060 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001061 }
1062 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001063 if (!fail_ok) {
1064 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
1065 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001066 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001067}
1068
Ian Rogers1d54e732013-05-02 21:10:01 -07001069space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
1070 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001071 for (const auto& space : discontinuous_spaces_) {
1072 if (space->Contains(obj)) {
1073 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -07001074 }
1075 }
1076 if (!fail_ok) {
1077 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
1078 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001079 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001080}
1081
1082space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
1083 space::Space* result = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001084 if (result != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001085 return result;
1086 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001087 return FindDiscontinuousSpaceFromObject(obj, fail_ok);
Ian Rogers1d54e732013-05-02 21:10:01 -07001088}
1089
1090space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001091 for (const auto& space : continuous_spaces_) {
1092 if (space->IsImageSpace()) {
1093 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001094 }
1095 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001096 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001097}
1098
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001099void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001100 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001101 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001102 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001103 << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM";
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001104 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001105 if (total_bytes_free >= byte_count) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001106 space::AllocSpace* space = nullptr;
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001107 if (allocator_type == kAllocatorTypeNonMoving) {
1108 space = non_moving_space_;
1109 } else if (allocator_type == kAllocatorTypeRosAlloc ||
1110 allocator_type == kAllocatorTypeDlMalloc) {
1111 space = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -07001112 } else if (allocator_type == kAllocatorTypeBumpPointer ||
1113 allocator_type == kAllocatorTypeTLAB) {
1114 space = bump_pointer_space_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001115 } else if (allocator_type == kAllocatorTypeRegion ||
1116 allocator_type == kAllocatorTypeRegionTLAB) {
1117 space = region_space_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001118 }
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001119 if (space != nullptr) {
1120 space->LogFragmentationAllocFailure(oss, byte_count);
1121 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001122 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001123 self->ThrowOutOfMemoryError(oss.str().c_str());
1124}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001125
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001126void Heap::DoPendingCollectorTransition() {
1127 CollectorType desired_collector_type = desired_collector_type_;
Mathieu Chartierb2728552014-09-08 20:08:41 +00001128 // Launch homogeneous space compaction if it is desired.
1129 if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
1130 if (!CareAboutPauseTimes()) {
1131 PerformHomogeneousSpaceCompact();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001132 } else {
1133 VLOG(gc) << "Homogeneous compaction ignored due to jank perceptible process state";
Mathieu Chartierb2728552014-09-08 20:08:41 +00001134 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001135 } else {
1136 TransitionCollector(desired_collector_type);
Mathieu Chartierb2728552014-09-08 20:08:41 +00001137 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001138}
1139
1140void Heap::Trim(Thread* self) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001141 if (!CareAboutPauseTimes()) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001142 ATRACE_BEGIN("Deflating monitors");
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001143 // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
1144 // about pauses.
1145 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001146 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001147 uint64_t start_time = NanoTime();
1148 size_t count = runtime->GetMonitorList()->DeflateMonitors();
1149 VLOG(heap) << "Deflating " << count << " monitors took "
1150 << PrettyDuration(NanoTime() - start_time);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001151 runtime->GetThreadList()->ResumeAll();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001152 ATRACE_END();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001153 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001154 TrimIndirectReferenceTables(self);
1155 TrimSpaces(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001156}
1157
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001158class TrimIndirectReferenceTableClosure : public Closure {
1159 public:
1160 explicit TrimIndirectReferenceTableClosure(Barrier* barrier) : barrier_(barrier) {
1161 }
1162 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1163 ATRACE_BEGIN("Trimming reference table");
1164 thread->GetJniEnv()->locals.Trim();
1165 ATRACE_END();
Lei Lidd9943d2015-02-02 14:24:44 +08001166 // If thread is a running mutator, then act on behalf of the trim thread.
1167 // See the code in ThreadList::RunCheckpoint.
1168 if (thread->GetState() == kRunnable) {
1169 barrier_->Pass(Thread::Current());
1170 }
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001171 }
1172
1173 private:
1174 Barrier* const barrier_;
1175};
1176
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001177void Heap::TrimIndirectReferenceTables(Thread* self) {
1178 ScopedObjectAccess soa(self);
1179 ATRACE_BEGIN(__FUNCTION__);
1180 JavaVMExt* vm = soa.Vm();
1181 // Trim globals indirect reference table.
1182 vm->TrimGlobals();
1183 // Trim locals indirect reference tables.
1184 Barrier barrier(0);
1185 TrimIndirectReferenceTableClosure closure(&barrier);
1186 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1187 size_t barrier_count = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
Lei Lidd9943d2015-02-02 14:24:44 +08001188 if (barrier_count != 0) {
1189 barrier.Increment(self, barrier_count);
1190 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001191 ATRACE_END();
1192}
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001193
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001194void Heap::TrimSpaces(Thread* self) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001195 {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001196 // Need to do this before acquiring the locks since we don't want to get suspended while
1197 // holding any locks.
1198 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001199 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1200 // trimming.
1201 MutexLock mu(self, *gc_complete_lock_);
1202 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001203 WaitForGcToCompleteLocked(kGcCauseTrim, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001204 collector_type_running_ = kCollectorTypeHeapTrim;
1205 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001206 ATRACE_BEGIN(__FUNCTION__);
1207 const uint64_t start_ns = NanoTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001208 // Trim the managed spaces.
1209 uint64_t total_alloc_space_allocated = 0;
1210 uint64_t total_alloc_space_size = 0;
1211 uint64_t managed_reclaimed = 0;
1212 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001213 if (space->IsMallocSpace()) {
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001214 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1215 if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1216 // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1217 // for a long period of time.
1218 managed_reclaimed += malloc_space->Trim();
1219 }
1220 total_alloc_space_size += malloc_space->Size();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001221 }
1222 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001223 total_alloc_space_allocated = GetBytesAllocated();
1224 if (large_object_space_ != nullptr) {
1225 total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1226 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07001227 if (bump_pointer_space_ != nullptr) {
1228 total_alloc_space_allocated -= bump_pointer_space_->Size();
1229 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001230 if (region_space_ != nullptr) {
1231 total_alloc_space_allocated -= region_space_->GetBytesAllocated();
1232 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001233 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1234 static_cast<float>(total_alloc_space_size);
1235 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001236 // We never move things in the native heap, so we can finish the GC at this point.
1237 FinishGC(self, collector::kGcTypeNone);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001238 size_t native_reclaimed = 0;
Ian Rogers872dd822014-10-30 11:19:14 -07001239
1240#ifdef HAVE_ANDROID_OS
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001241 // Only trim the native heap if we don't care about pauses.
1242 if (!CareAboutPauseTimes()) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001243#if defined(USE_DLMALLOC)
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001244 // Trim the native heap.
1245 dlmalloc_trim(0);
1246 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001247#elif defined(USE_JEMALLOC)
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001248 // Jemalloc does it's own internal trimming.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001249#else
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001250 UNIMPLEMENTED(WARNING) << "Add trimming support";
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001251#endif
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001252 }
Ian Rogers872dd822014-10-30 11:19:14 -07001253#endif // HAVE_ANDROID_OS
Mathieu Chartier590fee92013-09-13 13:46:47 -07001254 uint64_t end_ns = NanoTime();
1255 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
1256 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
1257 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
1258 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
1259 << "%.";
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001260 ATRACE_END();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001261}
1262
1263bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
1264 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
1265 // taking the lock.
1266 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -07001267 return true;
1268 }
Mathieu Chartier15d34022014-02-26 17:16:38 -08001269 return IsAligned<kObjectAlignment>(obj) && FindSpaceFromObject(obj, true) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001270}
1271
Mathieu Chartierd68ac702014-02-11 14:50:51 -08001272bool Heap::IsNonDiscontinuousSpaceHeapAddress(const mirror::Object* obj) const {
1273 return FindContinuousSpaceFromObject(obj, true) != nullptr;
1274}
1275
Mathieu Chartier15d34022014-02-26 17:16:38 -08001276bool Heap::IsValidContinuousSpaceObjectAddress(const mirror::Object* obj) const {
1277 if (obj == nullptr || !IsAligned<kObjectAlignment>(obj)) {
1278 return false;
1279 }
1280 for (const auto& space : continuous_spaces_) {
1281 if (space->HasAddress(obj)) {
1282 return true;
1283 }
1284 }
1285 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -07001286}
1287
Ian Rogersef7d42f2014-01-06 12:55:46 -08001288bool Heap::IsLiveObjectLocked(mirror::Object* obj, bool search_allocation_stack,
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001289 bool search_live_stack, bool sorted) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001290 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
1291 return false;
1292 }
1293 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001294 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001295 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08001296 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001297 return true;
1298 }
1299 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1300 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001301 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1302 // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1303 return temp_space_->Contains(obj);
Ian Rogers1d54e732013-05-02 21:10:01 -07001304 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001305 if (region_space_ != nullptr && region_space_->HasAddress(obj)) {
1306 return true;
1307 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001308 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001309 space::DiscontinuousSpace* d_space = nullptr;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001310 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001311 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001312 return true;
1313 }
1314 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001315 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001316 if (d_space != nullptr) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001317 if (d_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001318 return true;
1319 }
1320 }
1321 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001322 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001323 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1324 if (i > 0) {
1325 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -07001326 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001327 if (search_allocation_stack) {
1328 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001329 if (allocation_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001330 return true;
1331 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001332 } else if (allocation_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001333 return true;
1334 }
1335 }
1336
1337 if (search_live_stack) {
1338 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001339 if (live_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001340 return true;
1341 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001342 } else if (live_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001343 return true;
1344 }
1345 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001346 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001347 // We need to check the bitmaps again since there is a race where we mark something as live and
1348 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001349 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001350 if (c_space->GetLiveBitmap()->Test(obj)) {
1351 return true;
1352 }
1353 } else {
1354 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001355 if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj)) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001356 return true;
1357 }
1358 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001359 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001360}
1361
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001362std::string Heap::DumpSpaces() const {
1363 std::ostringstream oss;
1364 DumpSpaces(oss);
1365 return oss.str();
1366}
1367
1368void Heap::DumpSpaces(std::ostream& stream) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001369 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001370 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1371 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001372 stream << space << " " << *space << "\n";
1373 if (live_bitmap != nullptr) {
1374 stream << live_bitmap << " " << *live_bitmap << "\n";
1375 }
1376 if (mark_bitmap != nullptr) {
1377 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1378 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001379 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001380 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001381 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001382 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001383}
1384
Ian Rogersef7d42f2014-01-06 12:55:46 -08001385void Heap::VerifyObjectBody(mirror::Object* obj) {
Stephen Hines22c6a812014-07-16 11:03:43 -07001386 if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1387 return;
1388 }
1389
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001390 // Ignore early dawn of the universe verifications.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001391 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.LoadRelaxed()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001392 return;
1393 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08001394 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001395 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
Mathieu Chartier4e305412014-02-19 10:54:44 -08001396 CHECK(c != nullptr) << "Null class in object " << obj;
1397 CHECK(IsAligned<kObjectAlignment>(c)) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001398 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001399
Mathieu Chartier4e305412014-02-19 10:54:44 -08001400 if (verify_object_mode_ > kVerifyObjectModeFast) {
1401 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001402 CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001403 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001404}
1405
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001406void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001407 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001408}
1409
1410void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001411 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001412 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001413}
1414
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001415void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
Mathieu Chartier601276a2014-03-20 15:12:30 -07001416 // Use signed comparison since freed bytes can be negative when background compaction foreground
1417 // transitions occurs. This is caused by the moving objects from a bump pointer space to a
1418 // free list backed space typically increasing memory footprint due to padding and binning.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001419 DCHECK_LE(freed_bytes, static_cast<int64_t>(num_bytes_allocated_.LoadRelaxed()));
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001420 // Note: This relies on 2s complement for handling negative freed_bytes.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001421 num_bytes_allocated_.FetchAndSubSequentiallyConsistent(static_cast<ssize_t>(freed_bytes));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001422 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001423 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001424 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001425 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001426 // TODO: Do this concurrently.
1427 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1428 global_stats->freed_objects += freed_objects;
1429 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001430 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001431}
1432
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001433void Heap::RecordFreeRevoke() {
1434 // Subtract num_bytes_freed_revoke_ from num_bytes_allocated_ to cancel out the
1435 // the ahead-of-time, bulk counting of bytes allocated in rosalloc thread-local buffers.
1436 // If there's a concurrent revoke, ok to not necessarily reset num_bytes_freed_revoke_
1437 // all the way to zero exactly as the remainder will be subtracted at the next GC.
1438 size_t bytes_freed = num_bytes_freed_revoke_.LoadSequentiallyConsistent();
1439 CHECK_GE(num_bytes_freed_revoke_.FetchAndSubSequentiallyConsistent(bytes_freed),
1440 bytes_freed) << "num_bytes_freed_revoke_ underflow";
1441 CHECK_GE(num_bytes_allocated_.FetchAndSubSequentiallyConsistent(bytes_freed),
1442 bytes_freed) << "num_bytes_allocated_ underflow";
1443 GetCurrentGcIteration()->SetFreedRevoke(bytes_freed);
1444}
1445
Zuo Wangf37a88b2014-07-10 04:26:41 -07001446space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
1447 for (const auto& space : continuous_spaces_) {
1448 if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1449 if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1450 return space->AsContinuousSpace()->AsRosAllocSpace();
1451 }
1452 }
1453 }
1454 return nullptr;
1455}
1456
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001457mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001458 size_t alloc_size, size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001459 size_t* usable_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001460 size_t* bytes_tl_bulk_allocated,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001461 mirror::Class** klass) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001462 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierf4f38432014-09-03 11:21:08 -07001463 // Make sure there is no pending exception since we may need to throw an OOME.
1464 self->AssertNoPendingException();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001465 DCHECK(klass != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001466 StackHandleScope<1> hs(self);
1467 HandleWrapper<mirror::Class> h(hs.NewHandleWrapper(klass));
1468 klass = nullptr; // Invalidate for safety.
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001469 // The allocation failed. If the GC is running, block until it completes, and then retry the
1470 // allocation.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001471 collector::GcType last_gc = WaitForGcToComplete(kGcCauseForAlloc, self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001472 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001473 // If we were the default allocator but the allocator changed while we were suspended,
1474 // abort the allocation.
1475 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001476 return nullptr;
1477 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001478 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001479 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001480 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001481 if (ptr != nullptr) {
1482 return ptr;
1483 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001484 }
1485
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001486 collector::GcType tried_type = next_gc_type_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001487 const bool gc_ran =
1488 CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1489 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1490 return nullptr;
1491 }
1492 if (gc_ran) {
1493 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001494 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001495 if (ptr != nullptr) {
1496 return ptr;
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001497 }
1498 }
1499
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001500 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001501 for (collector::GcType gc_type : gc_plan_) {
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001502 if (gc_type == tried_type) {
1503 continue;
1504 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001505 // Attempt to run the collector, if we succeed, re-try the allocation.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001506 const bool plan_gc_ran =
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001507 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1508 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001509 return nullptr;
1510 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001511 if (plan_gc_ran) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001512 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001513 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001514 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001515 if (ptr != nullptr) {
1516 return ptr;
1517 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001518 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001519 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001520 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001521 // Try harder, growing the heap if necessary.
1522 mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001523 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001524 if (ptr != nullptr) {
1525 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001526 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001527 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1528 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1529 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1530 // OOME.
1531 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1532 << " allocation";
1533 // TODO: Run finalization, but this may cause more allocations to occur.
1534 // We don't need a WaitForGcToComplete here either.
1535 DCHECK(!gc_plan_.empty());
1536 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
1537 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1538 return nullptr;
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001539 }
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001540 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size,
1541 bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001542 if (ptr == nullptr) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001543 const uint64_t current_time = NanoTime();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001544 switch (allocator) {
1545 case kAllocatorTypeRosAlloc:
1546 // Fall-through.
1547 case kAllocatorTypeDlMalloc: {
1548 if (use_homogeneous_space_compaction_for_oom_ &&
1549 current_time - last_time_homogeneous_space_compaction_by_oom_ >
1550 min_interval_homogeneous_space_compaction_by_oom_) {
1551 last_time_homogeneous_space_compaction_by_oom_ = current_time;
1552 HomogeneousSpaceCompactResult result = PerformHomogeneousSpaceCompact();
1553 switch (result) {
1554 case HomogeneousSpaceCompactResult::kSuccess:
1555 // If the allocation succeeded, we delayed an oom.
1556 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001557 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001558 if (ptr != nullptr) {
1559 count_delayed_oom_++;
1560 }
1561 break;
1562 case HomogeneousSpaceCompactResult::kErrorReject:
1563 // Reject due to disabled moving GC.
1564 break;
1565 case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1566 // Throw OOM by default.
1567 break;
1568 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07001569 UNIMPLEMENTED(FATAL) << "homogeneous space compaction result: "
1570 << static_cast<size_t>(result);
1571 UNREACHABLE();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001572 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001573 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001574 // Always print that we ran homogeneous space compation since this can cause jank.
1575 VLOG(heap) << "Ran heap homogeneous space compaction, "
1576 << " requested defragmentation "
1577 << count_requested_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1578 << " performed defragmentation "
1579 << count_performed_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1580 << " ignored homogeneous space compaction "
1581 << count_ignored_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1582 << " delayed count = "
1583 << count_delayed_oom_.LoadSequentiallyConsistent();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001584 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001585 break;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001586 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001587 case kAllocatorTypeNonMoving: {
1588 // Try to transition the heap if the allocation failure was due to the space being full.
1589 if (!IsOutOfMemoryOnAllocation<false>(allocator, alloc_size)) {
1590 // If we aren't out of memory then the OOM was probably from the non moving space being
1591 // full. Attempt to disable compaction and turn the main space into a non moving space.
1592 DisableMovingGc();
1593 // If we are still a moving GC then something must have caused the transition to fail.
1594 if (IsMovingGc(collector_type_)) {
1595 MutexLock mu(self, *gc_complete_lock_);
1596 // If we couldn't disable moving GC, just throw OOME and return null.
1597 LOG(WARNING) << "Couldn't disable moving GC with disable GC count "
1598 << disable_moving_gc_count_;
1599 } else {
1600 LOG(WARNING) << "Disabled moving GC due to the non moving space being full";
1601 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001602 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001603 }
1604 }
1605 break;
1606 }
1607 default: {
1608 // Do nothing for others allocators.
1609 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001610 }
1611 }
1612 // If the allocation hasn't succeeded by this point, throw an OOM error.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001613 if (ptr == nullptr) {
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001614 ThrowOutOfMemoryError(self, alloc_size, allocator);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001615 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001616 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001617}
1618
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001619void Heap::SetTargetHeapUtilization(float target) {
1620 DCHECK_GT(target, 0.0f); // asserted in Java code
1621 DCHECK_LT(target, 1.0f);
1622 target_utilization_ = target;
1623}
1624
Ian Rogers1d54e732013-05-02 21:10:01 -07001625size_t Heap::GetObjectsAllocated() const {
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001626 Thread* self = Thread::Current();
1627 ScopedThreadStateChange tsc(self, kWaitingForGetObjectsAllocated);
1628 auto* tl = Runtime::Current()->GetThreadList();
1629 // Need SuspendAll here to prevent lock violation if RosAlloc does it during InspectAll.
1630 tl->SuspendAll(__FUNCTION__);
Ian Rogers1d54e732013-05-02 21:10:01 -07001631 size_t total = 0;
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001632 {
1633 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1634 for (space::AllocSpace* space : alloc_spaces_) {
1635 total += space->GetObjectsAllocated();
1636 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001637 }
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001638 tl->ResumeAll();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001639 return total;
1640}
1641
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001642uint64_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier4edd8472015-06-01 10:47:36 -07001643 uint64_t total = GetObjectsFreedEver();
1644 // If we are detached, we can't use GetObjectsAllocated since we can't change thread states.
1645 if (Thread::Current() != nullptr) {
1646 total += GetObjectsAllocated();
1647 }
1648 return total;
Ian Rogers1d54e732013-05-02 21:10:01 -07001649}
1650
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001651uint64_t Heap::GetBytesAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001652 return GetBytesFreedEver() + GetBytesAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001653}
1654
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001655class InstanceCounter {
1656 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001657 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001658 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001659 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001660 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001661 static void Callback(mirror::Object* obj, void* arg)
1662 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1663 InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1664 mirror::Class* instance_class = obj->GetClass();
1665 CHECK(instance_class != nullptr);
1666 for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
1667 if (instance_counter->use_is_assignable_from_) {
1668 if (instance_counter->classes_[i]->IsAssignableFrom(instance_class)) {
1669 ++instance_counter->counts_[i];
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001670 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001671 } else if (instance_class == instance_counter->classes_[i]) {
1672 ++instance_counter->counts_[i];
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001673 }
1674 }
1675 }
1676
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001677 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001678 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001679 bool use_is_assignable_from_;
1680 uint64_t* const counts_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001681 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001682};
1683
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001684void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001685 uint64_t* counts) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001686 InstanceCounter counter(classes, use_is_assignable_from, counts);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001687 VisitObjects(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001688}
1689
Elliott Hughes3b78c942013-01-15 17:35:41 -08001690class InstanceCollector {
1691 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001692 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001693 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1694 : class_(c), max_count_(max_count), instances_(instances) {
1695 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001696 static void Callback(mirror::Object* obj, void* arg)
1697 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1698 DCHECK(arg != nullptr);
1699 InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001700 if (obj->GetClass() == instance_collector->class_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001701 if (instance_collector->max_count_ == 0 ||
1702 instance_collector->instances_.size() < instance_collector->max_count_) {
1703 instance_collector->instances_.push_back(obj);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001704 }
1705 }
1706 }
1707
1708 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001709 const mirror::Class* const class_;
1710 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001711 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001712 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1713};
1714
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001715void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1716 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001717 InstanceCollector collector(c, max_count, instances);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001718 VisitObjects(&InstanceCollector::Callback, &collector);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001719}
1720
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001721class ReferringObjectsFinder {
1722 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001723 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1724 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001725 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1726 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1727 }
1728
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001729 static void Callback(mirror::Object* obj, void* arg)
1730 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1731 reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1732 }
1733
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001734 // For bitmap Visit.
1735 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1736 // annotalysis on visitors.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001737 void operator()(mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001738 o->VisitReferences<true>(*this, VoidFunctor());
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001739 }
1740
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001741 // For Object::VisitReferences.
Mathieu Chartier407f7022014-02-18 14:37:05 -08001742 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1743 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001744 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08001745 if (ref == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1746 referring_objects_.push_back(obj);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001747 }
1748 }
1749
1750 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001751 const mirror::Object* const object_;
1752 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001753 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001754 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1755};
1756
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001757void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1758 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001759 ReferringObjectsFinder finder(o, max_count, referring_objects);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001760 VisitObjects(&ReferringObjectsFinder::Callback, &finder);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001761}
1762
Ian Rogers30fab402012-01-23 15:43:46 -08001763void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001764 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1765 // last GC will not have necessarily been cleared.
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001766 CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001767}
1768
Zuo Wangf37a88b2014-07-10 04:26:41 -07001769HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
1770 Thread* self = Thread::Current();
1771 // Inc requested homogeneous space compaction.
1772 count_requested_homogeneous_space_compaction_++;
1773 // Store performed homogeneous space compaction at a new request arrival.
1774 ThreadList* tl = Runtime::Current()->GetThreadList();
1775 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1776 Locks::mutator_lock_->AssertNotHeld(self);
1777 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001778 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001779 MutexLock mu(self, *gc_complete_lock_);
1780 // Ensure there is only one GC at a time.
1781 WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
1782 // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable count
1783 // is non zero.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001784 // If the collector type changed to something which doesn't benefit from homogeneous space compaction,
Zuo Wangf37a88b2014-07-10 04:26:41 -07001785 // exit.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001786 if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
1787 !main_space_->CanMoveObjects()) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001788 return HomogeneousSpaceCompactResult::kErrorReject;
1789 }
1790 collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
1791 }
1792 if (Runtime::Current()->IsShuttingDown(self)) {
1793 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1794 // cause objects to get finalized.
1795 FinishGC(self, collector::kGcTypeNone);
1796 return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
1797 }
1798 // Suspend all threads.
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001799 tl->SuspendAll(__FUNCTION__);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001800 uint64_t start_time = NanoTime();
1801 // Launch compaction.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001802 space::MallocSpace* to_space = main_space_backup_.release();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001803 space::MallocSpace* from_space = main_space_;
1804 to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1805 const uint64_t space_size_before_compaction = from_space->Size();
Mathieu Chartierb363f662014-07-16 13:28:58 -07001806 AddSpace(to_space);
Mathieu Chartier0310da52014-12-01 13:40:48 -08001807 // Make sure that we will have enough room to copy.
1808 CHECK_GE(to_space->GetFootprintLimit(), from_space->GetFootprintLimit());
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001809 collector::GarbageCollector* collector = Compact(to_space, from_space,
1810 kGcCauseHomogeneousSpaceCompact);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001811 const uint64_t space_size_after_compaction = to_space->Size();
Mathieu Chartierb363f662014-07-16 13:28:58 -07001812 main_space_ = to_space;
1813 main_space_backup_.reset(from_space);
1814 RemoveSpace(from_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001815 SetSpaceAsDefault(main_space_); // Set as default to reset the proper dlmalloc space.
1816 // Update performed homogeneous space compaction count.
1817 count_performed_homogeneous_space_compaction_++;
1818 // Print statics log and resume all threads.
1819 uint64_t duration = NanoTime() - start_time;
Mathieu Chartier98172a62014-09-02 12:33:25 -07001820 VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
1821 << PrettySize(space_size_before_compaction) << " -> "
1822 << PrettySize(space_size_after_compaction) << " compact-ratio: "
1823 << std::fixed << static_cast<double>(space_size_after_compaction) /
1824 static_cast<double>(space_size_before_compaction);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001825 tl->ResumeAll();
1826 // Finish GC.
1827 reference_processor_.EnqueueClearedReferences(self);
1828 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001829 LogGC(kGcCauseHomogeneousSpaceCompact, collector);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001830 FinishGC(self, collector::kGcTypeFull);
1831 return HomogeneousSpaceCompactResult::kSuccess;
1832}
1833
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001834void Heap::TransitionCollector(CollectorType collector_type) {
1835 if (collector_type == collector_type_) {
1836 return;
1837 }
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001838 VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1839 << " -> " << static_cast<int>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001840 uint64_t start_time = NanoTime();
Ian Rogers3e5cf302014-05-20 16:40:37 -07001841 uint32_t before_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001842 Runtime* const runtime = Runtime::Current();
1843 ThreadList* const tl = runtime->GetThreadList();
1844 Thread* const self = Thread::Current();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001845 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1846 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001847 // Busy wait until we can GC (StartGC can fail if we have a non-zero
1848 // compacting_gc_disable_count_, this should rarely occurs).
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001849 for (;;) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001850 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001851 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001852 MutexLock mu(self, *gc_complete_lock_);
1853 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001854 WaitForGcToCompleteLocked(kGcCauseCollectorTransition, self);
Mathieu Chartiere4927f62014-08-23 13:56:03 -07001855 // Currently we only need a heap transition if we switch from a moving collector to a
1856 // non-moving one, or visa versa.
1857 const bool copying_transition = IsMovingGc(collector_type_) != IsMovingGc(collector_type);
Mathieu Chartierb38d4832014-04-10 10:56:55 -07001858 // If someone else beat us to it and changed the collector before we could, exit.
1859 // This is safe to do before the suspend all since we set the collector_type_running_ before
1860 // we exit the loop. If another thread attempts to do the heap transition before we exit,
1861 // then it would get blocked on WaitForGcToCompleteLocked.
1862 if (collector_type == collector_type_) {
1863 return;
1864 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001865 // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1866 if (!copying_transition || disable_moving_gc_count_ == 0) {
1867 // TODO: Not hard code in semi-space collector?
1868 collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1869 break;
1870 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001871 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001872 usleep(1000);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001873 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001874 if (runtime->IsShuttingDown(self)) {
Hiroshi Yamauchia6a8d142014-05-12 16:57:33 -07001875 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1876 // cause objects to get finalized.
1877 FinishGC(self, collector::kGcTypeNone);
1878 return;
1879 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001880 collector::GarbageCollector* collector = nullptr;
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001881 tl->SuspendAll(__FUNCTION__);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001882 switch (collector_type) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001883 case kCollectorTypeSS: {
Mathieu Chartier31f44142014-04-08 14:40:03 -07001884 if (!IsMovingGc(collector_type_)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001885 // Create the bump pointer space from the backup space.
1886 CHECK(main_space_backup_ != nullptr);
1887 std::unique_ptr<MemMap> mem_map(main_space_backup_->ReleaseMemMap());
Mathieu Chartier31f44142014-04-08 14:40:03 -07001888 // We are transitioning from non moving GC -> moving GC, since we copied from the bump
1889 // pointer space last transition it will be protected.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001890 CHECK(mem_map != nullptr);
1891 mem_map->Protect(PROT_READ | PROT_WRITE);
1892 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space",
1893 mem_map.release());
1894 AddSpace(bump_pointer_space_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001895 collector = Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001896 // Use the now empty main space mem map for the bump pointer temp space.
1897 mem_map.reset(main_space_->ReleaseMemMap());
Mathieu Chartier00b59152014-07-25 10:13:51 -07001898 // Unset the pointers just in case.
1899 if (dlmalloc_space_ == main_space_) {
1900 dlmalloc_space_ = nullptr;
1901 } else if (rosalloc_space_ == main_space_) {
1902 rosalloc_space_ = nullptr;
1903 }
Mathieu Chartier2796a162014-07-25 11:50:47 -07001904 // Remove the main space so that we don't try to trim it, this doens't work for debug
1905 // builds since RosAlloc attempts to read the magic number from a protected page.
1906 RemoveSpace(main_space_);
Mathieu Chartierc5a83472014-07-23 18:45:17 -07001907 RemoveRememberedSet(main_space_);
Mathieu Chartier2796a162014-07-25 11:50:47 -07001908 delete main_space_; // Delete the space since it has been removed.
Mathieu Chartierc5a83472014-07-23 18:45:17 -07001909 main_space_ = nullptr;
Mathieu Chartier2796a162014-07-25 11:50:47 -07001910 RemoveRememberedSet(main_space_backup_.get());
1911 main_space_backup_.reset(nullptr); // Deletes the space.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001912 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
1913 mem_map.release());
1914 AddSpace(temp_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07001915 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001916 break;
1917 }
1918 case kCollectorTypeMS:
1919 // Fall through.
1920 case kCollectorTypeCMS: {
Mathieu Chartier31f44142014-04-08 14:40:03 -07001921 if (IsMovingGc(collector_type_)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001922 CHECK(temp_space_ != nullptr);
1923 std::unique_ptr<MemMap> mem_map(temp_space_->ReleaseMemMap());
1924 RemoveSpace(temp_space_);
1925 temp_space_ = nullptr;
Mathieu Chartier36dab362014-07-30 14:59:56 -07001926 mem_map->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier0310da52014-12-01 13:40:48 -08001927 CreateMainMallocSpace(mem_map.get(), kDefaultInitialSize,
1928 std::min(mem_map->Size(), growth_limit_), mem_map->Size());
Mathieu Chartierb363f662014-07-16 13:28:58 -07001929 mem_map.release();
Mathieu Chartier31f44142014-04-08 14:40:03 -07001930 // Compact to the main space from the bump pointer space, don't need to swap semispaces.
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001931 AddSpace(main_space_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001932 collector = Compact(main_space_, bump_pointer_space_, kGcCauseCollectorTransition);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001933 mem_map.reset(bump_pointer_space_->ReleaseMemMap());
1934 RemoveSpace(bump_pointer_space_);
1935 bump_pointer_space_ = nullptr;
1936 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07001937 // Temporarily unprotect the backup mem map so rosalloc can write the debug magic number.
1938 if (kIsDebugBuild && kUseRosAlloc) {
1939 mem_map->Protect(PROT_READ | PROT_WRITE);
1940 }
Mathieu Chartier0310da52014-12-01 13:40:48 -08001941 main_space_backup_.reset(CreateMallocSpaceFromMemMap(
1942 mem_map.get(), kDefaultInitialSize, std::min(mem_map->Size(), growth_limit_),
1943 mem_map->Size(), name, true));
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07001944 if (kIsDebugBuild && kUseRosAlloc) {
1945 mem_map->Protect(PROT_NONE);
1946 }
Mathieu Chartierb363f662014-07-16 13:28:58 -07001947 mem_map.release();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001948 }
1949 break;
1950 }
1951 default: {
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001952 LOG(FATAL) << "Attempted to transition to invalid collector type "
1953 << static_cast<size_t>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001954 break;
1955 }
1956 }
1957 ChangeCollector(collector_type);
1958 tl->ResumeAll();
1959 // Can't call into java code with all threads suspended.
Mathieu Chartier308351a2014-06-15 12:39:02 -07001960 reference_processor_.EnqueueClearedReferences(self);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001961 uint64_t duration = NanoTime() - start_time;
Mathieu Chartierafe49982014-03-27 10:55:04 -07001962 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001963 DCHECK(collector != nullptr);
1964 LogGC(kGcCauseCollectorTransition, collector);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001965 FinishGC(self, collector::kGcTypeFull);
Ian Rogers3e5cf302014-05-20 16:40:37 -07001966 int32_t after_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001967 int32_t delta_allocated = before_allocated - after_allocated;
Mathieu Chartier19d46b42014-06-17 15:04:40 -07001968 std::string saved_str;
1969 if (delta_allocated >= 0) {
1970 saved_str = " saved at least " + PrettySize(delta_allocated);
1971 } else {
1972 saved_str = " expanded " + PrettySize(-delta_allocated);
1973 }
Mathieu Chartier98172a62014-09-02 12:33:25 -07001974 VLOG(heap) << "Heap transition to " << process_state_ << " took "
Mathieu Chartier19d46b42014-06-17 15:04:40 -07001975 << PrettyDuration(duration) << saved_str;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001976}
1977
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001978void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001979 // TODO: Only do this with all mutators suspended to avoid races.
1980 if (collector_type != collector_type_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001981 if (collector_type == kCollectorTypeMC) {
1982 // Don't allow mark compact unless support is compiled in.
1983 CHECK(kMarkCompactSupport);
1984 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001985 collector_type_ = collector_type;
1986 gc_plan_.clear();
1987 switch (collector_type_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001988 case kCollectorTypeCC: {
1989 gc_plan_.push_back(collector::kGcTypeFull);
1990 if (use_tlab_) {
1991 ChangeAllocator(kAllocatorTypeRegionTLAB);
1992 } else {
1993 ChangeAllocator(kAllocatorTypeRegion);
1994 }
1995 break;
1996 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001997 case kCollectorTypeMC: // Fall-through.
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07001998 case kCollectorTypeSS: // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001999 case kCollectorTypeGSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002000 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002001 if (use_tlab_) {
2002 ChangeAllocator(kAllocatorTypeTLAB);
2003 } else {
2004 ChangeAllocator(kAllocatorTypeBumpPointer);
2005 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002006 break;
2007 }
2008 case kCollectorTypeMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002009 gc_plan_.push_back(collector::kGcTypeSticky);
2010 gc_plan_.push_back(collector::kGcTypePartial);
2011 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002012 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002013 break;
2014 }
2015 case kCollectorTypeCMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002016 gc_plan_.push_back(collector::kGcTypeSticky);
2017 gc_plan_.push_back(collector::kGcTypePartial);
2018 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002019 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002020 break;
2021 }
2022 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07002023 UNIMPLEMENTED(FATAL);
2024 UNREACHABLE();
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002025 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002026 }
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002027 if (IsGcConcurrent()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002028 concurrent_start_bytes_ =
2029 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
2030 } else {
2031 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002032 }
2033 }
2034}
2035
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002036// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Ian Rogers6fac4472014-02-25 17:01:10 -08002037class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002038 public:
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002039 explicit ZygoteCompactingCollector(gc::Heap* heap) : SemiSpace(heap, false, "zygote collector"),
Ian Rogers6fac4472014-02-25 17:01:10 -08002040 bin_live_bitmap_(nullptr), bin_mark_bitmap_(nullptr) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002041 }
2042
2043 void BuildBins(space::ContinuousSpace* space) {
2044 bin_live_bitmap_ = space->GetLiveBitmap();
2045 bin_mark_bitmap_ = space->GetMarkBitmap();
2046 BinContext context;
2047 context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
2048 context.collector_ = this;
2049 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2050 // Note: This requires traversing the space in increasing order of object addresses.
2051 bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
2052 // Add the last bin which spans after the last object to the end of the space.
2053 AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
2054 }
2055
2056 private:
2057 struct BinContext {
2058 uintptr_t prev_; // The end of the previous object.
2059 ZygoteCompactingCollector* collector_;
2060 };
2061 // Maps from bin sizes to locations.
2062 std::multimap<size_t, uintptr_t> bins_;
2063 // Live bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002064 accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002065 // Mark bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002066 accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002067
2068 static void Callback(mirror::Object* obj, void* arg)
2069 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2070 DCHECK(arg != nullptr);
2071 BinContext* context = reinterpret_cast<BinContext*>(arg);
2072 ZygoteCompactingCollector* collector = context->collector_;
2073 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
2074 size_t bin_size = object_addr - context->prev_;
2075 // Add the bin consisting of the end of the previous object to the start of the current object.
2076 collector->AddBin(bin_size, context->prev_);
2077 context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
2078 }
2079
2080 void AddBin(size_t size, uintptr_t position) {
2081 if (size != 0) {
2082 bins_.insert(std::make_pair(size, position));
2083 }
2084 }
2085
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002086 virtual bool ShouldSweepSpace(space::ContinuousSpace* space) const {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002087 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
2088 // allocator.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002089 UNUSED(space);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002090 return false;
2091 }
2092
2093 virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
2094 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002095 size_t obj_size = obj->SizeOf();
2096 size_t alloc_size = RoundUp(obj_size, kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08002097 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002098 // Find the smallest bin which we can move obj in.
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002099 auto it = bins_.lower_bound(alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002100 if (it == bins_.end()) {
2101 // No available space in the bins, place it in the target space instead (grows the zygote
2102 // space).
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002103 size_t bytes_allocated, dummy;
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002104 forward_address = to_space_->Alloc(self_, alloc_size, &bytes_allocated, nullptr, &dummy);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002105 if (to_space_live_bitmap_ != nullptr) {
2106 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002107 } else {
2108 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
2109 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002110 }
2111 } else {
2112 size_t size = it->first;
2113 uintptr_t pos = it->second;
2114 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
2115 forward_address = reinterpret_cast<mirror::Object*>(pos);
2116 // Set the live and mark bits so that sweeping system weaks works properly.
2117 bin_live_bitmap_->Set(forward_address);
2118 bin_mark_bitmap_->Set(forward_address);
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002119 DCHECK_GE(size, alloc_size);
2120 // Add a new bin with the remaining space.
2121 AddBin(size - alloc_size, pos + alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002122 }
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002123 // Copy the object over to its new location. Don't use alloc_size to avoid valgrind error.
2124 memcpy(reinterpret_cast<void*>(forward_address), obj, obj_size);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002125 if (kUseBakerOrBrooksReadBarrier) {
2126 obj->AssertReadBarrierPointer();
2127 if (kUseBrooksReadBarrier) {
2128 DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
2129 forward_address->SetReadBarrierPointer(forward_address);
2130 }
2131 forward_address->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002132 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002133 return forward_address;
2134 }
2135};
2136
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002137void Heap::UnBindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002138 TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002139 for (const auto& space : GetContinuousSpaces()) {
2140 if (space->IsContinuousMemMapAllocSpace()) {
2141 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2142 if (alloc_space->HasBoundBitmaps()) {
2143 alloc_space->UnBindBitmaps();
2144 }
2145 }
2146 }
2147}
2148
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002149void Heap::PreZygoteFork() {
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002150 if (!HasZygoteSpace()) {
2151 // We still want to GC in case there is some unreachable non moving objects that could cause a
2152 // suboptimal bin packing when we compact the zygote space.
2153 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
2154 }
Ian Rogers81d425b2012-09-27 16:03:43 -07002155 Thread* self = Thread::Current();
2156 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002157 // Try to see if we have any Zygote spaces.
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002158 if (HasZygoteSpace()) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002159 return;
2160 }
Mathieu Chartiereb175f72014-10-31 11:49:27 -07002161 Runtime::Current()->GetInternTable()->SwapPostZygoteWithPreZygote();
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002162 Runtime::Current()->GetClassLinker()->MoveClassTableToPreZygote();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002163 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier590fee92013-09-13 13:46:47 -07002164 // Trim the pages at the end of the non moving space.
2165 non_moving_space_->Trim();
Mathieu Chartier31f44142014-04-08 14:40:03 -07002166 // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
2167 // there.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002168 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002169 const bool same_space = non_moving_space_ == main_space_;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002170 if (kCompactZygote) {
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002171 // Temporarily disable rosalloc verification because the zygote
2172 // compaction will mess up the rosalloc internal metadata.
2173 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002174 ZygoteCompactingCollector zygote_collector(this);
2175 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08002176 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002177 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
2178 non_moving_space_->Limit());
2179 // Compact the bump pointer space to a new zygote bump pointer space.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002180 bool reset_main_space = false;
2181 if (IsMovingGc(collector_type_)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002182 if (collector_type_ == kCollectorTypeCC) {
2183 zygote_collector.SetFromSpace(region_space_);
2184 } else {
2185 zygote_collector.SetFromSpace(bump_pointer_space_);
2186 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002187 } else {
2188 CHECK(main_space_ != nullptr);
Hiroshi Yamauchid04495e2015-03-11 19:09:07 -07002189 CHECK_NE(main_space_, non_moving_space_)
2190 << "Does not make sense to compact within the same space";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002191 // Copy from the main space.
2192 zygote_collector.SetFromSpace(main_space_);
2193 reset_main_space = true;
2194 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002195 zygote_collector.SetToSpace(&target_space);
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07002196 zygote_collector.SetSwapSemiSpaces(false);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002197 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002198 if (reset_main_space) {
2199 main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2200 madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
2201 MemMap* mem_map = main_space_->ReleaseMemMap();
2202 RemoveSpace(main_space_);
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002203 space::Space* old_main_space = main_space_;
Mathieu Chartier0310da52014-12-01 13:40:48 -08002204 CreateMainMallocSpace(mem_map, kDefaultInitialSize, std::min(mem_map->Size(), growth_limit_),
2205 mem_map->Size());
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002206 delete old_main_space;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002207 AddSpace(main_space_);
2208 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002209 if (collector_type_ == kCollectorTypeCC) {
2210 region_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2211 } else {
2212 bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2213 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002214 }
2215 if (temp_space_ != nullptr) {
2216 CHECK(temp_space_->IsEmpty());
2217 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002218 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2219 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002220 // Update the end and write out image.
2221 non_moving_space_->SetEnd(target_space.End());
2222 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002223 VLOG(heap) << "Create zygote space with size=" << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002224 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002225 // Change the collector to the post zygote one.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002226 ChangeCollector(foreground_collector_type_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002227 // Save the old space so that we can remove it after we complete creating the zygote space.
2228 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002229 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002230 // the remaining available space.
2231 // Remove the old space before creating the zygote space since creating the zygote space sets
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002232 // the old alloc space's bitmaps to null.
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002233 RemoveSpace(old_alloc_space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002234 if (collector::SemiSpace::kUseRememberedSet) {
2235 // Sanity bound check.
2236 FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
2237 // Remove the remembered set for the now zygote space (the old
2238 // non-moving space). Note now that we have compacted objects into
2239 // the zygote space, the data in the remembered set is no longer
2240 // needed. The zygote space will instead have a mod-union table
2241 // from this point on.
2242 RemoveRememberedSet(old_alloc_space);
2243 }
Mathieu Chartier7247af52014-11-19 10:51:42 -08002244 // Remaining space becomes the new non moving space.
2245 zygote_space_ = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName, low_memory_mode_,
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002246 &non_moving_space_);
Mathieu Chartierb363f662014-07-16 13:28:58 -07002247 CHECK(!non_moving_space_->CanMoveObjects());
2248 if (same_space) {
2249 main_space_ = non_moving_space_;
2250 SetSpaceAsDefault(main_space_);
2251 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002252 delete old_alloc_space;
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002253 CHECK(HasZygoteSpace()) << "Failed creating zygote space";
2254 AddSpace(zygote_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002255 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2256 AddSpace(non_moving_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002257 // Create the zygote space mod union table.
2258 accounting::ModUnionTable* mod_union_table =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002259 new accounting::ModUnionTableCardCache("zygote space mod-union table", this,
2260 zygote_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002261 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002262 // Set all the cards in the mod-union table since we don't know which objects contain references
2263 // to large objects.
2264 mod_union_table->SetCards();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002265 AddModUnionTable(mod_union_table);
Mathieu Chartierf6c2a272015-06-03 17:32:42 -07002266 large_object_space_->SetAllLargeObjectsAsZygoteObjects(self);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002267 if (collector::SemiSpace::kUseRememberedSet) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002268 // Add a new remembered set for the post-zygote non-moving space.
2269 accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2270 new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2271 non_moving_space_);
2272 CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2273 << "Failed to create post-zygote non-moving space remembered set";
2274 AddRememberedSet(post_zygote_non_moving_space_rem_set);
2275 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002276}
2277
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002278void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002279 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002280 allocation_stack_->Reset();
2281}
2282
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002283void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2284 accounting::ContinuousSpaceBitmap* bitmap2,
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07002285 accounting::LargeObjectBitmap* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07002286 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002287 DCHECK(bitmap1 != nullptr);
2288 DCHECK(bitmap2 != nullptr);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002289 const auto* limit = stack->End();
2290 for (auto* it = stack->Begin(); it != limit; ++it) {
2291 const mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002292 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2293 if (bitmap1->HasAddress(obj)) {
2294 bitmap1->Set(obj);
2295 } else if (bitmap2->HasAddress(obj)) {
2296 bitmap2->Set(obj);
2297 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07002298 DCHECK(large_objects != nullptr);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002299 large_objects->Set(obj);
2300 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07002301 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002302 }
2303}
2304
Mathieu Chartier590fee92013-09-13 13:46:47 -07002305void Heap::SwapSemiSpaces() {
Mathieu Chartier31f44142014-04-08 14:40:03 -07002306 CHECK(bump_pointer_space_ != nullptr);
2307 CHECK(temp_space_ != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002308 std::swap(bump_pointer_space_, temp_space_);
2309}
2310
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002311collector::GarbageCollector* Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2312 space::ContinuousMemMapAllocSpace* source_space,
2313 GcCause gc_cause) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002314 CHECK(kMovingCollector);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002315 if (target_space != source_space) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002316 // Don't swap spaces since this isn't a typical semi space collection.
2317 semi_space_collector_->SetSwapSemiSpaces(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002318 semi_space_collector_->SetFromSpace(source_space);
2319 semi_space_collector_->SetToSpace(target_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002320 semi_space_collector_->Run(gc_cause, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002321 return semi_space_collector_;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002322 } else {
2323 CHECK(target_space->IsBumpPointerSpace())
2324 << "In-place compaction is only supported for bump pointer spaces";
2325 mark_compact_collector_->SetSpace(target_space->AsBumpPointerSpace());
2326 mark_compact_collector_->Run(kGcCauseCollectorTransition, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002327 return mark_compact_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002328 }
2329}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002330
Ian Rogers1d54e732013-05-02 21:10:01 -07002331collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
2332 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002333 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002334 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002335 // If the heap can't run the GC, silently fail and return that no GC was run.
2336 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002337 case collector::kGcTypePartial: {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002338 if (!HasZygoteSpace()) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002339 return collector::kGcTypeNone;
2340 }
2341 break;
2342 }
2343 default: {
2344 // Other GC types don't have any special cases which makes them not runnable. The main case
2345 // here is full GC.
2346 }
2347 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002348 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07002349 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002350 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier50c138f2015-01-07 16:00:03 -08002351 // If we are throwing a stack overflow error we probably don't have enough remaining stack
2352 // space to run the GC.
2353 return collector::kGcTypeNone;
Ian Rogers120f1c72012-09-28 17:17:10 -07002354 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002355 bool compacting_gc;
2356 {
2357 gc_complete_lock_->AssertNotHeld(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002358 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002359 MutexLock mu(self, *gc_complete_lock_);
2360 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002361 WaitForGcToCompleteLocked(gc_cause, self);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002362 compacting_gc = IsMovingGc(collector_type_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002363 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2364 if (compacting_gc && disable_moving_gc_count_ != 0) {
2365 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2366 return collector::kGcTypeNone;
2367 }
2368 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002369 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002370 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2371 ++runtime->GetStats()->gc_for_alloc_count;
2372 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002373 }
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002374 const uint64_t bytes_allocated_before_gc = GetBytesAllocated();
2375 // Approximate heap size.
2376 ATRACE_INT("Heap size (KB)", bytes_allocated_before_gc / KB);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002377
Ian Rogers1d54e732013-05-02 21:10:01 -07002378 DCHECK_LT(gc_type, collector::kGcTypeMax);
2379 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002380
Mathieu Chartier590fee92013-09-13 13:46:47 -07002381 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08002382 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002383 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002384 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002385 current_allocator_ == kAllocatorTypeTLAB ||
2386 current_allocator_ == kAllocatorTypeRegion ||
2387 current_allocator_ == kAllocatorTypeRegionTLAB);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002388 switch (collector_type_) {
2389 case kCollectorTypeSS:
2390 // Fall-through.
2391 case kCollectorTypeGSS:
2392 semi_space_collector_->SetFromSpace(bump_pointer_space_);
2393 semi_space_collector_->SetToSpace(temp_space_);
2394 semi_space_collector_->SetSwapSemiSpaces(true);
2395 collector = semi_space_collector_;
2396 break;
2397 case kCollectorTypeCC:
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002398 concurrent_copying_collector_->SetRegionSpace(region_space_);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002399 collector = concurrent_copying_collector_;
2400 break;
2401 case kCollectorTypeMC:
2402 mark_compact_collector_->SetSpace(bump_pointer_space_);
2403 collector = mark_compact_collector_;
2404 break;
2405 default:
2406 LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002407 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002408 if (collector != mark_compact_collector_ && collector != concurrent_copying_collector_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002409 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2410 CHECK(temp_space_->IsEmpty());
2411 }
2412 gc_type = collector::kGcTypeFull; // TODO: Not hard code this in.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002413 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2414 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002415 collector = FindCollectorByGcType(gc_type);
Mathieu Chartier50482232013-11-21 11:48:14 -08002416 } else {
2417 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002418 }
Mathieu Chartier08cef222014-10-22 17:18:34 -07002419 if (IsGcConcurrent()) {
2420 // Disable concurrent GC check so that we don't have spammy JNI requests.
2421 // This gets recalculated in GrowForUtilization. It is important that it is disabled /
2422 // calculated in the same thread so that there aren't any races that can cause it to become
2423 // permanantly disabled. b/17942071
2424 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2425 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002426 CHECK(collector != nullptr)
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002427 << "Could not find garbage collector with collector_type="
2428 << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002429 collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002430 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2431 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08002432 RequestTrim(self);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002433 // Enqueue cleared references.
Mathieu Chartier308351a2014-06-15 12:39:02 -07002434 reference_processor_.EnqueueClearedReferences(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002435 // Grow the heap so that we know when to perform the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002436 GrowForUtilization(collector, bytes_allocated_before_gc);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002437 LogGC(gc_cause, collector);
2438 FinishGC(self, gc_type);
2439 // Inform DDMS that a GC completed.
2440 Dbg::GcDidFinish();
2441 return gc_type;
2442}
2443
2444void Heap::LogGC(GcCause gc_cause, collector::GarbageCollector* collector) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002445 const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2446 const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002447 // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002448 // (mutator time blocked >= long_pause_log_threshold_).
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002449 bool log_gc = gc_cause == kGcCauseExplicit;
2450 if (!log_gc && CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002451 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002452 log_gc = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002453 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002454 for (uint64_t pause : pause_times) {
2455 log_gc = log_gc || pause >= long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002456 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002457 }
2458 if (log_gc) {
2459 const size_t percent_free = GetPercentFree();
2460 const size_t current_heap_size = GetBytesAllocated();
2461 const size_t total_memory = GetTotalMemory();
2462 std::ostringstream pause_string;
2463 for (size_t i = 0; i < pause_times.size(); ++i) {
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002464 pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2465 << ((i != pause_times.size() - 1) ? "," : "");
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002466 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002467 LOG(INFO) << gc_cause << " " << collector->GetName()
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002468 << " GC freed " << current_gc_iteration_.GetFreedObjects() << "("
2469 << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2470 << current_gc_iteration_.GetFreedLargeObjects() << "("
2471 << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002472 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2473 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2474 << " total " << PrettyDuration((duration / 1000) * 1000);
Ian Rogersc7dd2952014-10-21 23:31:19 -07002475 VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002476 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002477}
Mathieu Chartiera6399032012-06-11 18:49:50 -07002478
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002479void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2480 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002481 collector_type_running_ = kCollectorTypeNone;
2482 if (gc_type != collector::kGcTypeNone) {
2483 last_gc_type_ = gc_type;
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002484
2485 // Update stats.
2486 ++gc_count_last_window_;
2487 if (running_collection_is_blocking_) {
2488 // If the currently running collection was a blocking one,
2489 // increment the counters and reset the flag.
2490 ++blocking_gc_count_;
2491 blocking_gc_time_ += GetCurrentGcIteration()->GetDurationNs();
2492 ++blocking_gc_count_last_window_;
2493 }
2494 // Update the gc count rate histograms if due.
2495 UpdateGcCountRateHistograms();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002496 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002497 // Reset.
2498 running_collection_is_blocking_ = false;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002499 // Wake anyone who may have been waiting for the GC to complete.
2500 gc_complete_cond_->Broadcast(self);
2501}
2502
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002503void Heap::UpdateGcCountRateHistograms() {
2504 // Invariant: if the time since the last update includes more than
2505 // one windows, all the GC runs (if > 0) must have happened in first
2506 // window because otherwise the update must have already taken place
2507 // at an earlier GC run. So, we report the non-first windows with
2508 // zero counts to the histograms.
2509 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2510 uint64_t now = NanoTime();
2511 DCHECK_GE(now, last_update_time_gc_count_rate_histograms_);
2512 uint64_t time_since_last_update = now - last_update_time_gc_count_rate_histograms_;
2513 uint64_t num_of_windows = time_since_last_update / kGcCountRateHistogramWindowDuration;
2514 if (time_since_last_update >= kGcCountRateHistogramWindowDuration) {
2515 // Record the first window.
2516 gc_count_rate_histogram_.AddValue(gc_count_last_window_ - 1); // Exclude the current run.
2517 blocking_gc_count_rate_histogram_.AddValue(running_collection_is_blocking_ ?
2518 blocking_gc_count_last_window_ - 1 : blocking_gc_count_last_window_);
2519 // Record the other windows (with zero counts).
2520 for (uint64_t i = 0; i < num_of_windows - 1; ++i) {
2521 gc_count_rate_histogram_.AddValue(0);
2522 blocking_gc_count_rate_histogram_.AddValue(0);
2523 }
2524 // Update the last update time and reset the counters.
2525 last_update_time_gc_count_rate_histograms_ =
2526 (now / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
2527 gc_count_last_window_ = 1; // Include the current run.
2528 blocking_gc_count_last_window_ = running_collection_is_blocking_ ? 1 : 0;
2529 }
2530 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2531}
2532
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002533class RootMatchesObjectVisitor : public SingleRootVisitor {
2534 public:
2535 explicit RootMatchesObjectVisitor(const mirror::Object* obj) : obj_(obj) { }
2536
2537 void VisitRoot(mirror::Object* root, const RootInfo& info)
2538 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2539 if (root == obj_) {
2540 LOG(INFO) << "Object " << obj_ << " is a root " << info.ToString();
2541 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002542 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002543
2544 private:
2545 const mirror::Object* const obj_;
2546};
2547
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002548
2549class ScanVisitor {
2550 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07002551 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002552 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002553 }
2554};
2555
Ian Rogers1d54e732013-05-02 21:10:01 -07002556// Verify a reference from an object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002557class VerifyReferenceVisitor : public SingleRootVisitor {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002558 public:
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002559 explicit VerifyReferenceVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
Ian Rogers1d54e732013-05-02 21:10:01 -07002560 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002561 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07002562
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002563 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002564 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002565 }
2566
Mathieu Chartier407f7022014-02-18 14:37:05 -08002567 void operator()(mirror::Class* klass, mirror::Reference* ref) const
2568 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002569 UNUSED(klass);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002570 if (verify_referent_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002571 VerifyReference(ref, ref->GetReferent(), mirror::Reference::ReferentOffset());
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002572 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08002573 }
2574
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07002575 void operator()(mirror::Object* obj, MemberOffset offset, bool /*is_static*/) const
Mathieu Chartier407f7022014-02-18 14:37:05 -08002576 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002577 VerifyReference(obj, obj->GetFieldObject<mirror::Object>(offset), offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08002578 }
2579
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002580 bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
2581 return heap_->IsLiveObjectLocked(obj, true, false, true);
2582 }
2583
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002584 void VisitRoot(mirror::Object* root, const RootInfo& root_info) OVERRIDE
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002585 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002586 if (root == nullptr) {
2587 LOG(ERROR) << "Root is null with info " << root_info.GetType();
2588 } else if (!VerifyReference(nullptr, root, MemberOffset(0))) {
2589 LOG(ERROR) << "Root " << root << " is dead with type " << PrettyTypeOf(root)
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002590 << " thread_id= " << root_info.GetThreadId() << " root_type= " << root_info.GetType();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002591 }
2592 }
2593
2594 private:
Mathieu Chartier407f7022014-02-18 14:37:05 -08002595 // TODO: Fix the no thread safety analysis.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002596 // Returns false on failure.
2597 bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002598 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002599 if (ref == nullptr || IsLive(ref)) {
2600 // Verify that the reference is live.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002601 return true;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002602 }
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002603 if (fail_count_->FetchAndAddSequentiallyConsistent(1) == 0) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002604 // Print message on only on first failure to prevent spam.
2605 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002606 }
2607 if (obj != nullptr) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002608 // Only do this part for non roots.
Ian Rogers1d54e732013-05-02 21:10:01 -07002609 accounting::CardTable* card_table = heap_->GetCardTable();
2610 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2611 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Ian Rogers13735952014-10-08 12:43:28 -07002612 uint8_t* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002613 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2614 << offset << "\n card value = " << static_cast<int>(*card_addr);
2615 if (heap_->IsValidObjectAddress(obj->GetClass())) {
2616 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
2617 } else {
2618 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002619 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002620
Mathieu Chartierb363f662014-07-16 13:28:58 -07002621 // Attempt to find the class inside of the recently freed objects.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002622 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2623 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2624 space::MallocSpace* space = ref_space->AsMallocSpace();
2625 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2626 if (ref_class != nullptr) {
2627 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
2628 << PrettyClass(ref_class);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002629 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002630 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002631 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002632 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002633
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002634 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2635 ref->GetClass()->IsClass()) {
2636 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
2637 } else {
2638 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2639 << ") is not a valid heap address";
2640 }
2641
Ian Rogers13735952014-10-08 12:43:28 -07002642 card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002643 void* cover_begin = card_table->AddrFromCard(card_addr);
2644 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2645 accounting::CardTable::kCardSize);
2646 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2647 << "-" << cover_end;
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002648 accounting::ContinuousSpaceBitmap* bitmap =
2649 heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002650
2651 if (bitmap == nullptr) {
2652 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08002653 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002654 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002655 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002656 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07002657 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002658 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002659 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2660 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002661 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002662 LOG(ERROR) << "Object " << obj << " found in allocation stack";
2663 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002664 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002665 LOG(ERROR) << "Object " << obj << " found in live stack";
2666 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002667 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2668 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2669 }
2670 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2671 LOG(ERROR) << "Ref " << ref << " found in live stack";
2672 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002673 // Attempt to see if the card table missed the reference.
2674 ScanVisitor scan_visitor;
Ian Rogers13735952014-10-08 12:43:28 -07002675 uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
Lei Li727b2942015-01-15 11:26:34 +08002676 card_table->Scan<false>(bitmap, byte_cover_begin,
2677 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002678 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002679
2680 // Search to see if any of the roots reference our object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002681 RootMatchesObjectVisitor visitor1(obj);
2682 Runtime::Current()->VisitRoots(&visitor1);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002683 // Search to see if any of the roots reference our reference.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002684 RootMatchesObjectVisitor visitor2(ref);
2685 Runtime::Current()->VisitRoots(&visitor2);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002686 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002687 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002688 }
2689
Ian Rogers1d54e732013-05-02 21:10:01 -07002690 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002691 Atomic<size_t>* const fail_count_;
2692 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002693};
2694
Ian Rogers1d54e732013-05-02 21:10:01 -07002695// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002696class VerifyObjectVisitor {
2697 public:
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002698 explicit VerifyObjectVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
2699 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002700 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002701
Mathieu Chartier590fee92013-09-13 13:46:47 -07002702 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07002703 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002704 // Note: we are verifying the references in obj but not obj itself, this is because obj must
2705 // be live or else how did we find it in the live bitmap?
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002706 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002707 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002708 obj->VisitReferences<true>(visitor, visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002709 }
2710
Mathieu Chartier590fee92013-09-13 13:46:47 -07002711 static void VisitCallback(mirror::Object* obj, void* arg)
2712 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2713 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
2714 visitor->operator()(obj);
2715 }
2716
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002717 void VerifyRoots() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
2718 LOCKS_EXCLUDED(Locks::heap_bitmap_lock_) {
2719 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2720 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
2721 Runtime::Current()->VisitRoots(&visitor);
2722 }
2723
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002724 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002725 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002726 }
2727
2728 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002729 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002730 Atomic<size_t>* const fail_count_;
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002731 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002732};
2733
Mathieu Chartierc1790162014-05-23 10:54:50 -07002734void Heap::PushOnAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2735 // Slow path, the allocation stack push back must have already failed.
2736 DCHECK(!allocation_stack_->AtomicPushBack(*obj));
2737 do {
2738 // TODO: Add handle VerifyObject.
2739 StackHandleScope<1> hs(self);
2740 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2741 // Push our object into the reserve region of the allocaiton stack. This is only required due
2742 // to heap verification requiring that roots are live (either in the live bitmap or in the
2743 // allocation stack).
2744 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2745 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2746 } while (!allocation_stack_->AtomicPushBack(*obj));
2747}
2748
2749void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2750 // Slow path, the allocation stack push back must have already failed.
2751 DCHECK(!self->PushOnThreadLocalAllocationStack(*obj));
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002752 StackReference<mirror::Object>* start_address;
2753 StackReference<mirror::Object>* end_address;
Mathieu Chartierc1790162014-05-23 10:54:50 -07002754 while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
2755 &end_address)) {
2756 // TODO: Add handle VerifyObject.
2757 StackHandleScope<1> hs(self);
2758 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2759 // Push our object into the reserve region of the allocaiton stack. This is only required due
2760 // to heap verification requiring that roots are live (either in the live bitmap or in the
2761 // allocation stack).
2762 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2763 // Push into the reserve allocation stack.
2764 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2765 }
2766 self->SetThreadLocalAllocationStack(start_address, end_address);
2767 // Retry on the new thread-local allocation stack.
2768 CHECK(self->PushOnThreadLocalAllocationStack(*obj)); // Must succeed.
2769}
2770
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002771// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002772size_t Heap::VerifyHeapReferences(bool verify_referents) {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002773 Thread* self = Thread::Current();
2774 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002775 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07002776 allocation_stack_->Sort();
2777 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002778 // Since we sorted the allocation stack content, need to revoke all
2779 // thread-local allocation stacks.
2780 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002781 Atomic<size_t> fail_count_(0);
2782 VerifyObjectVisitor visitor(this, &fail_count_, verify_referents);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002783 // Verify objects in the allocation stack since these will be objects which were:
2784 // 1. Allocated prior to the GC (pre GC verification).
2785 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002786 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002787 // pointing to dead objects if they are not reachable.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002788 VisitObjectsPaused(VerifyObjectVisitor::VisitCallback, &visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002789 // Verify the roots:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002790 visitor.VerifyRoots();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002791 if (visitor.GetFailureCount() > 0) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002792 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002793 for (const auto& table_pair : mod_union_tables_) {
2794 accounting::ModUnionTable* mod_union_table = table_pair.second;
2795 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
2796 }
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002797 // Dump remembered sets.
2798 for (const auto& table_pair : remembered_sets_) {
2799 accounting::RememberedSet* remembered_set = table_pair.second;
2800 remembered_set->Dump(LOG(ERROR) << remembered_set->GetName() << ": ");
2801 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07002802 DumpSpaces(LOG(ERROR));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002803 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002804 return visitor.GetFailureCount();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002805}
2806
2807class VerifyReferenceCardVisitor {
2808 public:
2809 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
2810 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
2811 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07002812 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002813 }
2814
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002815 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
2816 // annotalysis on visitors.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002817 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
2818 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07002819 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002820 // Filter out class references since changing an object's class does not mark the card as dirty.
2821 // Also handles large objects, since the only reference they hold is a class reference.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002822 if (ref != nullptr && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002823 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002824 // If the object is not dirty and it is referencing something in the live stack other than
2825 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002826 if (!card_table->AddrIsInCardTable(obj)) {
2827 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
2828 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002829 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002830 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002831 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
2832 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002833 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier407f7022014-02-18 14:37:05 -08002834 if (live_stack->ContainsSorted(ref)) {
2835 if (live_stack->ContainsSorted(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002836 LOG(ERROR) << "Object " << obj << " found in live stack";
2837 }
2838 if (heap_->GetLiveBitmap()->Test(obj)) {
2839 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2840 }
2841 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
2842 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
2843
2844 // Print which field of the object is dead.
2845 if (!obj->IsObjectArray()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002846 mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002847 CHECK(klass != nullptr);
2848 auto* fields = is_static ? klass->GetSFields() : klass->GetIFields();
2849 auto num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
2850 CHECK_EQ(fields == nullptr, num_fields == 0u);
2851 for (size_t i = 0; i < num_fields; ++i) {
2852 ArtField* cur = &fields[i];
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002853 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
2854 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
2855 << PrettyField(cur);
2856 break;
2857 }
2858 }
2859 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002860 mirror::ObjectArray<mirror::Object>* object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002861 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002862 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
2863 if (object_array->Get(i) == ref) {
2864 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
2865 }
2866 }
2867 }
2868
2869 *failed_ = true;
2870 }
2871 }
2872 }
2873 }
2874
2875 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002876 Heap* const heap_;
2877 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002878};
2879
2880class VerifyLiveStackReferences {
2881 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002882 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002883 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002884 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002885
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002886 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002887 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2888 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07002889 obj->VisitReferences<true>(visitor, VoidFunctor());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002890 }
2891
2892 bool Failed() const {
2893 return failed_;
2894 }
2895
2896 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002897 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002898 bool failed_;
2899};
2900
2901bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002902 Thread* self = Thread::Current();
2903 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002904 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002905 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002906 // Since we sorted the allocation stack content, need to revoke all
2907 // thread-local allocation stacks.
2908 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002909 VerifyLiveStackReferences visitor(this);
2910 GetLiveBitmap()->Visit(visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002911 // We can verify objects in the live stack since none of these should reference dead objects.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002912 for (auto* it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
2913 if (!kUseThreadLocalAllocationStack || it->AsMirrorPtr() != nullptr) {
2914 visitor(it->AsMirrorPtr());
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002915 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002916 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07002917 return !visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002918}
2919
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002920void Heap::SwapStacks(Thread* self) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002921 UNUSED(self);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002922 if (kUseThreadLocalAllocationStack) {
2923 live_stack_->AssertAllZero();
2924 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002925 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002926}
2927
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002928void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002929 // This must be called only during the pause.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002930 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002931 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2932 MutexLock mu2(self, *Locks::thread_list_lock_);
2933 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
2934 for (Thread* t : thread_list) {
2935 t->RevokeThreadLocalAllocationStack();
2936 }
2937}
2938
Ian Rogers68d8b422014-07-17 11:09:10 -07002939void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
2940 if (kIsDebugBuild) {
2941 if (rosalloc_space_ != nullptr) {
2942 rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
2943 }
2944 if (bump_pointer_space_ != nullptr) {
2945 bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
2946 }
2947 }
2948}
2949
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002950void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
2951 if (kIsDebugBuild) {
2952 if (bump_pointer_space_ != nullptr) {
2953 bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
2954 }
2955 }
2956}
2957
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002958accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
2959 auto it = mod_union_tables_.find(space);
2960 if (it == mod_union_tables_.end()) {
2961 return nullptr;
2962 }
2963 return it->second;
2964}
2965
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002966accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
2967 auto it = remembered_sets_.find(space);
2968 if (it == remembered_sets_.end()) {
2969 return nullptr;
2970 }
2971 return it->second;
2972}
2973
Lei Li4add3b42015-01-15 11:55:26 +08002974void Heap::ProcessCards(TimingLogger* timings, bool use_rem_sets, bool process_alloc_space_cards,
2975 bool clear_alloc_space_cards) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002976 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07002977 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07002978 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002979 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002980 accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002981 if (table != nullptr) {
2982 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
2983 "ImageModUnionClearCards";
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002984 TimingLogger::ScopedTiming t2(name, timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002985 table->ClearCards();
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002986 } else if (use_rem_sets && rem_set != nullptr) {
2987 DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
2988 << static_cast<int>(collector_type_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002989 TimingLogger::ScopedTiming t2("AllocSpaceRemSetClearCards", timings);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002990 rem_set->ClearCards();
Lei Li4add3b42015-01-15 11:55:26 +08002991 } else if (process_alloc_space_cards) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002992 TimingLogger::ScopedTiming t2("AllocSpaceClearCards", timings);
Lei Li4add3b42015-01-15 11:55:26 +08002993 if (clear_alloc_space_cards) {
2994 card_table_->ClearCardRange(space->Begin(), space->End());
2995 } else {
2996 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these
2997 // cards were dirty before the GC started.
2998 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
2999 // -> clean(cleaning thread).
3000 // The races are we either end up with: Aged card, unaged card. Since we have the
3001 // checkpoint roots and then we scan / update mod union tables after. We will always
3002 // scan either card. If we end up with the non aged card, we scan it it in the pause.
3003 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
3004 VoidFunctor());
3005 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003006 }
3007 }
3008}
3009
Mathieu Chartier407f7022014-02-18 14:37:05 -08003010static void IdentityMarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>*, void*) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003011}
3012
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003013void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
3014 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003015 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003016 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003017 if (verify_pre_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003018 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003019 size_t failures = VerifyHeapReferences();
3020 if (failures > 0) {
3021 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3022 << " failures";
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003023 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003024 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003025 // Check that all objects which reference things in the live stack are on dirty cards.
3026 if (verify_missing_card_marks_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003027 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyMissingCardMarks", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003028 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
3029 SwapStacks(self);
3030 // Sort the live stack so that we can quickly binary search it later.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003031 CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
3032 << " missing card mark verification failed\n" << DumpSpaces();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003033 SwapStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003034 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003035 if (verify_mod_union_table_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003036 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyModUnionTables", timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003037 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003038 for (const auto& table_pair : mod_union_tables_) {
3039 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier407f7022014-02-18 14:37:05 -08003040 mod_union_table->UpdateAndMarkReferences(IdentityMarkHeapReferenceCallback, nullptr);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003041 mod_union_table->Verify();
3042 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003043 }
3044}
3045
3046void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier0651d412014-04-29 14:37:57 -07003047 if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003048 collector::GarbageCollector::ScopedPause pause(gc);
3049 PreGcVerificationPaused(gc);
3050 }
3051}
3052
3053void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003054 UNUSED(gc);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003055 // TODO: Add a new runtime option for this?
3056 if (verify_pre_gc_rosalloc_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003057 RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003058 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003059}
3060
Ian Rogers1d54e732013-05-02 21:10:01 -07003061void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003062 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003063 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003064 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003065 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
3066 // reachable objects.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003067 if (verify_pre_sweeping_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003068 TimingLogger::ScopedTiming t2("(Paused)PostSweepingVerifyHeapReferences", timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003069 CHECK_NE(self->GetState(), kRunnable);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003070 {
3071 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3072 // Swapping bound bitmaps does nothing.
3073 gc->SwapBitmaps();
3074 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07003075 // Pass in false since concurrent reference processing can mean that the reference referents
3076 // may point to dead objects at the point which PreSweepingGcVerification is called.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003077 size_t failures = VerifyHeapReferences(false);
3078 if (failures > 0) {
3079 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
3080 << " failures";
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003081 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003082 {
3083 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3084 gc->SwapBitmaps();
3085 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003086 }
3087 if (verify_pre_sweeping_rosalloc_) {
3088 RosAllocVerification(timings, "PreSweepingRosAllocVerification");
3089 }
3090}
3091
3092void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
3093 // Only pause if we have to do some verification.
3094 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003095 TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003096 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003097 if (verify_system_weaks_) {
3098 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3099 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
3100 mark_sweep->VerifySystemWeaks();
3101 }
3102 if (verify_post_gc_rosalloc_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003103 RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003104 }
3105 if (verify_post_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003106 TimingLogger::ScopedTiming t2("(Paused)PostGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003107 size_t failures = VerifyHeapReferences();
3108 if (failures > 0) {
3109 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3110 << " failures";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003111 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003112 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003113}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003114
Ian Rogers1d54e732013-05-02 21:10:01 -07003115void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003116 if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
3117 collector::GarbageCollector::ScopedPause pause(gc);
Mathieu Chartierd35326f2014-08-18 15:02:59 -07003118 PostGcVerificationPaused(gc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003119 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003120}
3121
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003122void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003123 TimingLogger::ScopedTiming t(name, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003124 for (const auto& space : continuous_spaces_) {
3125 if (space->IsRosAllocSpace()) {
3126 VLOG(heap) << name << " : " << space->GetName();
3127 space->AsRosAllocSpace()->Verify();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08003128 }
3129 }
3130}
3131
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003132collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08003133 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003134 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003135 return WaitForGcToCompleteLocked(cause, self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003136}
3137
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003138collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003139 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003140 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08003141 while (collector_type_running_ != kCollectorTypeNone) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003142 if (self != task_processor_->GetRunningThread()) {
3143 // The current thread is about to wait for a currently running
3144 // collection to finish. If the waiting thread is not the heap
3145 // task daemon thread, the currently running collection is
3146 // considered as a blocking GC.
3147 running_collection_is_blocking_ = true;
3148 VLOG(gc) << "Waiting for a blocking GC " << cause;
3149 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003150 ATRACE_BEGIN("GC: Wait For Completion");
3151 // We must wait, change thread state then sleep on gc_complete_cond_;
3152 gc_complete_cond_->Wait(self);
3153 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07003154 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003155 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003156 uint64_t wait_time = NanoTime() - wait_start;
3157 total_wait_time_ += wait_time;
3158 if (wait_time > long_pause_log_threshold_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003159 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time)
3160 << " for cause " << cause;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003161 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003162 if (self != task_processor_->GetRunningThread()) {
3163 // The current thread is about to run a collection. If the thread
3164 // is not the heap task daemon thread, it's considered as a
3165 // blocking GC (i.e., blocking itself).
3166 running_collection_is_blocking_ = true;
3167 VLOG(gc) << "Starting a blocking GC " << cause;
3168 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07003169 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07003170}
3171
Elliott Hughesc967f782012-04-16 10:23:15 -07003172void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003173 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003174 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07003175 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07003176}
3177
3178size_t Heap::GetPercentFree() {
Mathieu Chartierd30e1d62014-06-09 13:25:22 -07003179 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / max_allowed_footprint_);
Elliott Hughesc967f782012-04-16 10:23:15 -07003180}
3181
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003182void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003183 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003184 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003185 << PrettySize(GetMaxMemory());
3186 max_allowed_footprint = GetMaxMemory();
3187 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07003188 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07003189}
3190
Mathieu Chartier590fee92013-09-13 13:46:47 -07003191bool Heap::IsMovableObject(const mirror::Object* obj) const {
3192 if (kMovingCollector) {
Mathieu Chartier31f44142014-04-08 14:40:03 -07003193 space::Space* space = FindContinuousSpaceFromObject(obj, true);
3194 if (space != nullptr) {
3195 // TODO: Check large object?
3196 return space->CanMoveObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003197 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003198 }
3199 return false;
3200}
3201
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003202void Heap::UpdateMaxNativeFootprint() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07003203 size_t native_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003204 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
3205 size_t target_size = native_size / GetTargetHeapUtilization();
3206 if (target_size > native_size + max_free_) {
3207 target_size = native_size + max_free_;
3208 } else if (target_size < native_size + min_free_) {
3209 target_size = native_size + min_free_;
3210 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003211 native_footprint_gc_watermark_ = std::min(growth_limit_, target_size);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003212}
3213
Mathieu Chartierafe49982014-03-27 10:55:04 -07003214collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
3215 for (const auto& collector : garbage_collectors_) {
3216 if (collector->GetCollectorType() == collector_type_ &&
3217 collector->GetGcType() == gc_type) {
3218 return collector;
3219 }
3220 }
3221 return nullptr;
3222}
3223
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003224double Heap::HeapGrowthMultiplier() const {
3225 // If we don't care about pause times we are background, so return 1.0.
3226 if (!CareAboutPauseTimes() || IsLowMemoryMode()) {
3227 return 1.0;
3228 }
3229 return foreground_heap_growth_multiplier_;
3230}
3231
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003232void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran,
3233 uint64_t bytes_allocated_before_gc) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003234 // We know what our utilization is at this moment.
3235 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003236 const uint64_t bytes_allocated = GetBytesAllocated();
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003237 uint64_t target_size;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003238 collector::GcType gc_type = collector_ran->GetGcType();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003239 const double multiplier = HeapGrowthMultiplier(); // Use the multiplier to grow more for
3240 // foreground.
3241 const uint64_t adjusted_min_free = static_cast<uint64_t>(min_free_ * multiplier);
3242 const uint64_t adjusted_max_free = static_cast<uint64_t>(max_free_ * multiplier);
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003243 if (gc_type != collector::kGcTypeSticky) {
3244 // Grow the heap for non sticky GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003245 ssize_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003246 CHECK_GE(delta, 0);
3247 target_size = bytes_allocated + delta * multiplier;
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003248 target_size = std::min(target_size, bytes_allocated + adjusted_max_free);
3249 target_size = std::max(target_size, bytes_allocated + adjusted_min_free);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003250 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003251 next_gc_type_ = collector::kGcTypeSticky;
3252 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003253 collector::GcType non_sticky_gc_type =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07003254 HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003255 // Find what the next non sticky collector will be.
3256 collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
3257 // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
3258 // do another sticky collection next.
3259 // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
3260 // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
3261 // if the sticky GC throughput always remained >= the full/partial throughput.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003262 if (current_gc_iteration_.GetEstimatedThroughput() * kStickyGcThroughputAdjustment >=
Mathieu Chartierafe49982014-03-27 10:55:04 -07003263 non_sticky_collector->GetEstimatedMeanThroughput() &&
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003264 non_sticky_collector->NumberOfIterations() > 0 &&
Mathieu Chartierafe49982014-03-27 10:55:04 -07003265 bytes_allocated <= max_allowed_footprint_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003266 next_gc_type_ = collector::kGcTypeSticky;
3267 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003268 next_gc_type_ = non_sticky_gc_type;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003269 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003270 // If we have freed enough memory, shrink the heap back down.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003271 if (bytes_allocated + adjusted_max_free < max_allowed_footprint_) {
3272 target_size = bytes_allocated + adjusted_max_free;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003273 } else {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003274 target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003275 }
3276 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003277 if (!ignore_max_footprint_) {
3278 SetIdealFootprint(target_size);
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003279 if (IsGcConcurrent()) {
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003280 const uint64_t freed_bytes = current_gc_iteration_.GetFreedBytes() +
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003281 current_gc_iteration_.GetFreedLargeObjectBytes() +
3282 current_gc_iteration_.GetFreedRevokeBytes();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003283 // Bytes allocated will shrink by freed_bytes after the GC runs, so if we want to figure out
3284 // how many bytes were allocated during the GC we need to add freed_bytes back on.
3285 CHECK_GE(bytes_allocated + freed_bytes, bytes_allocated_before_gc);
3286 const uint64_t bytes_allocated_during_gc = bytes_allocated + freed_bytes -
3287 bytes_allocated_before_gc;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003288 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003289 // Calculate the estimated GC duration.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003290 const double gc_duration_seconds = NsToMs(current_gc_iteration_.GetDurationNs()) / 1000.0;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003291 // Estimate how many remaining bytes we will have when we need to start the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003292 size_t remaining_bytes = bytes_allocated_during_gc * gc_duration_seconds;
Mathieu Chartier74762802014-01-24 10:21:35 -08003293 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003294 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
3295 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
3296 // A never going to happen situation that from the estimated allocation rate we will exceed
3297 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08003298 // another GC nearly straight away.
3299 remaining_bytes = kMinConcurrentRemainingBytes;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003300 }
Mathieu Chartier74762802014-01-24 10:21:35 -08003301 DCHECK_LE(remaining_bytes, max_allowed_footprint_);
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003302 DCHECK_LE(max_allowed_footprint_, GetMaxMemory());
Mathieu Chartier74762802014-01-24 10:21:35 -08003303 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
3304 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
3305 // right away.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003306 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
3307 static_cast<size_t>(bytes_allocated));
Mathieu Chartier65db8802012-11-20 12:36:46 -08003308 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08003309 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003310}
3311
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003312void Heap::ClampGrowthLimit() {
Mathieu Chartierddac4232015-04-02 10:08:03 -07003313 // Use heap bitmap lock to guard against races with BindLiveToMarkBitmap.
3314 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003315 capacity_ = growth_limit_;
3316 for (const auto& space : continuous_spaces_) {
3317 if (space->IsMallocSpace()) {
3318 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3319 malloc_space->ClampGrowthLimit();
3320 }
3321 }
3322 // This space isn't added for performance reasons.
3323 if (main_space_backup_.get() != nullptr) {
3324 main_space_backup_->ClampGrowthLimit();
3325 }
3326}
3327
jeffhaoc1160702011-10-27 15:48:45 -07003328void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08003329 growth_limit_ = capacity_;
Mathieu Chartier0310da52014-12-01 13:40:48 -08003330 for (const auto& space : continuous_spaces_) {
3331 if (space->IsMallocSpace()) {
3332 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3333 malloc_space->ClearGrowthLimit();
3334 malloc_space->SetFootprintLimit(malloc_space->Capacity());
3335 }
3336 }
3337 // This space isn't added for performance reasons.
3338 if (main_space_backup_.get() != nullptr) {
3339 main_space_backup_->ClearGrowthLimit();
3340 main_space_backup_->SetFootprintLimit(main_space_backup_->Capacity());
3341 }
jeffhaoc1160702011-10-27 15:48:45 -07003342}
3343
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003344void Heap::AddFinalizerReference(Thread* self, mirror::Object** object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003345 ScopedObjectAccess soa(self);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003346 ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
Ian Rogers53b8b092014-03-13 23:45:53 -07003347 jvalue args[1];
3348 args[0].l = arg.get();
3349 InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003350 // Restore object in case it gets moved.
3351 *object = soa.Decode<mirror::Object*>(arg.get());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003352}
3353
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003354void Heap::RequestConcurrentGCAndSaveObject(Thread* self, bool force_full, mirror::Object** obj) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003355 StackHandleScope<1> hs(self);
3356 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003357 RequestConcurrentGC(self, force_full);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003358}
3359
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003360class Heap::ConcurrentGCTask : public HeapTask {
3361 public:
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003362 explicit ConcurrentGCTask(uint64_t target_time, bool force_full)
3363 : HeapTask(target_time), force_full_(force_full) { }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003364 virtual void Run(Thread* self) OVERRIDE {
3365 gc::Heap* heap = Runtime::Current()->GetHeap();
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003366 heap->ConcurrentGC(self, force_full_);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003367 heap->ClearConcurrentGCRequest();
Ian Rogers120f1c72012-09-28 17:17:10 -07003368 }
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003369
3370 private:
3371 const bool force_full_; // If true, force full (or partial) collection.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003372};
3373
3374static bool CanAddHeapTask(Thread* self) LOCKS_EXCLUDED(Locks::runtime_shutdown_lock_) {
3375 Runtime* runtime = Runtime::Current();
3376 return runtime != nullptr && runtime->IsFinishedStarting() && !runtime->IsShuttingDown(self) &&
3377 !self->IsHandlingStackOverflow();
3378}
3379
3380void Heap::ClearConcurrentGCRequest() {
3381 concurrent_gc_pending_.StoreRelaxed(false);
3382}
3383
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003384void Heap::RequestConcurrentGC(Thread* self, bool force_full) {
Mathieu Chartierac195162015-02-20 18:44:28 +00003385 if (CanAddHeapTask(self) &&
3386 concurrent_gc_pending_.CompareExchangeStrongSequentiallyConsistent(false, true)) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003387 task_processor_->AddTask(self, new ConcurrentGCTask(NanoTime(), // Start straight away.
3388 force_full));
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003389 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003390}
3391
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003392void Heap::ConcurrentGC(Thread* self, bool force_full) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003393 if (!Runtime::Current()->IsShuttingDown(self)) {
3394 // Wait for any GCs currently running to finish.
3395 if (WaitForGcToComplete(kGcCauseBackground, self) == collector::kGcTypeNone) {
3396 // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
3397 // instead. E.g. can't do partial, so do full instead.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003398 collector::GcType next_gc_type = next_gc_type_;
3399 // If forcing full and next gc type is sticky, override with a non-sticky type.
3400 if (force_full && next_gc_type == collector::kGcTypeSticky) {
3401 next_gc_type = HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
3402 }
3403 if (CollectGarbageInternal(next_gc_type, kGcCauseBackground, false) ==
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003404 collector::kGcTypeNone) {
3405 for (collector::GcType gc_type : gc_plan_) {
3406 // Attempt to run the collector, if we succeed, we are done.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003407 if (gc_type > next_gc_type &&
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003408 CollectGarbageInternal(gc_type, kGcCauseBackground, false) !=
3409 collector::kGcTypeNone) {
3410 break;
3411 }
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08003412 }
3413 }
3414 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07003415 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003416}
3417
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003418class Heap::CollectorTransitionTask : public HeapTask {
3419 public:
3420 explicit CollectorTransitionTask(uint64_t target_time) : HeapTask(target_time) { }
3421 virtual void Run(Thread* self) OVERRIDE {
3422 gc::Heap* heap = Runtime::Current()->GetHeap();
3423 heap->DoPendingCollectorTransition();
3424 heap->ClearPendingCollectorTransition(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003425 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003426};
3427
3428void Heap::ClearPendingCollectorTransition(Thread* self) {
3429 MutexLock mu(self, *pending_task_lock_);
3430 pending_collector_transition_ = nullptr;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003431}
3432
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003433void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
3434 Thread* self = Thread::Current();
3435 desired_collector_type_ = desired_collector_type;
3436 if (desired_collector_type_ == collector_type_ || !CanAddHeapTask(self)) {
3437 return;
3438 }
3439 CollectorTransitionTask* added_task = nullptr;
3440 const uint64_t target_time = NanoTime() + delta_time;
3441 {
3442 MutexLock mu(self, *pending_task_lock_);
3443 // If we have an existing collector transition, update the targe time to be the new target.
3444 if (pending_collector_transition_ != nullptr) {
3445 task_processor_->UpdateTargetRunTime(self, pending_collector_transition_, target_time);
3446 return;
3447 }
3448 added_task = new CollectorTransitionTask(target_time);
3449 pending_collector_transition_ = added_task;
3450 }
3451 task_processor_->AddTask(self, added_task);
3452}
3453
3454class Heap::HeapTrimTask : public HeapTask {
3455 public:
3456 explicit HeapTrimTask(uint64_t delta_time) : HeapTask(NanoTime() + delta_time) { }
3457 virtual void Run(Thread* self) OVERRIDE {
3458 gc::Heap* heap = Runtime::Current()->GetHeap();
3459 heap->Trim(self);
3460 heap->ClearPendingTrim(self);
3461 }
3462};
3463
3464void Heap::ClearPendingTrim(Thread* self) {
3465 MutexLock mu(self, *pending_task_lock_);
3466 pending_heap_trim_ = nullptr;
3467}
3468
3469void Heap::RequestTrim(Thread* self) {
3470 if (!CanAddHeapTask(self)) {
3471 return;
3472 }
Ian Rogers48931882013-01-22 14:35:16 -08003473 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3474 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3475 // a space it will hold its lock and can become a cause of jank.
3476 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3477 // forking.
3478
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08003479 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3480 // because that only marks object heads, so a large array looks like lots of empty space. We
3481 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3482 // to utilization (which is probably inversely proportional to how much benefit we can expect).
3483 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3484 // not how much use we're making of those pages.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003485 HeapTrimTask* added_task = nullptr;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003486 {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003487 MutexLock mu(self, *pending_task_lock_);
3488 if (pending_heap_trim_ != nullptr) {
3489 // Already have a heap trim request in task processor, ignore this request.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003490 return;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003491 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003492 added_task = new HeapTrimTask(kHeapTrimWait);
3493 pending_heap_trim_ = added_task;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07003494 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003495 task_processor_->AddTask(self, added_task);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003496}
3497
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003498void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003499 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003500 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3501 if (freed_bytes_revoke > 0U) {
3502 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3503 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3504 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003505 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003506 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003507 CHECK_EQ(bump_pointer_space_->RevokeThreadLocalBuffers(thread), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003508 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003509 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003510 CHECK_EQ(region_space_->RevokeThreadLocalBuffers(thread), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003511 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003512}
3513
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003514void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3515 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003516 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
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 }
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003521 }
3522}
3523
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003524void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003525 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003526 size_t freed_bytes_revoke = rosalloc_space_->RevokeAllThreadLocalBuffers();
3527 if (freed_bytes_revoke > 0U) {
3528 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3529 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3530 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003531 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003532 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003533 CHECK_EQ(bump_pointer_space_->RevokeAllThreadLocalBuffers(), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003534 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003535 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003536 CHECK_EQ(region_space_->RevokeAllThreadLocalBuffers(), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003537 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003538}
3539
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003540bool Heap::IsGCRequestPending() const {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003541 return concurrent_gc_pending_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003542}
3543
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003544void Heap::RunFinalization(JNIEnv* env, uint64_t timeout) {
3545 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
3546 WellKnownClasses::dalvik_system_VMRuntime_runFinalization,
3547 static_cast<jlong>(timeout));
Mathieu Chartier590fee92013-09-13 13:46:47 -07003548}
3549
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003550void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003551 Thread* self = ThreadForEnv(env);
3552 if (native_need_to_run_finalization_) {
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003553 RunFinalization(env, kNativeAllocationFinalizeTimeout);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003554 UpdateMaxNativeFootprint();
3555 native_need_to_run_finalization_ = false;
3556 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003557 // Total number of native bytes allocated.
Ian Rogers3e5cf302014-05-20 16:40:37 -07003558 size_t new_native_bytes_allocated = native_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes);
3559 new_native_bytes_allocated += bytes;
3560 if (new_native_bytes_allocated > native_footprint_gc_watermark_) {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07003561 collector::GcType gc_type = HasZygoteSpace() ? collector::kGcTypePartial :
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08003562 collector::kGcTypeFull;
3563
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003564 // The second watermark is higher than the gc watermark. If you hit this it means you are
3565 // allocating native objects faster than the GC can keep up with.
Mathieu Chartier08487452014-09-02 16:21:01 -07003566 if (new_native_bytes_allocated > growth_limit_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003567 if (WaitForGcToComplete(kGcCauseForNativeAlloc, self) != collector::kGcTypeNone) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003568 // Just finished a GC, attempt to run finalizers.
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003569 RunFinalization(env, kNativeAllocationFinalizeTimeout);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003570 CHECK(!env->ExceptionCheck());
Lin Zang60e27162015-03-10 18:53:21 +08003571 // Native bytes allocated may be updated by finalization, refresh it.
3572 new_native_bytes_allocated = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003573 }
3574 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
Mathieu Chartier08487452014-09-02 16:21:01 -07003575 if (new_native_bytes_allocated > growth_limit_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08003576 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003577 RunFinalization(env, kNativeAllocationFinalizeTimeout);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003578 native_need_to_run_finalization_ = false;
3579 CHECK(!env->ExceptionCheck());
3580 }
3581 // We have just run finalizers, update the native watermark since it is very likely that
3582 // finalizers released native managed allocations.
3583 UpdateMaxNativeFootprint();
3584 } else if (!IsGCRequestPending()) {
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003585 if (IsGcConcurrent()) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003586 RequestConcurrentGC(self, true); // Request non-sticky type.
Mathieu Chartier590fee92013-09-13 13:46:47 -07003587 } else {
Hiroshi Yamauchid20aba12014-04-11 15:31:09 -07003588 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003589 }
3590 }
3591 }
3592}
3593
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003594void Heap::RegisterNativeFree(JNIEnv* env, size_t bytes) {
3595 size_t expected_size;
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003596 do {
Ian Rogers3e5cf302014-05-20 16:40:37 -07003597 expected_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003598 if (UNLIKELY(bytes > expected_size)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003599 ScopedObjectAccess soa(env);
3600 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003601 StringPrintf("Attempted to free %zd native bytes with only %zd native bytes "
Mathieu Chartier590fee92013-09-13 13:46:47 -07003602 "registered as allocated", bytes, expected_size).c_str());
3603 break;
3604 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003605 } while (!native_bytes_allocated_.CompareExchangeWeakRelaxed(expected_size,
3606 expected_size - bytes));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003607}
3608
Ian Rogersef7d42f2014-01-06 12:55:46 -08003609size_t Heap::GetTotalMemory() const {
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003610 return std::max(max_allowed_footprint_, GetBytesAllocated());
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07003611}
3612
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003613void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3614 DCHECK(mod_union_table != nullptr);
3615 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3616}
3617
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003618void Heap::CheckPreconditionsForAllocObject(mirror::Class* c, size_t byte_count) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003619 CHECK(c == nullptr || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers1ff3c982014-08-12 02:30:58 -07003620 (c->IsVariableSize() || c->GetObjectSize() == byte_count));
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003621 CHECK_GE(byte_count, sizeof(mirror::Object));
3622}
3623
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003624void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
3625 CHECK(remembered_set != nullptr);
3626 space::Space* space = remembered_set->GetSpace();
3627 CHECK(space != nullptr);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003628 CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003629 remembered_sets_.Put(space, remembered_set);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003630 CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003631}
3632
3633void Heap::RemoveRememberedSet(space::Space* space) {
3634 CHECK(space != nullptr);
3635 auto it = remembered_sets_.find(space);
3636 CHECK(it != remembered_sets_.end());
Mathieu Chartier5189e242014-07-24 11:11:05 -07003637 delete it->second;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003638 remembered_sets_.erase(it);
3639 CHECK(remembered_sets_.find(space) == remembered_sets_.end());
3640}
3641
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003642void Heap::ClearMarkedObjects() {
3643 // Clear all of the spaces' mark bitmaps.
3644 for (const auto& space : GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07003645 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003646 if (space->GetLiveBitmap() != mark_bitmap) {
3647 mark_bitmap->Clear();
3648 }
3649 }
3650 // Clear the marked objects in the discontinous space object sets.
3651 for (const auto& space : GetDiscontinuousSpaces()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07003652 space->GetMarkBitmap()->Clear();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003653 }
3654}
3655
Ian Rogers1d54e732013-05-02 21:10:01 -07003656} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07003657} // namespace art