blob: d344d81ddc94523b5d28fc2707e5c7b5c3de2ff9 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070018
Mathieu Chartier752a0e62013-06-27 11:03:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
Brian Carlstrom5643b782012-02-05 12:32:53 -080021
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Carl Shapiro58551df2011-07-24 03:09:51 -070024#include <vector>
25
Mathieu Chartierc7853442015-03-27 14:35:38 -070026#include "art_field-inl.h"
Mathieu Chartierbad02672014-08-25 13:08:22 -070027#include "base/allocator.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include "base/dumpable.h"
Mathieu Chartierb2f99362013-11-20 17:26:00 -080029#include "base/histogram-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080030#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010031#include "base/time_utils.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070032#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080033#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070034#include "debugger.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080035#include "dex_file-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070036#include "gc/accounting/atomic_stack.h"
37#include "gc/accounting/card_table-inl.h"
38#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070039#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/accounting/mod_union_table-inl.h"
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -080041#include "gc/accounting/remembered_set.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070042#include "gc/accounting/space_bitmap-inl.h"
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070043#include "gc/collector/concurrent_copying.h"
Mathieu Chartier52e4b432014-06-10 11:22:31 -070044#include "gc/collector/mark_compact.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070045#include "gc/collector/mark_sweep-inl.h"
46#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070047#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070048#include "gc/collector/sticky_mark_sweep.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070049#include "gc/reference_processor.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070050#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070051#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "gc/space/image_space.h"
53#include "gc/space/large_object_space.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080054#include "gc/space/region_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070055#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070056#include "gc/space/space-inl.h"
Mathieu Chartiera1602f22014-01-13 17:19:19 -080057#include "gc/space/zygote_space.h"
Mathieu Chartiera5eae692014-12-17 17:56:03 -080058#include "gc/task_processor.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080059#include "entrypoints/quick/quick_alloc_entrypoints.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070060#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070061#include "image.h"
Mathieu Chartiereb175f72014-10-31 11:49:27 -070062#include "intern_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080063#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "mirror/object.h"
65#include "mirror/object-inl.h"
66#include "mirror/object_array-inl.h"
Mathieu Chartier8fa2dad2014-03-13 12:22:56 -070067#include "mirror/reference-inl.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080068#include "os.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070069#include "reflection.h"
Mathieu Chartier0de9f732013-11-22 17:58:48 -080070#include "runtime.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070071#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070072#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070073#include "handle_scope-inl.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070074#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070075#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070076
77namespace art {
Mathieu Chartier50482232013-11-21 11:48:14 -080078
Ian Rogers1d54e732013-05-02 21:10:01 -070079namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070080
Mathieu Chartier91e30632014-03-25 15:58:50 -070081static constexpr size_t kCollectorTransitionStressIterations = 0;
82static constexpr size_t kCollectorTransitionStressWait = 10 * 1000; // Microseconds
Ian Rogers1d54e732013-05-02 21:10:01 -070083// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070084static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier74762802014-01-24 10:21:35 -080085static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -070086// Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
Mathieu Chartier73d1e172014-04-11 17:53:48 -070087// relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -070088// threads (lower pauses, use less memory bandwidth).
Mathieu Chartier73d1e172014-04-11 17:53:48 -070089static constexpr double kStickyGcThroughputAdjustment = 1.0;
Mathieu Chartierc1790162014-05-23 10:54:50 -070090// Whether or not we compact the zygote in PreZygoteFork.
Mathieu Chartier31f44142014-04-08 14:40:03 -070091static constexpr bool kCompactZygote = kMovingCollector;
Mathieu Chartierc1790162014-05-23 10:54:50 -070092// How many reserve entries are at the end of the allocation stack, these are only needed if the
93// allocation stack overflows.
94static constexpr size_t kAllocationStackReserveSize = 1024;
95// Default mark stack size in bytes.
96static const size_t kDefaultMarkStackSize = 64 * KB;
Zuo Wangf37a88b2014-07-10 04:26:41 -070097// Define space name.
98static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
99static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
100static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
Mathieu Chartier7247af52014-11-19 10:51:42 -0800101static const char* kNonMovingSpaceName = "non moving space";
102static const char* kZygoteSpaceName = "zygote space";
Mathieu Chartierb363f662014-07-16 13:28:58 -0700103static constexpr size_t kGSSBumpPointerSpaceCapacity = 32 * MB;
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800104static constexpr bool kGCALotMode = false;
105// GC alot mode uses a small allocation stack to stress test a lot of GC.
106static constexpr size_t kGcAlotAllocationStackSize = 4 * KB /
107 sizeof(mirror::HeapReference<mirror::Object>);
108// Verify objet has a small allocation stack size since searching the allocation stack is slow.
109static constexpr size_t kVerifyObjectAllocationStackSize = 16 * KB /
110 sizeof(mirror::HeapReference<mirror::Object>);
111static constexpr size_t kDefaultAllocationStackSize = 8 * MB /
112 sizeof(mirror::HeapReference<mirror::Object>);
Mathieu Chartier0051be62012-10-12 17:47:11 -0700113
Mathieu Chartier0051be62012-10-12 17:47:11 -0700114Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700115 double target_utilization, double foreground_heap_growth_multiplier,
116 size_t capacity, size_t non_moving_space_capacity, const std::string& image_file_name,
117 const InstructionSet image_instruction_set, CollectorType foreground_collector_type,
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700118 CollectorType background_collector_type,
119 space::LargeObjectSpaceType large_object_space_type, size_t large_object_threshold,
120 size_t parallel_gc_threads, size_t conc_gc_threads, bool low_memory_mode,
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800121 size_t long_pause_log_threshold, size_t long_gc_log_threshold,
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700122 bool ignore_max_footprint, bool use_tlab,
123 bool verify_pre_gc_heap, bool verify_pre_sweeping_heap, bool verify_post_gc_heap,
124 bool verify_pre_gc_rosalloc, bool verify_pre_sweeping_rosalloc,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700125 bool verify_post_gc_rosalloc, bool use_homogeneous_space_compaction_for_oom,
126 uint64_t min_interval_homogeneous_space_compaction_by_oom)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800127 : non_moving_space_(nullptr),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800128 rosalloc_space_(nullptr),
129 dlmalloc_space_(nullptr),
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800130 main_space_(nullptr),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800131 collector_type_(kCollectorTypeNone),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700132 foreground_collector_type_(foreground_collector_type),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800133 background_collector_type_(background_collector_type),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700134 desired_collector_type_(foreground_collector_type_),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800135 pending_task_lock_(nullptr),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700136 parallel_gc_threads_(parallel_gc_threads),
137 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -0700138 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700139 long_pause_log_threshold_(long_pause_log_threshold),
140 long_gc_log_threshold_(long_gc_log_threshold),
141 ignore_max_footprint_(ignore_max_footprint),
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -0700142 zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700143 zygote_space_(nullptr),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700144 large_object_threshold_(large_object_threshold),
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800145 collector_type_running_(kCollectorTypeNone),
Ian Rogers1d54e732013-05-02 21:10:01 -0700146 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700147 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800148 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700149 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700150 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700151 native_footprint_gc_watermark_(initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700152 native_need_to_run_finalization_(false),
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800153 // Initially assume we perceive jank in case the process state is never updated.
154 process_state_(kProcessStateJankPerceptible),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800155 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700156 total_bytes_freed_ever_(0),
157 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800158 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700159 native_bytes_allocated_(0),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700160 num_bytes_freed_revoke_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700161 verify_missing_card_marks_(false),
162 verify_system_weaks_(false),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800163 verify_pre_gc_heap_(verify_pre_gc_heap),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700164 verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800165 verify_post_gc_heap_(verify_post_gc_heap),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700166 verify_mod_union_table_(false),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800167 verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700168 verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800169 verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700170 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
171 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
172 * verification is enabled, we limit the size of allocation stacks to speed up their
173 * searching.
174 */
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800175 max_allocation_stack_size_(kGCALotMode ? kGcAlotAllocationStackSize
176 : (kVerifyObjectSupport > kVerifyObjectModeFast) ? kVerifyObjectAllocationStackSize :
177 kDefaultAllocationStackSize),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800178 current_allocator_(kAllocatorTypeDlMalloc),
179 current_non_moving_allocator_(kAllocatorTypeNonMoving),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700180 bump_pointer_space_(nullptr),
181 temp_space_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800182 region_space_(nullptr),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700183 min_free_(min_free),
184 max_free_(max_free),
185 target_utilization_(target_utilization),
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -0700186 foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700187 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700188 total_allocation_time_(0),
Mathieu Chartier4e305412014-02-19 10:54:44 -0800189 verify_object_mode_(kVerifyObjectModeDisabled),
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800190 disable_moving_gc_count_(0),
Mathieu Chartierda44d772014-04-01 15:01:46 -0700191 running_on_valgrind_(Runtime::Current()->RunningOnValgrind()),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700192 use_tlab_(use_tlab),
193 main_space_backup_(nullptr),
Mathieu Chartierb363f662014-07-16 13:28:58 -0700194 min_interval_homogeneous_space_compaction_by_oom_(
195 min_interval_homogeneous_space_compaction_by_oom),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700196 last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800197 pending_collector_transition_(nullptr),
198 pending_heap_trim_(nullptr),
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700199 use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom),
200 running_collection_is_blocking_(false),
201 blocking_gc_count_(0U),
202 blocking_gc_time_(0U),
203 last_update_time_gc_count_rate_histograms_( // Round down by the window duration.
204 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration),
205 gc_count_last_window_(0U),
206 blocking_gc_count_last_window_(0U),
207 gc_count_rate_histogram_("gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
208 blocking_gc_count_rate_histogram_("blocking gc count rate histogram", 1U,
209 kGcCountRateMaxBucketCount) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800210 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800211 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700212 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800213 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
214 // entrypoints.
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700215 const bool is_zygote = Runtime::Current()->IsZygote();
216 if (!is_zygote) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700217 // Background compaction is currently not supported for command line runs.
218 if (background_collector_type_ != foreground_collector_type_) {
Mathieu Chartier52ba1992014-05-07 14:39:21 -0700219 VLOG(heap) << "Disabling background compaction for non zygote";
Mathieu Chartier31f44142014-04-08 14:40:03 -0700220 background_collector_type_ = foreground_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800221 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800222 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800223 ChangeCollector(desired_collector_type_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700224 live_bitmap_.reset(new accounting::HeapBitmap(this));
225 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Ian Rogers30fab402012-01-23 15:43:46 -0800226 // Requested begin for the alloc space, to follow the mapped image and oat files
Ian Rogers13735952014-10-08 12:43:28 -0700227 uint8_t* requested_alloc_space_begin = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800228 if (foreground_collector_type_ == kCollectorTypeCC) {
229 // Need to use a low address so that we can allocate a contiguous
230 // 2 * Xmx space when there's no image (dex2oat for target).
231 CHECK_GE(300 * MB, non_moving_space_capacity);
232 requested_alloc_space_begin = reinterpret_cast<uint8_t*>(300 * MB) - non_moving_space_capacity;
233 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800234 if (!image_file_name.empty()) {
Richard Uhler054a0782015-04-07 10:56:50 -0700235 ATRACE_BEGIN("ImageSpace::Create");
Alex Light64ad14d2014-08-19 14:23:13 -0700236 std::string error_msg;
Richard Uhler054a0782015-04-07 10:56:50 -0700237 auto* image_space = space::ImageSpace::Create(image_file_name.c_str(), image_instruction_set,
238 &error_msg);
239 ATRACE_END();
Alex Light64ad14d2014-08-19 14:23:13 -0700240 if (image_space != nullptr) {
241 AddSpace(image_space);
242 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
243 // isn't going to get in the middle
Ian Rogers13735952014-10-08 12:43:28 -0700244 uint8_t* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
Alex Light64ad14d2014-08-19 14:23:13 -0700245 CHECK_GT(oat_file_end_addr, image_space->End());
246 requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
247 } else {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700248 LOG(ERROR) << "Could not create image space with image file '" << image_file_name << "'. "
Alex Light64ad14d2014-08-19 14:23:13 -0700249 << "Attempting to fall back to imageless running. Error was: " << error_msg;
250 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700251 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700252 /*
253 requested_alloc_space_begin -> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700254 +- nonmoving space (non_moving_space_capacity)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700255 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700256 +-????????????????????????????????????????????+-
257 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700258 +-main alloc space / bump space 1 (capacity_) +-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700259 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700260 +-????????????????????????????????????????????+-
261 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
262 +-main alloc space2 / bump space 2 (capacity_)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700263 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
264 */
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800265 // We don't have hspace compaction enabled with GSS or CC.
266 if (foreground_collector_type_ == kCollectorTypeGSS ||
267 foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800268 use_homogeneous_space_compaction_for_oom_ = false;
269 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700270 bool support_homogeneous_space_compaction =
Mathieu Chartier0deeb812014-08-21 18:28:20 -0700271 background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800272 use_homogeneous_space_compaction_for_oom_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700273 // We may use the same space the main space for the non moving space if we don't need to compact
274 // from the main space.
275 // This is not the case if we support homogeneous compaction or have a moving background
276 // collector type.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700277 bool separate_non_moving_space = is_zygote ||
278 support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
279 IsMovingGc(background_collector_type_);
280 if (foreground_collector_type == kCollectorTypeGSS) {
281 separate_non_moving_space = false;
282 }
283 std::unique_ptr<MemMap> main_mem_map_1;
284 std::unique_ptr<MemMap> main_mem_map_2;
Ian Rogers13735952014-10-08 12:43:28 -0700285 uint8_t* request_begin = requested_alloc_space_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700286 if (request_begin != nullptr && separate_non_moving_space) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700287 request_begin += non_moving_space_capacity;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700288 }
289 std::string error_str;
290 std::unique_ptr<MemMap> non_moving_space_mem_map;
Richard Uhler054a0782015-04-07 10:56:50 -0700291 ATRACE_BEGIN("Create heap maps");
Mathieu Chartierb363f662014-07-16 13:28:58 -0700292 if (separate_non_moving_space) {
Mathieu Chartier7247af52014-11-19 10:51:42 -0800293 // If we are the zygote, the non moving space becomes the zygote space when we run
294 // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
295 // rename the mem map later.
296 const char* space_name = is_zygote ? kZygoteSpaceName: kNonMovingSpaceName;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700297 // Reserve the non moving mem map before the other two since it needs to be at a specific
298 // address.
299 non_moving_space_mem_map.reset(
Mathieu Chartier7247af52014-11-19 10:51:42 -0800300 MemMap::MapAnonymous(space_name, requested_alloc_space_begin,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000301 non_moving_space_capacity, PROT_READ | PROT_WRITE, true, false,
302 &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700303 CHECK(non_moving_space_mem_map != nullptr) << error_str;
Mathieu Chartierc44ce2e2014-08-25 16:32:41 -0700304 // Try to reserve virtual memory at a lower address if we have a separate non moving space.
Ian Rogers13735952014-10-08 12:43:28 -0700305 request_begin = reinterpret_cast<uint8_t*>(300 * MB);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700306 }
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700307 // Attempt to create 2 mem maps at or after the requested begin.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800308 if (foreground_collector_type_ != kCollectorTypeCC) {
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700309 if (separate_non_moving_space) {
310 main_mem_map_1.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[0], request_begin,
311 capacity_, &error_str));
312 } else {
313 // If no separate non-moving space, the main space must come
314 // right after the image space to avoid a gap.
315 main_mem_map_1.reset(MemMap::MapAnonymous(kMemMapSpaceName[0], request_begin, capacity_,
316 PROT_READ | PROT_WRITE, true, false,
317 &error_str));
318 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800319 CHECK(main_mem_map_1.get() != nullptr) << error_str;
320 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700321 if (support_homogeneous_space_compaction ||
322 background_collector_type_ == kCollectorTypeSS ||
323 foreground_collector_type_ == kCollectorTypeSS) {
324 main_mem_map_2.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[1], main_mem_map_1->End(),
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700325 capacity_, &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700326 CHECK(main_mem_map_2.get() != nullptr) << error_str;
327 }
Richard Uhler054a0782015-04-07 10:56:50 -0700328 ATRACE_END();
329 ATRACE_BEGIN("Create spaces");
Mathieu Chartierb363f662014-07-16 13:28:58 -0700330 // Create the non moving space first so that bitmaps don't take up the address range.
331 if (separate_non_moving_space) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700332 // Non moving space is always dlmalloc since we currently don't have support for multiple
Zuo Wangf37a88b2014-07-10 04:26:41 -0700333 // active rosalloc spaces.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700334 const size_t size = non_moving_space_mem_map->Size();
335 non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700336 non_moving_space_mem_map.release(), "zygote / non moving space", kDefaultStartingSize,
Mathieu Chartierb363f662014-07-16 13:28:58 -0700337 initial_size, size, size, false);
Mathieu Chartier78408882014-04-11 18:06:01 -0700338 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Mathieu Chartierb363f662014-07-16 13:28:58 -0700339 CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
340 << requested_alloc_space_begin;
341 AddSpace(non_moving_space_);
342 }
343 // Create other spaces based on whether or not we have a moving GC.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800344 if (foreground_collector_type_ == kCollectorTypeCC) {
345 region_space_ = space::RegionSpace::Create("Region space", capacity_ * 2, request_begin);
346 AddSpace(region_space_);
Richard Uhler054a0782015-04-07 10:56:50 -0700347 } else if (IsMovingGc(foreground_collector_type_) &&
348 foreground_collector_type_ != kCollectorTypeGSS) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700349 // Create bump pointer spaces.
350 // We only to create the bump pointer if the foreground collector is a compacting GC.
351 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
352 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
353 main_mem_map_1.release());
354 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
355 AddSpace(bump_pointer_space_);
356 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
357 main_mem_map_2.release());
358 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
359 AddSpace(temp_space_);
360 CHECK(separate_non_moving_space);
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700361 } else {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700362 CreateMainMallocSpace(main_mem_map_1.release(), initial_size, growth_limit_, capacity_);
363 CHECK(main_space_ != nullptr);
364 AddSpace(main_space_);
365 if (!separate_non_moving_space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700366 non_moving_space_ = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700367 CHECK(!non_moving_space_->CanMoveObjects());
368 }
369 if (foreground_collector_type_ == kCollectorTypeGSS) {
370 CHECK_EQ(foreground_collector_type_, background_collector_type_);
371 // Create bump pointer spaces instead of a backup space.
372 main_mem_map_2.release();
373 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space 1",
374 kGSSBumpPointerSpaceCapacity, nullptr);
375 CHECK(bump_pointer_space_ != nullptr);
376 AddSpace(bump_pointer_space_);
377 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2",
378 kGSSBumpPointerSpaceCapacity, nullptr);
379 CHECK(temp_space_ != nullptr);
380 AddSpace(temp_space_);
381 } else if (main_mem_map_2.get() != nullptr) {
382 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
383 main_space_backup_.reset(CreateMallocSpaceFromMemMap(main_mem_map_2.release(), initial_size,
384 growth_limit_, capacity_, name, true));
385 CHECK(main_space_backup_.get() != nullptr);
386 // Add the space so its accounted for in the heap_begin and heap_end.
387 AddSpace(main_space_backup_.get());
Zuo Wangf37a88b2014-07-10 04:26:41 -0700388 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700389 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700390 CHECK(non_moving_space_ != nullptr);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700391 CHECK(!non_moving_space_->CanMoveObjects());
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700392 // Allocate the large object space.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800393 if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700394 large_object_space_ = space::FreeListSpace::Create("free list large object space", nullptr,
395 capacity_);
396 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800397 } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700398 large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
399 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700400 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700401 // Disable the large object space by making the cutoff excessively large.
402 large_object_threshold_ = std::numeric_limits<size_t>::max();
403 large_object_space_ = nullptr;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700404 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700405 if (large_object_space_ != nullptr) {
406 AddSpace(large_object_space_);
407 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700408 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700409 CHECK(!continuous_spaces_.empty());
410 // Relies on the spaces being sorted.
Ian Rogers13735952014-10-08 12:43:28 -0700411 uint8_t* heap_begin = continuous_spaces_.front()->Begin();
412 uint8_t* heap_end = continuous_spaces_.back()->Limit();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700413 size_t heap_capacity = heap_end - heap_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700414 // Remove the main backup space since it slows down the GC to have unused extra spaces.
Mathieu Chartier0310da52014-12-01 13:40:48 -0800415 // TODO: Avoid needing to do this.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700416 if (main_space_backup_.get() != nullptr) {
417 RemoveSpace(main_space_backup_.get());
418 }
Richard Uhler054a0782015-04-07 10:56:50 -0700419 ATRACE_END();
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800420 // Allocate the card table.
Richard Uhler054a0782015-04-07 10:56:50 -0700421 ATRACE_BEGIN("Create card table");
Ian Rogers1d54e732013-05-02 21:10:01 -0700422 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700423 CHECK(card_table_.get() != nullptr) << "Failed to create card table";
Richard Uhler054a0782015-04-07 10:56:50 -0700424 ATRACE_END();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800425 if (foreground_collector_type_ == kCollectorTypeCC && kUseTableLookupReadBarrier) {
426 rb_table_.reset(new accounting::ReadBarrierTable());
427 DCHECK(rb_table_->IsAllCleared());
428 }
Mathieu Chartier4858a932015-01-23 13:18:53 -0800429 if (GetImageSpace() != nullptr) {
430 // Don't add the image mod union table if we are running without an image, this can crash if
431 // we use the CardCache implementation.
432 accounting::ModUnionTable* mod_union_table = new accounting::ModUnionTableToZygoteAllocspace(
433 "Image mod-union table", this, GetImageSpace());
434 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
435 AddModUnionTable(mod_union_table);
436 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700437 if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800438 accounting::RememberedSet* non_moving_space_rem_set =
439 new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
440 CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
441 AddRememberedSet(non_moving_space_rem_set);
442 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700443 // TODO: Count objects in the image space here?
Ian Rogers3e5cf302014-05-20 16:40:37 -0700444 num_bytes_allocated_.StoreRelaxed(0);
Mathieu Chartierc1790162014-05-23 10:54:50 -0700445 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
446 kDefaultMarkStackSize));
447 const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
448 allocation_stack_.reset(accounting::ObjectStack::Create(
449 "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
450 live_stack_.reset(accounting::ObjectStack::Create(
451 "live stack", max_allocation_stack_size_, alloc_stack_capacity));
Mathieu Chartier65db8802012-11-20 12:36:46 -0800452 // It's still too early to take a lock because there are no threads yet, but we can create locks
453 // now. We don't create it earlier to make it clear that you can't use locks during heap
454 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700455 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700456 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
457 *gc_complete_lock_));
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800458 task_processor_.reset(new TaskProcessor());
459 pending_task_lock_ = new Mutex("Pending task lock");
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700460 if (ignore_max_footprint_) {
461 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700462 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700463 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700464 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800465 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800466 for (size_t i = 0; i < 2; ++i) {
467 const bool concurrent = i != 0;
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800468 if ((MayUseCollector(kCollectorTypeCMS) && concurrent) ||
469 (MayUseCollector(kCollectorTypeMS) && !concurrent)) {
470 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
471 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
472 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
473 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800474 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800475 if (kMovingCollector) {
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800476 if (MayUseCollector(kCollectorTypeSS) || MayUseCollector(kCollectorTypeGSS) ||
477 MayUseCollector(kCollectorTypeHomogeneousSpaceCompact) ||
478 use_homogeneous_space_compaction_for_oom_) {
479 // TODO: Clean this up.
480 const bool generational = foreground_collector_type_ == kCollectorTypeGSS;
481 semi_space_collector_ = new collector::SemiSpace(this, generational,
482 generational ? "generational" : "");
483 garbage_collectors_.push_back(semi_space_collector_);
484 }
485 if (MayUseCollector(kCollectorTypeCC)) {
486 concurrent_copying_collector_ = new collector::ConcurrentCopying(this);
487 garbage_collectors_.push_back(concurrent_copying_collector_);
488 }
489 if (MayUseCollector(kCollectorTypeMC)) {
490 mark_compact_collector_ = new collector::MarkCompact(this);
491 garbage_collectors_.push_back(mark_compact_collector_);
492 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700493 }
Andreas Gampee1cb2982014-08-27 11:01:09 -0700494 if (GetImageSpace() != nullptr && non_moving_space_ != nullptr &&
495 (is_zygote || separate_non_moving_space || foreground_collector_type_ == kCollectorTypeGSS)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700496 // 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 -0700497 // immune region won't break (eg. due to a large object allocated in the gap). This is only
498 // required when we're the zygote or using GSS.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700499 bool no_gap = MemMap::CheckNoGaps(GetImageSpace()->GetMemMap(),
500 non_moving_space_->GetMemMap());
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700501 if (!no_gap) {
Vladimir Marko17a924a2015-05-08 15:17:32 +0100502 MemMap::DumpMaps(LOG(ERROR), true);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700503 LOG(FATAL) << "There's a gap between the image space and the non-moving space";
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700504 }
505 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700506 if (running_on_valgrind_) {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700507 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700508 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800509 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800510 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700511 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700512}
513
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700514MemMap* Heap::MapAnonymousPreferredAddress(const char* name, uint8_t* request_begin,
515 size_t capacity, std::string* out_error_str) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700516 while (true) {
Kyungmin Leeef32b8f2014-10-23 09:32:05 +0900517 MemMap* map = MemMap::MapAnonymous(name, request_begin, capacity,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000518 PROT_READ | PROT_WRITE, true, false, out_error_str);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700519 if (map != nullptr || request_begin == nullptr) {
520 return map;
521 }
522 // Retry a second time with no specified request begin.
523 request_begin = nullptr;
524 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700525}
526
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800527bool Heap::MayUseCollector(CollectorType type) const {
528 return foreground_collector_type_ == type || background_collector_type_ == type;
529}
530
Zuo Wangf37a88b2014-07-10 04:26:41 -0700531space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap* mem_map, size_t initial_size,
532 size_t growth_limit, size_t capacity,
533 const char* name, bool can_move_objects) {
534 space::MallocSpace* malloc_space = nullptr;
535 if (kUseRosAlloc) {
536 // Create rosalloc space.
537 malloc_space = space::RosAllocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
538 initial_size, growth_limit, capacity,
539 low_memory_mode_, can_move_objects);
540 } else {
541 malloc_space = space::DlMallocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
542 initial_size, growth_limit, capacity,
543 can_move_objects);
544 }
545 if (collector::SemiSpace::kUseRememberedSet) {
546 accounting::RememberedSet* rem_set =
547 new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
548 CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
549 AddRememberedSet(rem_set);
550 }
551 CHECK(malloc_space != nullptr) << "Failed to create " << name;
552 malloc_space->SetFootprintLimit(malloc_space->Capacity());
553 return malloc_space;
554}
555
Mathieu Chartier31f44142014-04-08 14:40:03 -0700556void Heap::CreateMainMallocSpace(MemMap* mem_map, size_t initial_size, size_t growth_limit,
557 size_t capacity) {
558 // Is background compaction is enabled?
559 bool can_move_objects = IsMovingGc(background_collector_type_) !=
Zuo Wangf37a88b2014-07-10 04:26:41 -0700560 IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700561 // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
562 // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
563 // from the main space to the zygote space. If background compaction is enabled, always pass in
564 // that we can move objets.
565 if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
566 // After the zygote we want this to be false if we don't have background compaction enabled so
567 // that getting primitive array elements is faster.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700568 // We never have homogeneous compaction with GSS and don't need a space with movable objects.
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700569 can_move_objects = !HasZygoteSpace() && foreground_collector_type_ != kCollectorTypeGSS;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700570 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700571 if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
572 RemoveRememberedSet(main_space_);
573 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700574 const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
575 main_space_ = CreateMallocSpaceFromMemMap(mem_map, initial_size, growth_limit, capacity, name,
576 can_move_objects);
577 SetSpaceAsDefault(main_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700578 VLOG(heap) << "Created main space " << main_space_;
579}
580
Mathieu Chartier50482232013-11-21 11:48:14 -0800581void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800582 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800583 // These two allocators are only used internally and don't have any entrypoints.
584 CHECK_NE(allocator, kAllocatorTypeLOS);
585 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800586 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800587 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800588 SetQuickAllocEntryPointsAllocator(current_allocator_);
589 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
590 }
591}
592
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700593void Heap::DisableMovingGc() {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700594 if (IsMovingGc(foreground_collector_type_)) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700595 foreground_collector_type_ = kCollectorTypeCMS;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800596 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700597 if (IsMovingGc(background_collector_type_)) {
598 background_collector_type_ = foreground_collector_type_;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800599 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700600 TransitionCollector(foreground_collector_type_);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700601 ThreadList* tl = Runtime::Current()->GetThreadList();
602 Thread* self = Thread::Current();
603 ScopedThreadStateChange tsc(self, kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700604 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700605 // Something may have caused the transition to fail.
Mathieu Chartiere4927f62014-08-23 13:56:03 -0700606 if (!IsMovingGc(collector_type_) && non_moving_space_ != main_space_) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700607 CHECK(main_space_ != nullptr);
608 // The allocation stack may have non movable objects in it. We need to flush it since the GC
609 // can't only handle marking allocation stack objects of one non moving space and one main
610 // space.
611 {
612 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
613 FlushAllocStack();
614 }
615 main_space_->DisableMovingObjects();
616 non_moving_space_ = main_space_;
617 CHECK(!non_moving_space_->CanMoveObjects());
618 }
619 tl->ResumeAll();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800620}
621
Mathieu Chartier15d34022014-02-26 17:16:38 -0800622std::string Heap::SafeGetClassDescriptor(mirror::Class* klass) {
623 if (!IsValidContinuousSpaceObjectAddress(klass)) {
624 return StringPrintf("<non heap address klass %p>", klass);
625 }
626 mirror::Class* component_type = klass->GetComponentType<kVerifyNone>();
627 if (IsValidContinuousSpaceObjectAddress(component_type) && klass->IsArrayClass<kVerifyNone>()) {
628 std::string result("[");
629 result += SafeGetClassDescriptor(component_type);
630 return result;
631 } else if (UNLIKELY(klass->IsPrimitive<kVerifyNone>())) {
632 return Primitive::Descriptor(klass->GetPrimitiveType<kVerifyNone>());
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800633 } else if (UNLIKELY(klass->IsProxyClass<kVerifyNone>())) {
Mathieu Chartier15d34022014-02-26 17:16:38 -0800634 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(klass);
635 } else {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800636 mirror::DexCache* dex_cache = klass->GetDexCache<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800637 if (!IsValidContinuousSpaceObjectAddress(dex_cache)) {
638 return StringPrintf("<non heap address dex_cache %p>", dex_cache);
639 }
640 const DexFile* dex_file = dex_cache->GetDexFile();
641 uint16_t class_def_idx = klass->GetDexClassDefIndex();
642 if (class_def_idx == DexFile::kDexNoIndex16) {
643 return "<class def not found>";
644 }
645 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
646 const DexFile::TypeId& type_id = dex_file->GetTypeId(class_def.class_idx_);
647 return dex_file->GetTypeDescriptor(type_id);
648 }
649}
650
651std::string Heap::SafePrettyTypeOf(mirror::Object* obj) {
652 if (obj == nullptr) {
653 return "null";
654 }
655 mirror::Class* klass = obj->GetClass<kVerifyNone>();
656 if (klass == nullptr) {
657 return "(class=null)";
658 }
659 std::string result(SafeGetClassDescriptor(klass));
660 if (obj->IsClass()) {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800661 result += "<" + SafeGetClassDescriptor(obj->AsClass<kVerifyNone>()) + ">";
Mathieu Chartier15d34022014-02-26 17:16:38 -0800662 }
663 return result;
664}
665
666void Heap::DumpObject(std::ostream& stream, mirror::Object* obj) {
667 if (obj == nullptr) {
668 stream << "(obj=null)";
669 return;
670 }
671 if (IsAligned<kObjectAlignment>(obj)) {
672 space::Space* space = nullptr;
673 // Don't use find space since it only finds spaces which actually contain objects instead of
674 // spaces which may contain objects (e.g. cleared bump pointer spaces).
675 for (const auto& cur_space : continuous_spaces_) {
676 if (cur_space->HasAddress(obj)) {
677 space = cur_space;
678 break;
679 }
680 }
Mathieu Chartier15d34022014-02-26 17:16:38 -0800681 // Unprotect all the spaces.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800682 for (const auto& con_space : continuous_spaces_) {
683 mprotect(con_space->Begin(), con_space->Capacity(), PROT_READ | PROT_WRITE);
Mathieu Chartier15d34022014-02-26 17:16:38 -0800684 }
685 stream << "Object " << obj;
686 if (space != nullptr) {
687 stream << " in space " << *space;
688 }
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800689 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800690 stream << "\nclass=" << klass;
691 if (klass != nullptr) {
692 stream << " type= " << SafePrettyTypeOf(obj);
693 }
694 // Re-protect the address we faulted on.
695 mprotect(AlignDown(obj, kPageSize), kPageSize, PROT_NONE);
696 }
697}
698
Mathieu Chartier590fee92013-09-13 13:46:47 -0700699bool Heap::IsCompilingBoot() const {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800700 if (!Runtime::Current()->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700701 return false;
702 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700703 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800704 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700705 return false;
706 }
707 }
708 return true;
709}
710
711bool Heap::HasImageSpace() const {
712 for (const auto& space : continuous_spaces_) {
713 if (space->IsImageSpace()) {
714 return true;
715 }
716 }
717 return false;
718}
719
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800720void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700721 // Need to do this holding the lock to prevent races where the GC is about to run / running when
722 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800723 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700724 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800725 ++disable_moving_gc_count_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700726 if (IsMovingGc(collector_type_running_)) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -0700727 WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800728 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700729}
730
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800731void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700732 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800733 CHECK_GE(disable_moving_gc_count_, 0U);
734 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700735}
736
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800737void Heap::UpdateProcessState(ProcessState process_state) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800738 if (process_state_ != process_state) {
739 process_state_ = process_state;
Mathieu Chartier91e30632014-03-25 15:58:50 -0700740 for (size_t i = 1; i <= kCollectorTransitionStressIterations; ++i) {
741 // Start at index 1 to avoid "is always false" warning.
742 // Have iteration 1 always transition the collector.
743 TransitionCollector((((i & 1) == 1) == (process_state_ == kProcessStateJankPerceptible))
Mathieu Chartier31f44142014-04-08 14:40:03 -0700744 ? foreground_collector_type_ : background_collector_type_);
Mathieu Chartier91e30632014-03-25 15:58:50 -0700745 usleep(kCollectorTransitionStressWait);
746 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800747 if (process_state_ == kProcessStateJankPerceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800748 // Transition back to foreground right away to prevent jank.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700749 RequestCollectorTransition(foreground_collector_type_, 0);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800750 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800751 // Don't delay for debug builds since we may want to stress test the GC.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700752 // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
753 // special handling which does a homogenous space compaction once but then doesn't transition
754 // the collector.
755 RequestCollectorTransition(background_collector_type_,
756 kIsDebugBuild ? 0 : kCollectorTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800757 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800758 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800759}
760
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700761void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700762 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
763 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800764 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700765 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700766}
767
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800768// Visit objects when threads aren't suspended. If concurrent moving
769// GC, disable moving GC and suspend threads and then visit objects.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800770void Heap::VisitObjects(ObjectCallback callback, void* arg) {
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800771 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800772 Locks::mutator_lock_->AssertSharedHeld(self);
773 DCHECK(!Locks::mutator_lock_->IsExclusiveHeld(self)) << "Call VisitObjectsPaused() instead";
774 if (IsGcConcurrentAndMoving()) {
775 // Concurrent moving GC. Just suspending threads isn't sufficient
776 // because a collection isn't one big pause and we could suspend
777 // threads in the middle (between phases) of a concurrent moving
778 // collection where it's not easily known which objects are alive
779 // (both the region space and the non-moving space) or which
780 // copies of objects to visit, and the to-space invariant could be
781 // easily broken. Visit objects while GC isn't running by using
782 // IncrementDisableMovingGC() and threads are suspended.
783 IncrementDisableMovingGC(self);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800784 self->TransitionFromRunnableToSuspended(kWaitingForVisitObjects);
785 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700786 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800787 VisitObjectsInternalRegionSpace(callback, arg);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800788 VisitObjectsInternal(callback, arg);
789 tl->ResumeAll();
790 self->TransitionFromSuspendedToRunnable();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800791 DecrementDisableMovingGC(self);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800792 } else {
793 // GCs can move objects, so don't allow this.
794 ScopedAssertNoThreadSuspension ants(self, "Visiting objects");
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800795 DCHECK(region_space_ == nullptr);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800796 VisitObjectsInternal(callback, arg);
797 }
798}
799
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800800// Visit objects when threads are already suspended.
801void Heap::VisitObjectsPaused(ObjectCallback callback, void* arg) {
802 Thread* self = Thread::Current();
803 Locks::mutator_lock_->AssertExclusiveHeld(self);
804 VisitObjectsInternalRegionSpace(callback, arg);
805 VisitObjectsInternal(callback, arg);
806}
807
808// Visit objects in the region spaces.
809void Heap::VisitObjectsInternalRegionSpace(ObjectCallback callback, void* arg) {
810 Thread* self = Thread::Current();
811 Locks::mutator_lock_->AssertExclusiveHeld(self);
812 if (region_space_ != nullptr) {
813 DCHECK(IsGcConcurrentAndMoving());
814 if (!zygote_creation_lock_.IsExclusiveHeld(self)) {
815 // Exclude the pre-zygote fork time where the semi-space collector
816 // calls VerifyHeapReferences() as part of the zygote compaction
817 // which then would call here without the moving GC disabled,
818 // which is fine.
819 DCHECK(IsMovingGCDisabled(self));
820 }
821 region_space_->Walk(callback, arg);
822 }
823}
824
825// Visit objects in the other spaces.
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800826void Heap::VisitObjectsInternal(ObjectCallback callback, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700827 if (bump_pointer_space_ != nullptr) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800828 // Visit objects in bump pointer space.
829 bump_pointer_space_->Walk(callback, arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700830 }
831 // TODO: Switch to standard begin and end to use ranged a based loop.
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800832 for (auto* it = allocation_stack_->Begin(), *end = allocation_stack_->End(); it < end; ++it) {
833 mirror::Object* const obj = it->AsMirrorPtr();
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800834 if (obj != nullptr && obj->GetClass() != nullptr) {
835 // Avoid the race condition caused by the object not yet being written into the allocation
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800836 // stack or the class not yet being written in the object. Or, if
837 // kUseThreadLocalAllocationStack, there can be nulls on the allocation stack.
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800838 callback(obj, arg);
839 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700840 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800841 {
842 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
843 GetLiveBitmap()->Walk(callback, arg);
844 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700845}
846
847void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartier00b59152014-07-25 10:13:51 -0700848 space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
849 space::ContinuousSpace* space2 = non_moving_space_;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800850 // TODO: Generalize this to n bitmaps?
Mathieu Chartier00b59152014-07-25 10:13:51 -0700851 CHECK(space1 != nullptr);
852 CHECK(space2 != nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800853 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700854 (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
855 stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700856}
857
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700858void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700859 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700860}
861
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700862void Heap::AddSpace(space::Space* space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700863 CHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700864 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
865 if (space->IsContinuousSpace()) {
866 DCHECK(!space->IsDiscontinuousSpace());
867 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
868 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700869 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
870 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700871 if (live_bitmap != nullptr) {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700872 CHECK(mark_bitmap != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700873 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
874 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700875 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700876 continuous_spaces_.push_back(continuous_space);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700877 // Ensure that spaces remain sorted in increasing order of start address.
878 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
879 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
880 return a->Begin() < b->Begin();
881 });
Mathieu Chartier590fee92013-09-13 13:46:47 -0700882 } else {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700883 CHECK(space->IsDiscontinuousSpace());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700884 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700885 live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
886 mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700887 discontinuous_spaces_.push_back(discontinuous_space);
888 }
889 if (space->IsAllocSpace()) {
890 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700891 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800892}
893
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700894void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
895 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
896 if (continuous_space->IsDlMallocSpace()) {
897 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
898 } else if (continuous_space->IsRosAllocSpace()) {
899 rosalloc_space_ = continuous_space->AsRosAllocSpace();
900 }
901}
902
903void Heap::RemoveSpace(space::Space* space) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800904 DCHECK(space != nullptr);
905 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
906 if (space->IsContinuousSpace()) {
907 DCHECK(!space->IsDiscontinuousSpace());
908 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
909 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700910 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
911 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800912 if (live_bitmap != nullptr) {
913 DCHECK(mark_bitmap != nullptr);
914 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
915 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
916 }
917 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
918 DCHECK(it != continuous_spaces_.end());
919 continuous_spaces_.erase(it);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800920 } else {
921 DCHECK(space->IsDiscontinuousSpace());
922 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700923 live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
924 mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800925 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
926 discontinuous_space);
927 DCHECK(it != discontinuous_spaces_.end());
928 discontinuous_spaces_.erase(it);
929 }
930 if (space->IsAllocSpace()) {
931 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
932 DCHECK(it != alloc_spaces_.end());
933 alloc_spaces_.erase(it);
934 }
935}
936
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700937void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700938 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700939 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700940 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800941 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800942 uint64_t total_paused_time = 0;
Mathieu Chartier5a487192014-04-08 11:14:54 -0700943 for (auto& collector : garbage_collectors_) {
Mathieu Chartier104fa0c2014-08-07 14:26:27 -0700944 total_duration += collector->GetCumulativeTimings().GetTotalNs();
945 total_paused_time += collector->GetTotalPausedTimeNs();
946 collector->DumpPerformanceInfo(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700947 }
Ian Rogers3e5cf302014-05-20 16:40:37 -0700948 uint64_t allocation_time =
949 static_cast<uint64_t>(total_allocation_time_.LoadRelaxed()) * kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700950 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700951 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700952 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
953 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700954 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700955 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700956 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700957 }
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700958 uint64_t total_objects_allocated = GetObjectsAllocatedEver();
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700959 os << "Total number of allocations " << total_objects_allocated << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700960 os << "Total bytes allocated " << PrettySize(GetBytesAllocatedEver()) << "\n";
961 os << "Total bytes freed " << PrettySize(GetBytesFreedEver()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700962 os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700963 os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
964 os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700965 os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
966 os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700967 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700968 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
969 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
970 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700971 }
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700972 if (HasZygoteSpace()) {
973 os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
974 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700975 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700976 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
977 os << "Total GC count: " << GetGcCount() << "\n";
978 os << "Total GC time: " << PrettyDuration(GetGcTime()) << "\n";
979 os << "Total blocking GC count: " << GetBlockingGcCount() << "\n";
980 os << "Total blocking GC time: " << PrettyDuration(GetBlockingGcTime()) << "\n";
981
982 {
983 MutexLock mu(Thread::Current(), *gc_complete_lock_);
984 if (gc_count_rate_histogram_.SampleSize() > 0U) {
985 os << "Histogram of GC count per " << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
986 gc_count_rate_histogram_.DumpBins(os);
987 os << "\n";
988 }
989 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
990 os << "Histogram of blocking GC count per "
991 << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
992 blocking_gc_count_rate_histogram_.DumpBins(os);
993 os << "\n";
994 }
995 }
996
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700997 BaseMutex::DumpAll(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700998}
999
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001000uint64_t Heap::GetGcCount() const {
1001 uint64_t gc_count = 0U;
1002 for (auto& collector : garbage_collectors_) {
1003 gc_count += collector->GetCumulativeTimings().GetIterations();
1004 }
1005 return gc_count;
1006}
1007
1008uint64_t Heap::GetGcTime() const {
1009 uint64_t gc_time = 0U;
1010 for (auto& collector : garbage_collectors_) {
1011 gc_time += collector->GetCumulativeTimings().GetTotalNs();
1012 }
1013 return gc_time;
1014}
1015
1016uint64_t Heap::GetBlockingGcCount() const {
1017 return blocking_gc_count_;
1018}
1019
1020uint64_t Heap::GetBlockingGcTime() const {
1021 return blocking_gc_time_;
1022}
1023
1024void Heap::DumpGcCountRateHistogram(std::ostream& os) const {
1025 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1026 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1027 gc_count_rate_histogram_.DumpBins(os);
1028 }
1029}
1030
1031void Heap::DumpBlockingGcCountRateHistogram(std::ostream& os) const {
1032 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1033 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1034 blocking_gc_count_rate_histogram_.DumpBins(os);
1035 }
1036}
1037
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001038Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001039 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001040 STLDeleteElements(&garbage_collectors_);
1041 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001042 allocation_stack_->Reset();
1043 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001044 STLDeleteValues(&mod_union_tables_);
Mathieu Chartier0767c9a2014-03-26 12:53:19 -07001045 STLDeleteValues(&remembered_sets_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001046 STLDeleteElements(&continuous_spaces_);
1047 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001048 delete gc_complete_lock_;
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001049 delete pending_task_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001050 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001051}
1052
Ian Rogers1d54e732013-05-02 21:10:01 -07001053space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
1054 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001055 for (const auto& space : continuous_spaces_) {
1056 if (space->Contains(obj)) {
1057 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001058 }
1059 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001060 if (!fail_ok) {
1061 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
1062 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001063 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001064}
1065
Ian Rogers1d54e732013-05-02 21:10:01 -07001066space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
1067 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001068 for (const auto& space : discontinuous_spaces_) {
1069 if (space->Contains(obj)) {
1070 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -07001071 }
1072 }
1073 if (!fail_ok) {
1074 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
1075 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001076 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001077}
1078
1079space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
1080 space::Space* result = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001081 if (result != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001082 return result;
1083 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001084 return FindDiscontinuousSpaceFromObject(obj, fail_ok);
Ian Rogers1d54e732013-05-02 21:10:01 -07001085}
1086
1087space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001088 for (const auto& space : continuous_spaces_) {
1089 if (space->IsImageSpace()) {
1090 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001091 }
1092 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001093 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001094}
1095
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001096void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001097 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001098 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001099 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001100 << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM";
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001101 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001102 if (total_bytes_free >= byte_count) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001103 space::AllocSpace* space = nullptr;
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001104 if (allocator_type == kAllocatorTypeNonMoving) {
1105 space = non_moving_space_;
1106 } else if (allocator_type == kAllocatorTypeRosAlloc ||
1107 allocator_type == kAllocatorTypeDlMalloc) {
1108 space = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -07001109 } else if (allocator_type == kAllocatorTypeBumpPointer ||
1110 allocator_type == kAllocatorTypeTLAB) {
1111 space = bump_pointer_space_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001112 } else if (allocator_type == kAllocatorTypeRegion ||
1113 allocator_type == kAllocatorTypeRegionTLAB) {
1114 space = region_space_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001115 }
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001116 if (space != nullptr) {
1117 space->LogFragmentationAllocFailure(oss, byte_count);
1118 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001119 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001120 self->ThrowOutOfMemoryError(oss.str().c_str());
1121}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001122
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001123void Heap::DoPendingCollectorTransition() {
1124 CollectorType desired_collector_type = desired_collector_type_;
Mathieu Chartierb2728552014-09-08 20:08:41 +00001125 // Launch homogeneous space compaction if it is desired.
1126 if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
1127 if (!CareAboutPauseTimes()) {
1128 PerformHomogeneousSpaceCompact();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001129 } else {
1130 VLOG(gc) << "Homogeneous compaction ignored due to jank perceptible process state";
Mathieu Chartierb2728552014-09-08 20:08:41 +00001131 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001132 } else {
1133 TransitionCollector(desired_collector_type);
Mathieu Chartierb2728552014-09-08 20:08:41 +00001134 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001135}
1136
1137void Heap::Trim(Thread* self) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001138 if (!CareAboutPauseTimes()) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001139 ATRACE_BEGIN("Deflating monitors");
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001140 // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
1141 // about pauses.
1142 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001143 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001144 uint64_t start_time = NanoTime();
1145 size_t count = runtime->GetMonitorList()->DeflateMonitors();
1146 VLOG(heap) << "Deflating " << count << " monitors took "
1147 << PrettyDuration(NanoTime() - start_time);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001148 runtime->GetThreadList()->ResumeAll();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001149 ATRACE_END();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001150 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001151 TrimIndirectReferenceTables(self);
1152 TrimSpaces(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001153}
1154
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001155class TrimIndirectReferenceTableClosure : public Closure {
1156 public:
1157 explicit TrimIndirectReferenceTableClosure(Barrier* barrier) : barrier_(barrier) {
1158 }
1159 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1160 ATRACE_BEGIN("Trimming reference table");
1161 thread->GetJniEnv()->locals.Trim();
1162 ATRACE_END();
Lei Lidd9943d2015-02-02 14:24:44 +08001163 // If thread is a running mutator, then act on behalf of the trim thread.
1164 // See the code in ThreadList::RunCheckpoint.
1165 if (thread->GetState() == kRunnable) {
1166 barrier_->Pass(Thread::Current());
1167 }
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001168 }
1169
1170 private:
1171 Barrier* const barrier_;
1172};
1173
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001174void Heap::TrimIndirectReferenceTables(Thread* self) {
1175 ScopedObjectAccess soa(self);
1176 ATRACE_BEGIN(__FUNCTION__);
1177 JavaVMExt* vm = soa.Vm();
1178 // Trim globals indirect reference table.
1179 vm->TrimGlobals();
1180 // Trim locals indirect reference tables.
1181 Barrier barrier(0);
1182 TrimIndirectReferenceTableClosure closure(&barrier);
1183 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1184 size_t barrier_count = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
Lei Lidd9943d2015-02-02 14:24:44 +08001185 if (barrier_count != 0) {
1186 barrier.Increment(self, barrier_count);
1187 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001188 ATRACE_END();
1189}
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001190
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001191void Heap::TrimSpaces(Thread* self) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001192 {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001193 // Need to do this before acquiring the locks since we don't want to get suspended while
1194 // holding any locks.
1195 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001196 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1197 // trimming.
1198 MutexLock mu(self, *gc_complete_lock_);
1199 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001200 WaitForGcToCompleteLocked(kGcCauseTrim, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001201 collector_type_running_ = kCollectorTypeHeapTrim;
1202 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001203 ATRACE_BEGIN(__FUNCTION__);
1204 const uint64_t start_ns = NanoTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001205 // Trim the managed spaces.
1206 uint64_t total_alloc_space_allocated = 0;
1207 uint64_t total_alloc_space_size = 0;
1208 uint64_t managed_reclaimed = 0;
1209 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001210 if (space->IsMallocSpace()) {
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001211 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1212 if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1213 // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1214 // for a long period of time.
1215 managed_reclaimed += malloc_space->Trim();
1216 }
1217 total_alloc_space_size += malloc_space->Size();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001218 }
1219 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001220 total_alloc_space_allocated = GetBytesAllocated();
1221 if (large_object_space_ != nullptr) {
1222 total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1223 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07001224 if (bump_pointer_space_ != nullptr) {
1225 total_alloc_space_allocated -= bump_pointer_space_->Size();
1226 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001227 if (region_space_ != nullptr) {
1228 total_alloc_space_allocated -= region_space_->GetBytesAllocated();
1229 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001230 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1231 static_cast<float>(total_alloc_space_size);
1232 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001233 // We never move things in the native heap, so we can finish the GC at this point.
1234 FinishGC(self, collector::kGcTypeNone);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001235 size_t native_reclaimed = 0;
Ian Rogers872dd822014-10-30 11:19:14 -07001236
1237#ifdef HAVE_ANDROID_OS
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001238 // Only trim the native heap if we don't care about pauses.
1239 if (!CareAboutPauseTimes()) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001240#if defined(USE_DLMALLOC)
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001241 // Trim the native heap.
1242 dlmalloc_trim(0);
1243 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001244#elif defined(USE_JEMALLOC)
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001245 // Jemalloc does it's own internal trimming.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001246#else
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001247 UNIMPLEMENTED(WARNING) << "Add trimming support";
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001248#endif
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001249 }
Ian Rogers872dd822014-10-30 11:19:14 -07001250#endif // HAVE_ANDROID_OS
Mathieu Chartier590fee92013-09-13 13:46:47 -07001251 uint64_t end_ns = NanoTime();
1252 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
1253 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
1254 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
1255 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
1256 << "%.";
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001257 ATRACE_END();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001258}
1259
1260bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
1261 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
1262 // taking the lock.
1263 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -07001264 return true;
1265 }
Mathieu Chartier15d34022014-02-26 17:16:38 -08001266 return IsAligned<kObjectAlignment>(obj) && FindSpaceFromObject(obj, true) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001267}
1268
Mathieu Chartierd68ac702014-02-11 14:50:51 -08001269bool Heap::IsNonDiscontinuousSpaceHeapAddress(const mirror::Object* obj) const {
1270 return FindContinuousSpaceFromObject(obj, true) != nullptr;
1271}
1272
Mathieu Chartier15d34022014-02-26 17:16:38 -08001273bool Heap::IsValidContinuousSpaceObjectAddress(const mirror::Object* obj) const {
1274 if (obj == nullptr || !IsAligned<kObjectAlignment>(obj)) {
1275 return false;
1276 }
1277 for (const auto& space : continuous_spaces_) {
1278 if (space->HasAddress(obj)) {
1279 return true;
1280 }
1281 }
1282 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -07001283}
1284
Ian Rogersef7d42f2014-01-06 12:55:46 -08001285bool Heap::IsLiveObjectLocked(mirror::Object* obj, bool search_allocation_stack,
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001286 bool search_live_stack, bool sorted) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001287 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
1288 return false;
1289 }
1290 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001291 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001292 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08001293 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001294 return true;
1295 }
1296 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1297 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001298 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1299 // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1300 return temp_space_->Contains(obj);
Ian Rogers1d54e732013-05-02 21:10:01 -07001301 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001302 if (region_space_ != nullptr && region_space_->HasAddress(obj)) {
1303 return true;
1304 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001305 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001306 space::DiscontinuousSpace* d_space = nullptr;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001307 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001308 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001309 return true;
1310 }
1311 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001312 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001313 if (d_space != nullptr) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001314 if (d_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001315 return true;
1316 }
1317 }
1318 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001319 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001320 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1321 if (i > 0) {
1322 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -07001323 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001324 if (search_allocation_stack) {
1325 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001326 if (allocation_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001327 return true;
1328 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001329 } else if (allocation_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001330 return true;
1331 }
1332 }
1333
1334 if (search_live_stack) {
1335 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001336 if (live_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001337 return true;
1338 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001339 } else if (live_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001340 return true;
1341 }
1342 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001343 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001344 // We need to check the bitmaps again since there is a race where we mark something as live and
1345 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001346 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001347 if (c_space->GetLiveBitmap()->Test(obj)) {
1348 return true;
1349 }
1350 } else {
1351 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001352 if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj)) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001353 return true;
1354 }
1355 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001356 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001357}
1358
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001359std::string Heap::DumpSpaces() const {
1360 std::ostringstream oss;
1361 DumpSpaces(oss);
1362 return oss.str();
1363}
1364
1365void Heap::DumpSpaces(std::ostream& stream) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001366 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001367 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1368 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001369 stream << space << " " << *space << "\n";
1370 if (live_bitmap != nullptr) {
1371 stream << live_bitmap << " " << *live_bitmap << "\n";
1372 }
1373 if (mark_bitmap != nullptr) {
1374 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1375 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001376 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001377 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001378 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001379 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001380}
1381
Ian Rogersef7d42f2014-01-06 12:55:46 -08001382void Heap::VerifyObjectBody(mirror::Object* obj) {
Stephen Hines22c6a812014-07-16 11:03:43 -07001383 if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1384 return;
1385 }
1386
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001387 // Ignore early dawn of the universe verifications.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001388 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.LoadRelaxed()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001389 return;
1390 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08001391 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001392 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
Mathieu Chartier4e305412014-02-19 10:54:44 -08001393 CHECK(c != nullptr) << "Null class in object " << obj;
1394 CHECK(IsAligned<kObjectAlignment>(c)) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001395 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001396
Mathieu Chartier4e305412014-02-19 10:54:44 -08001397 if (verify_object_mode_ > kVerifyObjectModeFast) {
1398 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001399 CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001400 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001401}
1402
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001403void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001404 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001405}
1406
1407void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001408 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001409 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001410}
1411
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001412void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
Mathieu Chartier601276a2014-03-20 15:12:30 -07001413 // Use signed comparison since freed bytes can be negative when background compaction foreground
1414 // transitions occurs. This is caused by the moving objects from a bump pointer space to a
1415 // free list backed space typically increasing memory footprint due to padding and binning.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001416 DCHECK_LE(freed_bytes, static_cast<int64_t>(num_bytes_allocated_.LoadRelaxed()));
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001417 // Note: This relies on 2s complement for handling negative freed_bytes.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001418 num_bytes_allocated_.FetchAndSubSequentiallyConsistent(static_cast<ssize_t>(freed_bytes));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001419 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001420 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001421 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001422 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001423 // TODO: Do this concurrently.
1424 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1425 global_stats->freed_objects += freed_objects;
1426 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001427 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001428}
1429
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001430void Heap::RecordFreeRevoke() {
1431 // Subtract num_bytes_freed_revoke_ from num_bytes_allocated_ to cancel out the
1432 // the ahead-of-time, bulk counting of bytes allocated in rosalloc thread-local buffers.
1433 // If there's a concurrent revoke, ok to not necessarily reset num_bytes_freed_revoke_
1434 // all the way to zero exactly as the remainder will be subtracted at the next GC.
1435 size_t bytes_freed = num_bytes_freed_revoke_.LoadSequentiallyConsistent();
1436 CHECK_GE(num_bytes_freed_revoke_.FetchAndSubSequentiallyConsistent(bytes_freed),
1437 bytes_freed) << "num_bytes_freed_revoke_ underflow";
1438 CHECK_GE(num_bytes_allocated_.FetchAndSubSequentiallyConsistent(bytes_freed),
1439 bytes_freed) << "num_bytes_allocated_ underflow";
1440 GetCurrentGcIteration()->SetFreedRevoke(bytes_freed);
1441}
1442
Zuo Wangf37a88b2014-07-10 04:26:41 -07001443space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
1444 for (const auto& space : continuous_spaces_) {
1445 if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1446 if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1447 return space->AsContinuousSpace()->AsRosAllocSpace();
1448 }
1449 }
1450 }
1451 return nullptr;
1452}
1453
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001454mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001455 size_t alloc_size, size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001456 size_t* usable_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001457 size_t* bytes_tl_bulk_allocated,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001458 mirror::Class** klass) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001459 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierf4f38432014-09-03 11:21:08 -07001460 // Make sure there is no pending exception since we may need to throw an OOME.
1461 self->AssertNoPendingException();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001462 DCHECK(klass != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001463 StackHandleScope<1> hs(self);
1464 HandleWrapper<mirror::Class> h(hs.NewHandleWrapper(klass));
1465 klass = nullptr; // Invalidate for safety.
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001466 // The allocation failed. If the GC is running, block until it completes, and then retry the
1467 // allocation.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001468 collector::GcType last_gc = WaitForGcToComplete(kGcCauseForAlloc, self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001469 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001470 // If we were the default allocator but the allocator changed while we were suspended,
1471 // abort the allocation.
1472 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001473 return nullptr;
1474 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001475 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001476 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001477 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001478 if (ptr != nullptr) {
1479 return ptr;
1480 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001481 }
1482
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001483 collector::GcType tried_type = next_gc_type_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001484 const bool gc_ran =
1485 CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1486 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1487 return nullptr;
1488 }
1489 if (gc_ran) {
1490 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001491 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001492 if (ptr != nullptr) {
1493 return ptr;
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001494 }
1495 }
1496
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001497 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001498 for (collector::GcType gc_type : gc_plan_) {
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001499 if (gc_type == tried_type) {
1500 continue;
1501 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001502 // Attempt to run the collector, if we succeed, re-try the allocation.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001503 const bool plan_gc_ran =
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001504 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1505 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001506 return nullptr;
1507 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001508 if (plan_gc_ran) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001509 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001510 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001511 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001512 if (ptr != nullptr) {
1513 return ptr;
1514 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001515 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001516 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001517 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001518 // Try harder, growing the heap if necessary.
1519 mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001520 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001521 if (ptr != nullptr) {
1522 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001523 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001524 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1525 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1526 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1527 // OOME.
1528 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1529 << " allocation";
1530 // TODO: Run finalization, but this may cause more allocations to occur.
1531 // We don't need a WaitForGcToComplete here either.
1532 DCHECK(!gc_plan_.empty());
1533 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
1534 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1535 return nullptr;
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001536 }
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001537 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size,
1538 bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001539 if (ptr == nullptr) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001540 const uint64_t current_time = NanoTime();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001541 switch (allocator) {
1542 case kAllocatorTypeRosAlloc:
1543 // Fall-through.
1544 case kAllocatorTypeDlMalloc: {
1545 if (use_homogeneous_space_compaction_for_oom_ &&
1546 current_time - last_time_homogeneous_space_compaction_by_oom_ >
1547 min_interval_homogeneous_space_compaction_by_oom_) {
1548 last_time_homogeneous_space_compaction_by_oom_ = current_time;
1549 HomogeneousSpaceCompactResult result = PerformHomogeneousSpaceCompact();
1550 switch (result) {
1551 case HomogeneousSpaceCompactResult::kSuccess:
1552 // If the allocation succeeded, we delayed an oom.
1553 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001554 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001555 if (ptr != nullptr) {
1556 count_delayed_oom_++;
1557 }
1558 break;
1559 case HomogeneousSpaceCompactResult::kErrorReject:
1560 // Reject due to disabled moving GC.
1561 break;
1562 case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1563 // Throw OOM by default.
1564 break;
1565 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07001566 UNIMPLEMENTED(FATAL) << "homogeneous space compaction result: "
1567 << static_cast<size_t>(result);
1568 UNREACHABLE();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001569 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001570 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001571 // Always print that we ran homogeneous space compation since this can cause jank.
1572 VLOG(heap) << "Ran heap homogeneous space compaction, "
1573 << " requested defragmentation "
1574 << count_requested_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1575 << " performed defragmentation "
1576 << count_performed_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1577 << " ignored homogeneous space compaction "
1578 << count_ignored_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1579 << " delayed count = "
1580 << count_delayed_oom_.LoadSequentiallyConsistent();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001581 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001582 break;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001583 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001584 case kAllocatorTypeNonMoving: {
1585 // Try to transition the heap if the allocation failure was due to the space being full.
1586 if (!IsOutOfMemoryOnAllocation<false>(allocator, alloc_size)) {
1587 // If we aren't out of memory then the OOM was probably from the non moving space being
1588 // full. Attempt to disable compaction and turn the main space into a non moving space.
1589 DisableMovingGc();
1590 // If we are still a moving GC then something must have caused the transition to fail.
1591 if (IsMovingGc(collector_type_)) {
1592 MutexLock mu(self, *gc_complete_lock_);
1593 // If we couldn't disable moving GC, just throw OOME and return null.
1594 LOG(WARNING) << "Couldn't disable moving GC with disable GC count "
1595 << disable_moving_gc_count_;
1596 } else {
1597 LOG(WARNING) << "Disabled moving GC due to the non moving space being full";
1598 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001599 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001600 }
1601 }
1602 break;
1603 }
1604 default: {
1605 // Do nothing for others allocators.
1606 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001607 }
1608 }
1609 // If the allocation hasn't succeeded by this point, throw an OOM error.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001610 if (ptr == nullptr) {
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001611 ThrowOutOfMemoryError(self, alloc_size, allocator);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001612 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001613 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001614}
1615
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001616void Heap::SetTargetHeapUtilization(float target) {
1617 DCHECK_GT(target, 0.0f); // asserted in Java code
1618 DCHECK_LT(target, 1.0f);
1619 target_utilization_ = target;
1620}
1621
Ian Rogers1d54e732013-05-02 21:10:01 -07001622size_t Heap::GetObjectsAllocated() const {
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001623 Thread* self = Thread::Current();
1624 ScopedThreadStateChange tsc(self, kWaitingForGetObjectsAllocated);
1625 auto* tl = Runtime::Current()->GetThreadList();
1626 // Need SuspendAll here to prevent lock violation if RosAlloc does it during InspectAll.
1627 tl->SuspendAll(__FUNCTION__);
Ian Rogers1d54e732013-05-02 21:10:01 -07001628 size_t total = 0;
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001629 {
1630 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1631 for (space::AllocSpace* space : alloc_spaces_) {
1632 total += space->GetObjectsAllocated();
1633 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001634 }
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001635 tl->ResumeAll();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001636 return total;
1637}
1638
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001639uint64_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier4edd8472015-06-01 10:47:36 -07001640 uint64_t total = GetObjectsFreedEver();
1641 // If we are detached, we can't use GetObjectsAllocated since we can't change thread states.
1642 if (Thread::Current() != nullptr) {
1643 total += GetObjectsAllocated();
1644 }
1645 return total;
Ian Rogers1d54e732013-05-02 21:10:01 -07001646}
1647
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001648uint64_t Heap::GetBytesAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001649 return GetBytesFreedEver() + GetBytesAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001650}
1651
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001652class InstanceCounter {
1653 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001654 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001655 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001656 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001657 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001658 static void Callback(mirror::Object* obj, void* arg)
1659 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1660 InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1661 mirror::Class* instance_class = obj->GetClass();
1662 CHECK(instance_class != nullptr);
1663 for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
1664 if (instance_counter->use_is_assignable_from_) {
1665 if (instance_counter->classes_[i]->IsAssignableFrom(instance_class)) {
1666 ++instance_counter->counts_[i];
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001667 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001668 } else if (instance_class == instance_counter->classes_[i]) {
1669 ++instance_counter->counts_[i];
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001670 }
1671 }
1672 }
1673
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001674 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001675 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001676 bool use_is_assignable_from_;
1677 uint64_t* const counts_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001678 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001679};
1680
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001681void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001682 uint64_t* counts) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001683 InstanceCounter counter(classes, use_is_assignable_from, counts);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001684 VisitObjects(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001685}
1686
Elliott Hughes3b78c942013-01-15 17:35:41 -08001687class InstanceCollector {
1688 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001689 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001690 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1691 : class_(c), max_count_(max_count), instances_(instances) {
1692 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001693 static void Callback(mirror::Object* obj, void* arg)
1694 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1695 DCHECK(arg != nullptr);
1696 InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001697 if (obj->GetClass() == instance_collector->class_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001698 if (instance_collector->max_count_ == 0 ||
1699 instance_collector->instances_.size() < instance_collector->max_count_) {
1700 instance_collector->instances_.push_back(obj);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001701 }
1702 }
1703 }
1704
1705 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001706 const mirror::Class* const class_;
1707 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001708 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001709 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1710};
1711
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001712void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1713 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001714 InstanceCollector collector(c, max_count, instances);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001715 VisitObjects(&InstanceCollector::Callback, &collector);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001716}
1717
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001718class ReferringObjectsFinder {
1719 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001720 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1721 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001722 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1723 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1724 }
1725
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001726 static void Callback(mirror::Object* obj, void* arg)
1727 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1728 reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1729 }
1730
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001731 // For bitmap Visit.
1732 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1733 // annotalysis on visitors.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001734 void operator()(mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001735 o->VisitReferences<true>(*this, VoidFunctor());
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001736 }
1737
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001738 // For Object::VisitReferences.
Mathieu Chartier407f7022014-02-18 14:37:05 -08001739 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1740 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001741 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08001742 if (ref == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1743 referring_objects_.push_back(obj);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001744 }
1745 }
1746
1747 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001748 const mirror::Object* const object_;
1749 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001750 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001751 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1752};
1753
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001754void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1755 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001756 ReferringObjectsFinder finder(o, max_count, referring_objects);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001757 VisitObjects(&ReferringObjectsFinder::Callback, &finder);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001758}
1759
Ian Rogers30fab402012-01-23 15:43:46 -08001760void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001761 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1762 // last GC will not have necessarily been cleared.
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001763 CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001764}
1765
Zuo Wangf37a88b2014-07-10 04:26:41 -07001766HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
1767 Thread* self = Thread::Current();
1768 // Inc requested homogeneous space compaction.
1769 count_requested_homogeneous_space_compaction_++;
1770 // Store performed homogeneous space compaction at a new request arrival.
1771 ThreadList* tl = Runtime::Current()->GetThreadList();
1772 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1773 Locks::mutator_lock_->AssertNotHeld(self);
1774 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001775 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001776 MutexLock mu(self, *gc_complete_lock_);
1777 // Ensure there is only one GC at a time.
1778 WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
1779 // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable count
1780 // is non zero.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001781 // If the collector type changed to something which doesn't benefit from homogeneous space compaction,
Zuo Wangf37a88b2014-07-10 04:26:41 -07001782 // exit.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001783 if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
1784 !main_space_->CanMoveObjects()) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001785 return HomogeneousSpaceCompactResult::kErrorReject;
1786 }
1787 collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
1788 }
1789 if (Runtime::Current()->IsShuttingDown(self)) {
1790 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1791 // cause objects to get finalized.
1792 FinishGC(self, collector::kGcTypeNone);
1793 return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
1794 }
1795 // Suspend all threads.
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001796 tl->SuspendAll(__FUNCTION__);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001797 uint64_t start_time = NanoTime();
1798 // Launch compaction.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001799 space::MallocSpace* to_space = main_space_backup_.release();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001800 space::MallocSpace* from_space = main_space_;
1801 to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1802 const uint64_t space_size_before_compaction = from_space->Size();
Mathieu Chartierb363f662014-07-16 13:28:58 -07001803 AddSpace(to_space);
Mathieu Chartier0310da52014-12-01 13:40:48 -08001804 // Make sure that we will have enough room to copy.
1805 CHECK_GE(to_space->GetFootprintLimit(), from_space->GetFootprintLimit());
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001806 collector::GarbageCollector* collector = Compact(to_space, from_space,
1807 kGcCauseHomogeneousSpaceCompact);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001808 const uint64_t space_size_after_compaction = to_space->Size();
Mathieu Chartierb363f662014-07-16 13:28:58 -07001809 main_space_ = to_space;
1810 main_space_backup_.reset(from_space);
1811 RemoveSpace(from_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001812 SetSpaceAsDefault(main_space_); // Set as default to reset the proper dlmalloc space.
1813 // Update performed homogeneous space compaction count.
1814 count_performed_homogeneous_space_compaction_++;
1815 // Print statics log and resume all threads.
1816 uint64_t duration = NanoTime() - start_time;
Mathieu Chartier98172a62014-09-02 12:33:25 -07001817 VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
1818 << PrettySize(space_size_before_compaction) << " -> "
1819 << PrettySize(space_size_after_compaction) << " compact-ratio: "
1820 << std::fixed << static_cast<double>(space_size_after_compaction) /
1821 static_cast<double>(space_size_before_compaction);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001822 tl->ResumeAll();
1823 // Finish GC.
1824 reference_processor_.EnqueueClearedReferences(self);
1825 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001826 LogGC(kGcCauseHomogeneousSpaceCompact, collector);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001827 FinishGC(self, collector::kGcTypeFull);
1828 return HomogeneousSpaceCompactResult::kSuccess;
1829}
1830
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001831void Heap::TransitionCollector(CollectorType collector_type) {
1832 if (collector_type == collector_type_) {
1833 return;
1834 }
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001835 VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1836 << " -> " << static_cast<int>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001837 uint64_t start_time = NanoTime();
Ian Rogers3e5cf302014-05-20 16:40:37 -07001838 uint32_t before_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001839 Runtime* const runtime = Runtime::Current();
1840 ThreadList* const tl = runtime->GetThreadList();
1841 Thread* const self = Thread::Current();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001842 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1843 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001844 // Busy wait until we can GC (StartGC can fail if we have a non-zero
1845 // compacting_gc_disable_count_, this should rarely occurs).
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001846 for (;;) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001847 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001848 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001849 MutexLock mu(self, *gc_complete_lock_);
1850 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001851 WaitForGcToCompleteLocked(kGcCauseCollectorTransition, self);
Mathieu Chartiere4927f62014-08-23 13:56:03 -07001852 // Currently we only need a heap transition if we switch from a moving collector to a
1853 // non-moving one, or visa versa.
1854 const bool copying_transition = IsMovingGc(collector_type_) != IsMovingGc(collector_type);
Mathieu Chartierb38d4832014-04-10 10:56:55 -07001855 // If someone else beat us to it and changed the collector before we could, exit.
1856 // This is safe to do before the suspend all since we set the collector_type_running_ before
1857 // we exit the loop. If another thread attempts to do the heap transition before we exit,
1858 // then it would get blocked on WaitForGcToCompleteLocked.
1859 if (collector_type == collector_type_) {
1860 return;
1861 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001862 // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1863 if (!copying_transition || disable_moving_gc_count_ == 0) {
1864 // TODO: Not hard code in semi-space collector?
1865 collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1866 break;
1867 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001868 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001869 usleep(1000);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001870 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001871 if (runtime->IsShuttingDown(self)) {
Hiroshi Yamauchia6a8d142014-05-12 16:57:33 -07001872 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1873 // cause objects to get finalized.
1874 FinishGC(self, collector::kGcTypeNone);
1875 return;
1876 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001877 collector::GarbageCollector* collector = nullptr;
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001878 tl->SuspendAll(__FUNCTION__);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001879 switch (collector_type) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001880 case kCollectorTypeSS: {
Mathieu Chartier31f44142014-04-08 14:40:03 -07001881 if (!IsMovingGc(collector_type_)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001882 // Create the bump pointer space from the backup space.
1883 CHECK(main_space_backup_ != nullptr);
1884 std::unique_ptr<MemMap> mem_map(main_space_backup_->ReleaseMemMap());
Mathieu Chartier31f44142014-04-08 14:40:03 -07001885 // We are transitioning from non moving GC -> moving GC, since we copied from the bump
1886 // pointer space last transition it will be protected.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001887 CHECK(mem_map != nullptr);
1888 mem_map->Protect(PROT_READ | PROT_WRITE);
1889 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space",
1890 mem_map.release());
1891 AddSpace(bump_pointer_space_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001892 collector = Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001893 // Use the now empty main space mem map for the bump pointer temp space.
1894 mem_map.reset(main_space_->ReleaseMemMap());
Mathieu Chartier00b59152014-07-25 10:13:51 -07001895 // Unset the pointers just in case.
1896 if (dlmalloc_space_ == main_space_) {
1897 dlmalloc_space_ = nullptr;
1898 } else if (rosalloc_space_ == main_space_) {
1899 rosalloc_space_ = nullptr;
1900 }
Mathieu Chartier2796a162014-07-25 11:50:47 -07001901 // Remove the main space so that we don't try to trim it, this doens't work for debug
1902 // builds since RosAlloc attempts to read the magic number from a protected page.
1903 RemoveSpace(main_space_);
Mathieu Chartierc5a83472014-07-23 18:45:17 -07001904 RemoveRememberedSet(main_space_);
Mathieu Chartier2796a162014-07-25 11:50:47 -07001905 delete main_space_; // Delete the space since it has been removed.
Mathieu Chartierc5a83472014-07-23 18:45:17 -07001906 main_space_ = nullptr;
Mathieu Chartier2796a162014-07-25 11:50:47 -07001907 RemoveRememberedSet(main_space_backup_.get());
1908 main_space_backup_.reset(nullptr); // Deletes the space.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001909 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
1910 mem_map.release());
1911 AddSpace(temp_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07001912 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001913 break;
1914 }
1915 case kCollectorTypeMS:
1916 // Fall through.
1917 case kCollectorTypeCMS: {
Mathieu Chartier31f44142014-04-08 14:40:03 -07001918 if (IsMovingGc(collector_type_)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001919 CHECK(temp_space_ != nullptr);
1920 std::unique_ptr<MemMap> mem_map(temp_space_->ReleaseMemMap());
1921 RemoveSpace(temp_space_);
1922 temp_space_ = nullptr;
Mathieu Chartier36dab362014-07-30 14:59:56 -07001923 mem_map->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier0310da52014-12-01 13:40:48 -08001924 CreateMainMallocSpace(mem_map.get(), kDefaultInitialSize,
1925 std::min(mem_map->Size(), growth_limit_), mem_map->Size());
Mathieu Chartierb363f662014-07-16 13:28:58 -07001926 mem_map.release();
Mathieu Chartier31f44142014-04-08 14:40:03 -07001927 // Compact to the main space from the bump pointer space, don't need to swap semispaces.
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001928 AddSpace(main_space_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001929 collector = Compact(main_space_, bump_pointer_space_, kGcCauseCollectorTransition);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001930 mem_map.reset(bump_pointer_space_->ReleaseMemMap());
1931 RemoveSpace(bump_pointer_space_);
1932 bump_pointer_space_ = nullptr;
1933 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07001934 // Temporarily unprotect the backup mem map so rosalloc can write the debug magic number.
1935 if (kIsDebugBuild && kUseRosAlloc) {
1936 mem_map->Protect(PROT_READ | PROT_WRITE);
1937 }
Mathieu Chartier0310da52014-12-01 13:40:48 -08001938 main_space_backup_.reset(CreateMallocSpaceFromMemMap(
1939 mem_map.get(), kDefaultInitialSize, std::min(mem_map->Size(), growth_limit_),
1940 mem_map->Size(), name, true));
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07001941 if (kIsDebugBuild && kUseRosAlloc) {
1942 mem_map->Protect(PROT_NONE);
1943 }
Mathieu Chartierb363f662014-07-16 13:28:58 -07001944 mem_map.release();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001945 }
1946 break;
1947 }
1948 default: {
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001949 LOG(FATAL) << "Attempted to transition to invalid collector type "
1950 << static_cast<size_t>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001951 break;
1952 }
1953 }
1954 ChangeCollector(collector_type);
1955 tl->ResumeAll();
1956 // Can't call into java code with all threads suspended.
Mathieu Chartier308351a2014-06-15 12:39:02 -07001957 reference_processor_.EnqueueClearedReferences(self);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001958 uint64_t duration = NanoTime() - start_time;
Mathieu Chartierafe49982014-03-27 10:55:04 -07001959 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001960 DCHECK(collector != nullptr);
1961 LogGC(kGcCauseCollectorTransition, collector);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001962 FinishGC(self, collector::kGcTypeFull);
Ian Rogers3e5cf302014-05-20 16:40:37 -07001963 int32_t after_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001964 int32_t delta_allocated = before_allocated - after_allocated;
Mathieu Chartier19d46b42014-06-17 15:04:40 -07001965 std::string saved_str;
1966 if (delta_allocated >= 0) {
1967 saved_str = " saved at least " + PrettySize(delta_allocated);
1968 } else {
1969 saved_str = " expanded " + PrettySize(-delta_allocated);
1970 }
Mathieu Chartier98172a62014-09-02 12:33:25 -07001971 VLOG(heap) << "Heap transition to " << process_state_ << " took "
Mathieu Chartier19d46b42014-06-17 15:04:40 -07001972 << PrettyDuration(duration) << saved_str;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001973}
1974
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001975void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001976 // TODO: Only do this with all mutators suspended to avoid races.
1977 if (collector_type != collector_type_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001978 if (collector_type == kCollectorTypeMC) {
1979 // Don't allow mark compact unless support is compiled in.
1980 CHECK(kMarkCompactSupport);
1981 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001982 collector_type_ = collector_type;
1983 gc_plan_.clear();
1984 switch (collector_type_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001985 case kCollectorTypeCC: {
1986 gc_plan_.push_back(collector::kGcTypeFull);
1987 if (use_tlab_) {
1988 ChangeAllocator(kAllocatorTypeRegionTLAB);
1989 } else {
1990 ChangeAllocator(kAllocatorTypeRegion);
1991 }
1992 break;
1993 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001994 case kCollectorTypeMC: // Fall-through.
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07001995 case kCollectorTypeSS: // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001996 case kCollectorTypeGSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001997 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001998 if (use_tlab_) {
1999 ChangeAllocator(kAllocatorTypeTLAB);
2000 } else {
2001 ChangeAllocator(kAllocatorTypeBumpPointer);
2002 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002003 break;
2004 }
2005 case kCollectorTypeMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002006 gc_plan_.push_back(collector::kGcTypeSticky);
2007 gc_plan_.push_back(collector::kGcTypePartial);
2008 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002009 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002010 break;
2011 }
2012 case kCollectorTypeCMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002013 gc_plan_.push_back(collector::kGcTypeSticky);
2014 gc_plan_.push_back(collector::kGcTypePartial);
2015 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002016 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002017 break;
2018 }
2019 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07002020 UNIMPLEMENTED(FATAL);
2021 UNREACHABLE();
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002022 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002023 }
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002024 if (IsGcConcurrent()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002025 concurrent_start_bytes_ =
2026 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
2027 } else {
2028 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002029 }
2030 }
2031}
2032
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002033// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Ian Rogers6fac4472014-02-25 17:01:10 -08002034class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002035 public:
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002036 explicit ZygoteCompactingCollector(gc::Heap* heap) : SemiSpace(heap, false, "zygote collector"),
Ian Rogers6fac4472014-02-25 17:01:10 -08002037 bin_live_bitmap_(nullptr), bin_mark_bitmap_(nullptr) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002038 }
2039
2040 void BuildBins(space::ContinuousSpace* space) {
2041 bin_live_bitmap_ = space->GetLiveBitmap();
2042 bin_mark_bitmap_ = space->GetMarkBitmap();
2043 BinContext context;
2044 context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
2045 context.collector_ = this;
2046 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2047 // Note: This requires traversing the space in increasing order of object addresses.
2048 bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
2049 // Add the last bin which spans after the last object to the end of the space.
2050 AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
2051 }
2052
2053 private:
2054 struct BinContext {
2055 uintptr_t prev_; // The end of the previous object.
2056 ZygoteCompactingCollector* collector_;
2057 };
2058 // Maps from bin sizes to locations.
2059 std::multimap<size_t, uintptr_t> bins_;
2060 // Live bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002061 accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002062 // Mark bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002063 accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002064
2065 static void Callback(mirror::Object* obj, void* arg)
2066 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2067 DCHECK(arg != nullptr);
2068 BinContext* context = reinterpret_cast<BinContext*>(arg);
2069 ZygoteCompactingCollector* collector = context->collector_;
2070 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
2071 size_t bin_size = object_addr - context->prev_;
2072 // Add the bin consisting of the end of the previous object to the start of the current object.
2073 collector->AddBin(bin_size, context->prev_);
2074 context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
2075 }
2076
2077 void AddBin(size_t size, uintptr_t position) {
2078 if (size != 0) {
2079 bins_.insert(std::make_pair(size, position));
2080 }
2081 }
2082
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002083 virtual bool ShouldSweepSpace(space::ContinuousSpace* space) const {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002084 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
2085 // allocator.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002086 UNUSED(space);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002087 return false;
2088 }
2089
2090 virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
2091 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002092 size_t obj_size = obj->SizeOf();
2093 size_t alloc_size = RoundUp(obj_size, kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08002094 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002095 // Find the smallest bin which we can move obj in.
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002096 auto it = bins_.lower_bound(alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002097 if (it == bins_.end()) {
2098 // No available space in the bins, place it in the target space instead (grows the zygote
2099 // space).
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002100 size_t bytes_allocated, dummy;
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002101 forward_address = to_space_->Alloc(self_, alloc_size, &bytes_allocated, nullptr, &dummy);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002102 if (to_space_live_bitmap_ != nullptr) {
2103 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002104 } else {
2105 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
2106 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002107 }
2108 } else {
2109 size_t size = it->first;
2110 uintptr_t pos = it->second;
2111 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
2112 forward_address = reinterpret_cast<mirror::Object*>(pos);
2113 // Set the live and mark bits so that sweeping system weaks works properly.
2114 bin_live_bitmap_->Set(forward_address);
2115 bin_mark_bitmap_->Set(forward_address);
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002116 DCHECK_GE(size, alloc_size);
2117 // Add a new bin with the remaining space.
2118 AddBin(size - alloc_size, pos + alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002119 }
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002120 // Copy the object over to its new location. Don't use alloc_size to avoid valgrind error.
2121 memcpy(reinterpret_cast<void*>(forward_address), obj, obj_size);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002122 if (kUseBakerOrBrooksReadBarrier) {
2123 obj->AssertReadBarrierPointer();
2124 if (kUseBrooksReadBarrier) {
2125 DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
2126 forward_address->SetReadBarrierPointer(forward_address);
2127 }
2128 forward_address->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002129 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002130 return forward_address;
2131 }
2132};
2133
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002134void Heap::UnBindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002135 TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002136 for (const auto& space : GetContinuousSpaces()) {
2137 if (space->IsContinuousMemMapAllocSpace()) {
2138 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2139 if (alloc_space->HasBoundBitmaps()) {
2140 alloc_space->UnBindBitmaps();
2141 }
2142 }
2143 }
2144}
2145
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002146void Heap::PreZygoteFork() {
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002147 if (!HasZygoteSpace()) {
2148 // We still want to GC in case there is some unreachable non moving objects that could cause a
2149 // suboptimal bin packing when we compact the zygote space.
2150 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
2151 }
Ian Rogers81d425b2012-09-27 16:03:43 -07002152 Thread* self = Thread::Current();
2153 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002154 // Try to see if we have any Zygote spaces.
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002155 if (HasZygoteSpace()) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002156 return;
2157 }
Mathieu Chartiereb175f72014-10-31 11:49:27 -07002158 Runtime::Current()->GetInternTable()->SwapPostZygoteWithPreZygote();
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002159 Runtime::Current()->GetClassLinker()->MoveClassTableToPreZygote();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002160 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier590fee92013-09-13 13:46:47 -07002161 // Trim the pages at the end of the non moving space.
2162 non_moving_space_->Trim();
Mathieu Chartier31f44142014-04-08 14:40:03 -07002163 // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
2164 // there.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002165 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002166 const bool same_space = non_moving_space_ == main_space_;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002167 if (kCompactZygote) {
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002168 // Temporarily disable rosalloc verification because the zygote
2169 // compaction will mess up the rosalloc internal metadata.
2170 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002171 ZygoteCompactingCollector zygote_collector(this);
2172 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08002173 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002174 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
2175 non_moving_space_->Limit());
2176 // Compact the bump pointer space to a new zygote bump pointer space.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002177 bool reset_main_space = false;
2178 if (IsMovingGc(collector_type_)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002179 if (collector_type_ == kCollectorTypeCC) {
2180 zygote_collector.SetFromSpace(region_space_);
2181 } else {
2182 zygote_collector.SetFromSpace(bump_pointer_space_);
2183 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002184 } else {
2185 CHECK(main_space_ != nullptr);
Hiroshi Yamauchid04495e2015-03-11 19:09:07 -07002186 CHECK_NE(main_space_, non_moving_space_)
2187 << "Does not make sense to compact within the same space";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002188 // Copy from the main space.
2189 zygote_collector.SetFromSpace(main_space_);
2190 reset_main_space = true;
2191 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002192 zygote_collector.SetToSpace(&target_space);
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07002193 zygote_collector.SetSwapSemiSpaces(false);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002194 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002195 if (reset_main_space) {
2196 main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2197 madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
2198 MemMap* mem_map = main_space_->ReleaseMemMap();
2199 RemoveSpace(main_space_);
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002200 space::Space* old_main_space = main_space_;
Mathieu Chartier0310da52014-12-01 13:40:48 -08002201 CreateMainMallocSpace(mem_map, kDefaultInitialSize, std::min(mem_map->Size(), growth_limit_),
2202 mem_map->Size());
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002203 delete old_main_space;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002204 AddSpace(main_space_);
2205 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002206 if (collector_type_ == kCollectorTypeCC) {
2207 region_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2208 } else {
2209 bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2210 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002211 }
2212 if (temp_space_ != nullptr) {
2213 CHECK(temp_space_->IsEmpty());
2214 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002215 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2216 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002217 // Update the end and write out image.
2218 non_moving_space_->SetEnd(target_space.End());
2219 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002220 VLOG(heap) << "Create zygote space with size=" << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002221 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002222 // Change the collector to the post zygote one.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002223 ChangeCollector(foreground_collector_type_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002224 // Save the old space so that we can remove it after we complete creating the zygote space.
2225 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002226 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002227 // the remaining available space.
2228 // Remove the old space before creating the zygote space since creating the zygote space sets
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002229 // the old alloc space's bitmaps to null.
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002230 RemoveSpace(old_alloc_space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002231 if (collector::SemiSpace::kUseRememberedSet) {
2232 // Sanity bound check.
2233 FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
2234 // Remove the remembered set for the now zygote space (the old
2235 // non-moving space). Note now that we have compacted objects into
2236 // the zygote space, the data in the remembered set is no longer
2237 // needed. The zygote space will instead have a mod-union table
2238 // from this point on.
2239 RemoveRememberedSet(old_alloc_space);
2240 }
Mathieu Chartier7247af52014-11-19 10:51:42 -08002241 // Remaining space becomes the new non moving space.
2242 zygote_space_ = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName, low_memory_mode_,
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002243 &non_moving_space_);
Mathieu Chartierb363f662014-07-16 13:28:58 -07002244 CHECK(!non_moving_space_->CanMoveObjects());
2245 if (same_space) {
2246 main_space_ = non_moving_space_;
2247 SetSpaceAsDefault(main_space_);
2248 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002249 delete old_alloc_space;
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002250 CHECK(HasZygoteSpace()) << "Failed creating zygote space";
2251 AddSpace(zygote_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002252 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2253 AddSpace(non_moving_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002254 // Create the zygote space mod union table.
2255 accounting::ModUnionTable* mod_union_table =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002256 new accounting::ModUnionTableCardCache("zygote space mod-union table", this,
2257 zygote_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002258 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002259 // Set all the cards in the mod-union table since we don't know which objects contain references
2260 // to large objects.
2261 mod_union_table->SetCards();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002262 AddModUnionTable(mod_union_table);
Mathieu Chartierf6c2a272015-06-03 17:32:42 -07002263 large_object_space_->SetAllLargeObjectsAsZygoteObjects(self);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002264 if (collector::SemiSpace::kUseRememberedSet) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002265 // Add a new remembered set for the post-zygote non-moving space.
2266 accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2267 new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2268 non_moving_space_);
2269 CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2270 << "Failed to create post-zygote non-moving space remembered set";
2271 AddRememberedSet(post_zygote_non_moving_space_rem_set);
2272 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002273}
2274
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002275void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002276 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002277 allocation_stack_->Reset();
2278}
2279
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002280void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2281 accounting::ContinuousSpaceBitmap* bitmap2,
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07002282 accounting::LargeObjectBitmap* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07002283 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002284 DCHECK(bitmap1 != nullptr);
2285 DCHECK(bitmap2 != nullptr);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002286 const auto* limit = stack->End();
2287 for (auto* it = stack->Begin(); it != limit; ++it) {
2288 const mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002289 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2290 if (bitmap1->HasAddress(obj)) {
2291 bitmap1->Set(obj);
2292 } else if (bitmap2->HasAddress(obj)) {
2293 bitmap2->Set(obj);
2294 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07002295 DCHECK(large_objects != nullptr);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002296 large_objects->Set(obj);
2297 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07002298 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002299 }
2300}
2301
Mathieu Chartier590fee92013-09-13 13:46:47 -07002302void Heap::SwapSemiSpaces() {
Mathieu Chartier31f44142014-04-08 14:40:03 -07002303 CHECK(bump_pointer_space_ != nullptr);
2304 CHECK(temp_space_ != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002305 std::swap(bump_pointer_space_, temp_space_);
2306}
2307
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002308collector::GarbageCollector* Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2309 space::ContinuousMemMapAllocSpace* source_space,
2310 GcCause gc_cause) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002311 CHECK(kMovingCollector);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002312 if (target_space != source_space) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002313 // Don't swap spaces since this isn't a typical semi space collection.
2314 semi_space_collector_->SetSwapSemiSpaces(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002315 semi_space_collector_->SetFromSpace(source_space);
2316 semi_space_collector_->SetToSpace(target_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002317 semi_space_collector_->Run(gc_cause, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002318 return semi_space_collector_;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002319 } else {
2320 CHECK(target_space->IsBumpPointerSpace())
2321 << "In-place compaction is only supported for bump pointer spaces";
2322 mark_compact_collector_->SetSpace(target_space->AsBumpPointerSpace());
2323 mark_compact_collector_->Run(kGcCauseCollectorTransition, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002324 return mark_compact_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002325 }
2326}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002327
Ian Rogers1d54e732013-05-02 21:10:01 -07002328collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
2329 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002330 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002331 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002332 // If the heap can't run the GC, silently fail and return that no GC was run.
2333 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002334 case collector::kGcTypePartial: {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002335 if (!HasZygoteSpace()) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002336 return collector::kGcTypeNone;
2337 }
2338 break;
2339 }
2340 default: {
2341 // Other GC types don't have any special cases which makes them not runnable. The main case
2342 // here is full GC.
2343 }
2344 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002345 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07002346 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002347 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier50c138f2015-01-07 16:00:03 -08002348 // If we are throwing a stack overflow error we probably don't have enough remaining stack
2349 // space to run the GC.
2350 return collector::kGcTypeNone;
Ian Rogers120f1c72012-09-28 17:17:10 -07002351 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002352 bool compacting_gc;
2353 {
2354 gc_complete_lock_->AssertNotHeld(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002355 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002356 MutexLock mu(self, *gc_complete_lock_);
2357 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002358 WaitForGcToCompleteLocked(gc_cause, self);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002359 compacting_gc = IsMovingGc(collector_type_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002360 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2361 if (compacting_gc && disable_moving_gc_count_ != 0) {
2362 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2363 return collector::kGcTypeNone;
2364 }
2365 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002366 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002367 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2368 ++runtime->GetStats()->gc_for_alloc_count;
2369 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002370 }
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002371 const uint64_t bytes_allocated_before_gc = GetBytesAllocated();
2372 // Approximate heap size.
2373 ATRACE_INT("Heap size (KB)", bytes_allocated_before_gc / KB);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002374
Ian Rogers1d54e732013-05-02 21:10:01 -07002375 DCHECK_LT(gc_type, collector::kGcTypeMax);
2376 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002377
Mathieu Chartier590fee92013-09-13 13:46:47 -07002378 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08002379 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002380 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002381 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002382 current_allocator_ == kAllocatorTypeTLAB ||
2383 current_allocator_ == kAllocatorTypeRegion ||
2384 current_allocator_ == kAllocatorTypeRegionTLAB);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002385 switch (collector_type_) {
2386 case kCollectorTypeSS:
2387 // Fall-through.
2388 case kCollectorTypeGSS:
2389 semi_space_collector_->SetFromSpace(bump_pointer_space_);
2390 semi_space_collector_->SetToSpace(temp_space_);
2391 semi_space_collector_->SetSwapSemiSpaces(true);
2392 collector = semi_space_collector_;
2393 break;
2394 case kCollectorTypeCC:
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002395 concurrent_copying_collector_->SetRegionSpace(region_space_);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002396 collector = concurrent_copying_collector_;
2397 break;
2398 case kCollectorTypeMC:
2399 mark_compact_collector_->SetSpace(bump_pointer_space_);
2400 collector = mark_compact_collector_;
2401 break;
2402 default:
2403 LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002404 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002405 if (collector != mark_compact_collector_ && collector != concurrent_copying_collector_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002406 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2407 CHECK(temp_space_->IsEmpty());
2408 }
2409 gc_type = collector::kGcTypeFull; // TODO: Not hard code this in.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002410 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2411 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002412 collector = FindCollectorByGcType(gc_type);
Mathieu Chartier50482232013-11-21 11:48:14 -08002413 } else {
2414 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002415 }
Mathieu Chartier08cef222014-10-22 17:18:34 -07002416 if (IsGcConcurrent()) {
2417 // Disable concurrent GC check so that we don't have spammy JNI requests.
2418 // This gets recalculated in GrowForUtilization. It is important that it is disabled /
2419 // calculated in the same thread so that there aren't any races that can cause it to become
2420 // permanantly disabled. b/17942071
2421 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2422 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002423 CHECK(collector != nullptr)
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002424 << "Could not find garbage collector with collector_type="
2425 << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002426 collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002427 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2428 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08002429 RequestTrim(self);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002430 // Enqueue cleared references.
Mathieu Chartier308351a2014-06-15 12:39:02 -07002431 reference_processor_.EnqueueClearedReferences(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002432 // Grow the heap so that we know when to perform the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002433 GrowForUtilization(collector, bytes_allocated_before_gc);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002434 LogGC(gc_cause, collector);
2435 FinishGC(self, gc_type);
2436 // Inform DDMS that a GC completed.
2437 Dbg::GcDidFinish();
2438 return gc_type;
2439}
2440
2441void Heap::LogGC(GcCause gc_cause, collector::GarbageCollector* collector) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002442 const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2443 const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002444 // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002445 // (mutator time blocked >= long_pause_log_threshold_).
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002446 bool log_gc = gc_cause == kGcCauseExplicit;
2447 if (!log_gc && CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002448 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002449 log_gc = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002450 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002451 for (uint64_t pause : pause_times) {
2452 log_gc = log_gc || pause >= long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002453 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002454 }
2455 if (log_gc) {
2456 const size_t percent_free = GetPercentFree();
2457 const size_t current_heap_size = GetBytesAllocated();
2458 const size_t total_memory = GetTotalMemory();
2459 std::ostringstream pause_string;
2460 for (size_t i = 0; i < pause_times.size(); ++i) {
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002461 pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2462 << ((i != pause_times.size() - 1) ? "," : "");
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002463 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002464 LOG(INFO) << gc_cause << " " << collector->GetName()
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002465 << " GC freed " << current_gc_iteration_.GetFreedObjects() << "("
2466 << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2467 << current_gc_iteration_.GetFreedLargeObjects() << "("
2468 << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002469 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2470 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2471 << " total " << PrettyDuration((duration / 1000) * 1000);
Ian Rogersc7dd2952014-10-21 23:31:19 -07002472 VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002473 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002474}
Mathieu Chartiera6399032012-06-11 18:49:50 -07002475
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002476void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2477 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002478 collector_type_running_ = kCollectorTypeNone;
2479 if (gc_type != collector::kGcTypeNone) {
2480 last_gc_type_ = gc_type;
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002481
2482 // Update stats.
2483 ++gc_count_last_window_;
2484 if (running_collection_is_blocking_) {
2485 // If the currently running collection was a blocking one,
2486 // increment the counters and reset the flag.
2487 ++blocking_gc_count_;
2488 blocking_gc_time_ += GetCurrentGcIteration()->GetDurationNs();
2489 ++blocking_gc_count_last_window_;
2490 }
2491 // Update the gc count rate histograms if due.
2492 UpdateGcCountRateHistograms();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002493 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002494 // Reset.
2495 running_collection_is_blocking_ = false;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002496 // Wake anyone who may have been waiting for the GC to complete.
2497 gc_complete_cond_->Broadcast(self);
2498}
2499
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002500void Heap::UpdateGcCountRateHistograms() {
2501 // Invariant: if the time since the last update includes more than
2502 // one windows, all the GC runs (if > 0) must have happened in first
2503 // window because otherwise the update must have already taken place
2504 // at an earlier GC run. So, we report the non-first windows with
2505 // zero counts to the histograms.
2506 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2507 uint64_t now = NanoTime();
2508 DCHECK_GE(now, last_update_time_gc_count_rate_histograms_);
2509 uint64_t time_since_last_update = now - last_update_time_gc_count_rate_histograms_;
2510 uint64_t num_of_windows = time_since_last_update / kGcCountRateHistogramWindowDuration;
2511 if (time_since_last_update >= kGcCountRateHistogramWindowDuration) {
2512 // Record the first window.
2513 gc_count_rate_histogram_.AddValue(gc_count_last_window_ - 1); // Exclude the current run.
2514 blocking_gc_count_rate_histogram_.AddValue(running_collection_is_blocking_ ?
2515 blocking_gc_count_last_window_ - 1 : blocking_gc_count_last_window_);
2516 // Record the other windows (with zero counts).
2517 for (uint64_t i = 0; i < num_of_windows - 1; ++i) {
2518 gc_count_rate_histogram_.AddValue(0);
2519 blocking_gc_count_rate_histogram_.AddValue(0);
2520 }
2521 // Update the last update time and reset the counters.
2522 last_update_time_gc_count_rate_histograms_ =
2523 (now / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
2524 gc_count_last_window_ = 1; // Include the current run.
2525 blocking_gc_count_last_window_ = running_collection_is_blocking_ ? 1 : 0;
2526 }
2527 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2528}
2529
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002530class RootMatchesObjectVisitor : public SingleRootVisitor {
2531 public:
2532 explicit RootMatchesObjectVisitor(const mirror::Object* obj) : obj_(obj) { }
2533
2534 void VisitRoot(mirror::Object* root, const RootInfo& info)
2535 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2536 if (root == obj_) {
2537 LOG(INFO) << "Object " << obj_ << " is a root " << info.ToString();
2538 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002539 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002540
2541 private:
2542 const mirror::Object* const obj_;
2543};
2544
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002545
2546class ScanVisitor {
2547 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07002548 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002549 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002550 }
2551};
2552
Ian Rogers1d54e732013-05-02 21:10:01 -07002553// Verify a reference from an object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002554class VerifyReferenceVisitor : public SingleRootVisitor {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002555 public:
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002556 explicit VerifyReferenceVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
Ian Rogers1d54e732013-05-02 21:10:01 -07002557 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002558 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07002559
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002560 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002561 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002562 }
2563
Mathieu Chartier407f7022014-02-18 14:37:05 -08002564 void operator()(mirror::Class* klass, mirror::Reference* ref) const
2565 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002566 UNUSED(klass);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002567 if (verify_referent_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002568 VerifyReference(ref, ref->GetReferent(), mirror::Reference::ReferentOffset());
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002569 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08002570 }
2571
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07002572 void operator()(mirror::Object* obj, MemberOffset offset, bool /*is_static*/) const
Mathieu Chartier407f7022014-02-18 14:37:05 -08002573 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002574 VerifyReference(obj, obj->GetFieldObject<mirror::Object>(offset), offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08002575 }
2576
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002577 bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
2578 return heap_->IsLiveObjectLocked(obj, true, false, true);
2579 }
2580
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002581 void VisitRoot(mirror::Object* root, const RootInfo& root_info) OVERRIDE
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002582 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002583 if (root == nullptr) {
2584 LOG(ERROR) << "Root is null with info " << root_info.GetType();
2585 } else if (!VerifyReference(nullptr, root, MemberOffset(0))) {
2586 LOG(ERROR) << "Root " << root << " is dead with type " << PrettyTypeOf(root)
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002587 << " thread_id= " << root_info.GetThreadId() << " root_type= " << root_info.GetType();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002588 }
2589 }
2590
2591 private:
Mathieu Chartier407f7022014-02-18 14:37:05 -08002592 // TODO: Fix the no thread safety analysis.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002593 // Returns false on failure.
2594 bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002595 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002596 if (ref == nullptr || IsLive(ref)) {
2597 // Verify that the reference is live.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002598 return true;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002599 }
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002600 if (fail_count_->FetchAndAddSequentiallyConsistent(1) == 0) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002601 // Print message on only on first failure to prevent spam.
2602 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002603 }
2604 if (obj != nullptr) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002605 // Only do this part for non roots.
Ian Rogers1d54e732013-05-02 21:10:01 -07002606 accounting::CardTable* card_table = heap_->GetCardTable();
2607 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2608 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Ian Rogers13735952014-10-08 12:43:28 -07002609 uint8_t* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002610 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2611 << offset << "\n card value = " << static_cast<int>(*card_addr);
2612 if (heap_->IsValidObjectAddress(obj->GetClass())) {
2613 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
2614 } else {
2615 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002616 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002617
Mathieu Chartierb363f662014-07-16 13:28:58 -07002618 // Attempt to find the class inside of the recently freed objects.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002619 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2620 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2621 space::MallocSpace* space = ref_space->AsMallocSpace();
2622 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2623 if (ref_class != nullptr) {
2624 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
2625 << PrettyClass(ref_class);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002626 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002627 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002628 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002629 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002630
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002631 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2632 ref->GetClass()->IsClass()) {
2633 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
2634 } else {
2635 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2636 << ") is not a valid heap address";
2637 }
2638
Ian Rogers13735952014-10-08 12:43:28 -07002639 card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002640 void* cover_begin = card_table->AddrFromCard(card_addr);
2641 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2642 accounting::CardTable::kCardSize);
2643 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2644 << "-" << cover_end;
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002645 accounting::ContinuousSpaceBitmap* bitmap =
2646 heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002647
2648 if (bitmap == nullptr) {
2649 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08002650 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002651 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002652 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002653 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07002654 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002655 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002656 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2657 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002658 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002659 LOG(ERROR) << "Object " << obj << " found in allocation stack";
2660 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002661 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002662 LOG(ERROR) << "Object " << obj << " found in live stack";
2663 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002664 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2665 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2666 }
2667 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2668 LOG(ERROR) << "Ref " << ref << " found in live stack";
2669 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002670 // Attempt to see if the card table missed the reference.
2671 ScanVisitor scan_visitor;
Ian Rogers13735952014-10-08 12:43:28 -07002672 uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
Lei Li727b2942015-01-15 11:26:34 +08002673 card_table->Scan<false>(bitmap, byte_cover_begin,
2674 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002675 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002676
2677 // Search to see if any of the roots reference our object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002678 RootMatchesObjectVisitor visitor1(obj);
2679 Runtime::Current()->VisitRoots(&visitor1);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002680 // Search to see if any of the roots reference our reference.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002681 RootMatchesObjectVisitor visitor2(ref);
2682 Runtime::Current()->VisitRoots(&visitor2);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002683 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002684 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002685 }
2686
Ian Rogers1d54e732013-05-02 21:10:01 -07002687 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002688 Atomic<size_t>* const fail_count_;
2689 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002690};
2691
Ian Rogers1d54e732013-05-02 21:10:01 -07002692// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002693class VerifyObjectVisitor {
2694 public:
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002695 explicit VerifyObjectVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
2696 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002697 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002698
Mathieu Chartier590fee92013-09-13 13:46:47 -07002699 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07002700 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002701 // Note: we are verifying the references in obj but not obj itself, this is because obj must
2702 // be live or else how did we find it in the live bitmap?
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002703 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002704 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002705 obj->VisitReferences<true>(visitor, visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002706 }
2707
Mathieu Chartier590fee92013-09-13 13:46:47 -07002708 static void VisitCallback(mirror::Object* obj, void* arg)
2709 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2710 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
2711 visitor->operator()(obj);
2712 }
2713
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002714 void VerifyRoots() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
2715 LOCKS_EXCLUDED(Locks::heap_bitmap_lock_) {
2716 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2717 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
2718 Runtime::Current()->VisitRoots(&visitor);
2719 }
2720
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002721 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002722 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002723 }
2724
2725 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002726 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002727 Atomic<size_t>* const fail_count_;
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002728 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002729};
2730
Mathieu Chartierc1790162014-05-23 10:54:50 -07002731void Heap::PushOnAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2732 // Slow path, the allocation stack push back must have already failed.
2733 DCHECK(!allocation_stack_->AtomicPushBack(*obj));
2734 do {
2735 // TODO: Add handle VerifyObject.
2736 StackHandleScope<1> hs(self);
2737 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2738 // Push our object into the reserve region of the allocaiton stack. This is only required due
2739 // to heap verification requiring that roots are live (either in the live bitmap or in the
2740 // allocation stack).
2741 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2742 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2743 } while (!allocation_stack_->AtomicPushBack(*obj));
2744}
2745
2746void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2747 // Slow path, the allocation stack push back must have already failed.
2748 DCHECK(!self->PushOnThreadLocalAllocationStack(*obj));
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002749 StackReference<mirror::Object>* start_address;
2750 StackReference<mirror::Object>* end_address;
Mathieu Chartierc1790162014-05-23 10:54:50 -07002751 while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
2752 &end_address)) {
2753 // TODO: Add handle VerifyObject.
2754 StackHandleScope<1> hs(self);
2755 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2756 // Push our object into the reserve region of the allocaiton stack. This is only required due
2757 // to heap verification requiring that roots are live (either in the live bitmap or in the
2758 // allocation stack).
2759 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2760 // Push into the reserve allocation stack.
2761 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2762 }
2763 self->SetThreadLocalAllocationStack(start_address, end_address);
2764 // Retry on the new thread-local allocation stack.
2765 CHECK(self->PushOnThreadLocalAllocationStack(*obj)); // Must succeed.
2766}
2767
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002768// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002769size_t Heap::VerifyHeapReferences(bool verify_referents) {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002770 Thread* self = Thread::Current();
2771 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002772 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07002773 allocation_stack_->Sort();
2774 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002775 // Since we sorted the allocation stack content, need to revoke all
2776 // thread-local allocation stacks.
2777 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002778 Atomic<size_t> fail_count_(0);
2779 VerifyObjectVisitor visitor(this, &fail_count_, verify_referents);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002780 // Verify objects in the allocation stack since these will be objects which were:
2781 // 1. Allocated prior to the GC (pre GC verification).
2782 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002783 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002784 // pointing to dead objects if they are not reachable.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002785 VisitObjectsPaused(VerifyObjectVisitor::VisitCallback, &visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002786 // Verify the roots:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002787 visitor.VerifyRoots();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002788 if (visitor.GetFailureCount() > 0) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002789 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002790 for (const auto& table_pair : mod_union_tables_) {
2791 accounting::ModUnionTable* mod_union_table = table_pair.second;
2792 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
2793 }
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002794 // Dump remembered sets.
2795 for (const auto& table_pair : remembered_sets_) {
2796 accounting::RememberedSet* remembered_set = table_pair.second;
2797 remembered_set->Dump(LOG(ERROR) << remembered_set->GetName() << ": ");
2798 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07002799 DumpSpaces(LOG(ERROR));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002800 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002801 return visitor.GetFailureCount();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002802}
2803
2804class VerifyReferenceCardVisitor {
2805 public:
2806 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
2807 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
2808 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07002809 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002810 }
2811
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002812 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
2813 // annotalysis on visitors.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002814 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
2815 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07002816 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002817 // Filter out class references since changing an object's class does not mark the card as dirty.
2818 // Also handles large objects, since the only reference they hold is a class reference.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002819 if (ref != nullptr && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002820 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002821 // If the object is not dirty and it is referencing something in the live stack other than
2822 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002823 if (!card_table->AddrIsInCardTable(obj)) {
2824 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
2825 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002826 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002827 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002828 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
2829 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002830 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier407f7022014-02-18 14:37:05 -08002831 if (live_stack->ContainsSorted(ref)) {
2832 if (live_stack->ContainsSorted(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002833 LOG(ERROR) << "Object " << obj << " found in live stack";
2834 }
2835 if (heap_->GetLiveBitmap()->Test(obj)) {
2836 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2837 }
2838 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
2839 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
2840
2841 // Print which field of the object is dead.
2842 if (!obj->IsObjectArray()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002843 mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002844 CHECK(klass != nullptr);
2845 auto* fields = is_static ? klass->GetSFields() : klass->GetIFields();
2846 auto num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
2847 CHECK_EQ(fields == nullptr, num_fields == 0u);
2848 for (size_t i = 0; i < num_fields; ++i) {
2849 ArtField* cur = &fields[i];
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002850 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
2851 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
2852 << PrettyField(cur);
2853 break;
2854 }
2855 }
2856 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002857 mirror::ObjectArray<mirror::Object>* object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002858 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002859 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
2860 if (object_array->Get(i) == ref) {
2861 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
2862 }
2863 }
2864 }
2865
2866 *failed_ = true;
2867 }
2868 }
2869 }
2870 }
2871
2872 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002873 Heap* const heap_;
2874 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002875};
2876
2877class VerifyLiveStackReferences {
2878 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002879 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002880 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002881 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002882
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002883 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002884 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2885 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07002886 obj->VisitReferences<true>(visitor, VoidFunctor());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002887 }
2888
2889 bool Failed() const {
2890 return failed_;
2891 }
2892
2893 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002894 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002895 bool failed_;
2896};
2897
2898bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002899 Thread* self = Thread::Current();
2900 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002901 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002902 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002903 // Since we sorted the allocation stack content, need to revoke all
2904 // thread-local allocation stacks.
2905 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002906 VerifyLiveStackReferences visitor(this);
2907 GetLiveBitmap()->Visit(visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002908 // We can verify objects in the live stack since none of these should reference dead objects.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002909 for (auto* it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
2910 if (!kUseThreadLocalAllocationStack || it->AsMirrorPtr() != nullptr) {
2911 visitor(it->AsMirrorPtr());
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002912 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002913 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07002914 return !visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002915}
2916
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002917void Heap::SwapStacks(Thread* self) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002918 UNUSED(self);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002919 if (kUseThreadLocalAllocationStack) {
2920 live_stack_->AssertAllZero();
2921 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002922 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002923}
2924
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002925void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002926 // This must be called only during the pause.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002927 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002928 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2929 MutexLock mu2(self, *Locks::thread_list_lock_);
2930 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
2931 for (Thread* t : thread_list) {
2932 t->RevokeThreadLocalAllocationStack();
2933 }
2934}
2935
Ian Rogers68d8b422014-07-17 11:09:10 -07002936void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
2937 if (kIsDebugBuild) {
2938 if (rosalloc_space_ != nullptr) {
2939 rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
2940 }
2941 if (bump_pointer_space_ != nullptr) {
2942 bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
2943 }
2944 }
2945}
2946
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002947void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
2948 if (kIsDebugBuild) {
2949 if (bump_pointer_space_ != nullptr) {
2950 bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
2951 }
2952 }
2953}
2954
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002955accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
2956 auto it = mod_union_tables_.find(space);
2957 if (it == mod_union_tables_.end()) {
2958 return nullptr;
2959 }
2960 return it->second;
2961}
2962
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002963accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
2964 auto it = remembered_sets_.find(space);
2965 if (it == remembered_sets_.end()) {
2966 return nullptr;
2967 }
2968 return it->second;
2969}
2970
Lei Li4add3b42015-01-15 11:55:26 +08002971void Heap::ProcessCards(TimingLogger* timings, bool use_rem_sets, bool process_alloc_space_cards,
2972 bool clear_alloc_space_cards) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002973 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07002974 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07002975 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002976 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002977 accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002978 if (table != nullptr) {
2979 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
2980 "ImageModUnionClearCards";
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002981 TimingLogger::ScopedTiming t2(name, timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002982 table->ClearCards();
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002983 } else if (use_rem_sets && rem_set != nullptr) {
2984 DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
2985 << static_cast<int>(collector_type_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002986 TimingLogger::ScopedTiming t2("AllocSpaceRemSetClearCards", timings);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002987 rem_set->ClearCards();
Lei Li4add3b42015-01-15 11:55:26 +08002988 } else if (process_alloc_space_cards) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002989 TimingLogger::ScopedTiming t2("AllocSpaceClearCards", timings);
Lei Li4add3b42015-01-15 11:55:26 +08002990 if (clear_alloc_space_cards) {
2991 card_table_->ClearCardRange(space->Begin(), space->End());
2992 } else {
2993 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these
2994 // cards were dirty before the GC started.
2995 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
2996 // -> clean(cleaning thread).
2997 // The races are we either end up with: Aged card, unaged card. Since we have the
2998 // checkpoint roots and then we scan / update mod union tables after. We will always
2999 // scan either card. If we end up with the non aged card, we scan it it in the pause.
3000 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
3001 VoidFunctor());
3002 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003003 }
3004 }
3005}
3006
Mathieu Chartier407f7022014-02-18 14:37:05 -08003007static void IdentityMarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>*, void*) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003008}
3009
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003010void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
3011 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003012 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003013 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003014 if (verify_pre_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003015 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003016 size_t failures = VerifyHeapReferences();
3017 if (failures > 0) {
3018 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3019 << " failures";
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003020 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003021 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003022 // Check that all objects which reference things in the live stack are on dirty cards.
3023 if (verify_missing_card_marks_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003024 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyMissingCardMarks", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003025 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
3026 SwapStacks(self);
3027 // Sort the live stack so that we can quickly binary search it later.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003028 CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
3029 << " missing card mark verification failed\n" << DumpSpaces();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003030 SwapStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003031 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003032 if (verify_mod_union_table_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003033 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyModUnionTables", timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003034 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003035 for (const auto& table_pair : mod_union_tables_) {
3036 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier407f7022014-02-18 14:37:05 -08003037 mod_union_table->UpdateAndMarkReferences(IdentityMarkHeapReferenceCallback, nullptr);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003038 mod_union_table->Verify();
3039 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003040 }
3041}
3042
3043void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier0651d412014-04-29 14:37:57 -07003044 if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003045 collector::GarbageCollector::ScopedPause pause(gc);
3046 PreGcVerificationPaused(gc);
3047 }
3048}
3049
3050void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003051 UNUSED(gc);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003052 // TODO: Add a new runtime option for this?
3053 if (verify_pre_gc_rosalloc_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003054 RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003055 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003056}
3057
Ian Rogers1d54e732013-05-02 21:10:01 -07003058void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003059 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003060 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003061 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003062 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
3063 // reachable objects.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003064 if (verify_pre_sweeping_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003065 TimingLogger::ScopedTiming t2("(Paused)PostSweepingVerifyHeapReferences", timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003066 CHECK_NE(self->GetState(), kRunnable);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003067 {
3068 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3069 // Swapping bound bitmaps does nothing.
3070 gc->SwapBitmaps();
3071 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07003072 // Pass in false since concurrent reference processing can mean that the reference referents
3073 // may point to dead objects at the point which PreSweepingGcVerification is called.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003074 size_t failures = VerifyHeapReferences(false);
3075 if (failures > 0) {
3076 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
3077 << " failures";
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003078 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003079 {
3080 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3081 gc->SwapBitmaps();
3082 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003083 }
3084 if (verify_pre_sweeping_rosalloc_) {
3085 RosAllocVerification(timings, "PreSweepingRosAllocVerification");
3086 }
3087}
3088
3089void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
3090 // Only pause if we have to do some verification.
3091 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003092 TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003093 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003094 if (verify_system_weaks_) {
3095 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3096 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
3097 mark_sweep->VerifySystemWeaks();
3098 }
3099 if (verify_post_gc_rosalloc_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003100 RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003101 }
3102 if (verify_post_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003103 TimingLogger::ScopedTiming t2("(Paused)PostGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003104 size_t failures = VerifyHeapReferences();
3105 if (failures > 0) {
3106 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3107 << " failures";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003108 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003109 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003110}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003111
Ian Rogers1d54e732013-05-02 21:10:01 -07003112void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003113 if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
3114 collector::GarbageCollector::ScopedPause pause(gc);
Mathieu Chartierd35326f2014-08-18 15:02:59 -07003115 PostGcVerificationPaused(gc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003116 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003117}
3118
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003119void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003120 TimingLogger::ScopedTiming t(name, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003121 for (const auto& space : continuous_spaces_) {
3122 if (space->IsRosAllocSpace()) {
3123 VLOG(heap) << name << " : " << space->GetName();
3124 space->AsRosAllocSpace()->Verify();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08003125 }
3126 }
3127}
3128
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003129collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08003130 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003131 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003132 return WaitForGcToCompleteLocked(cause, self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003133}
3134
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003135collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003136 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003137 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08003138 while (collector_type_running_ != kCollectorTypeNone) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003139 if (self != task_processor_->GetRunningThread()) {
3140 // The current thread is about to wait for a currently running
3141 // collection to finish. If the waiting thread is not the heap
3142 // task daemon thread, the currently running collection is
3143 // considered as a blocking GC.
3144 running_collection_is_blocking_ = true;
3145 VLOG(gc) << "Waiting for a blocking GC " << cause;
3146 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003147 ATRACE_BEGIN("GC: Wait For Completion");
3148 // We must wait, change thread state then sleep on gc_complete_cond_;
3149 gc_complete_cond_->Wait(self);
3150 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07003151 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003152 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003153 uint64_t wait_time = NanoTime() - wait_start;
3154 total_wait_time_ += wait_time;
3155 if (wait_time > long_pause_log_threshold_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003156 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time)
3157 << " for cause " << cause;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003158 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003159 if (self != task_processor_->GetRunningThread()) {
3160 // The current thread is about to run a collection. If the thread
3161 // is not the heap task daemon thread, it's considered as a
3162 // blocking GC (i.e., blocking itself).
3163 running_collection_is_blocking_ = true;
3164 VLOG(gc) << "Starting a blocking GC " << cause;
3165 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07003166 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07003167}
3168
Elliott Hughesc967f782012-04-16 10:23:15 -07003169void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003170 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003171 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07003172 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07003173}
3174
3175size_t Heap::GetPercentFree() {
Mathieu Chartierd30e1d62014-06-09 13:25:22 -07003176 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / max_allowed_footprint_);
Elliott Hughesc967f782012-04-16 10:23:15 -07003177}
3178
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003179void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003180 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003181 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003182 << PrettySize(GetMaxMemory());
3183 max_allowed_footprint = GetMaxMemory();
3184 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07003185 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07003186}
3187
Mathieu Chartier590fee92013-09-13 13:46:47 -07003188bool Heap::IsMovableObject(const mirror::Object* obj) const {
3189 if (kMovingCollector) {
Mathieu Chartier31f44142014-04-08 14:40:03 -07003190 space::Space* space = FindContinuousSpaceFromObject(obj, true);
3191 if (space != nullptr) {
3192 // TODO: Check large object?
3193 return space->CanMoveObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003194 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003195 }
3196 return false;
3197}
3198
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003199void Heap::UpdateMaxNativeFootprint() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07003200 size_t native_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003201 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
3202 size_t target_size = native_size / GetTargetHeapUtilization();
3203 if (target_size > native_size + max_free_) {
3204 target_size = native_size + max_free_;
3205 } else if (target_size < native_size + min_free_) {
3206 target_size = native_size + min_free_;
3207 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003208 native_footprint_gc_watermark_ = std::min(growth_limit_, target_size);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003209}
3210
Mathieu Chartierafe49982014-03-27 10:55:04 -07003211collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
3212 for (const auto& collector : garbage_collectors_) {
3213 if (collector->GetCollectorType() == collector_type_ &&
3214 collector->GetGcType() == gc_type) {
3215 return collector;
3216 }
3217 }
3218 return nullptr;
3219}
3220
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003221double Heap::HeapGrowthMultiplier() const {
3222 // If we don't care about pause times we are background, so return 1.0.
3223 if (!CareAboutPauseTimes() || IsLowMemoryMode()) {
3224 return 1.0;
3225 }
3226 return foreground_heap_growth_multiplier_;
3227}
3228
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003229void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran,
3230 uint64_t bytes_allocated_before_gc) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003231 // We know what our utilization is at this moment.
3232 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003233 const uint64_t bytes_allocated = GetBytesAllocated();
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003234 uint64_t target_size;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003235 collector::GcType gc_type = collector_ran->GetGcType();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003236 const double multiplier = HeapGrowthMultiplier(); // Use the multiplier to grow more for
3237 // foreground.
3238 const uint64_t adjusted_min_free = static_cast<uint64_t>(min_free_ * multiplier);
3239 const uint64_t adjusted_max_free = static_cast<uint64_t>(max_free_ * multiplier);
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003240 if (gc_type != collector::kGcTypeSticky) {
3241 // Grow the heap for non sticky GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003242 ssize_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003243 CHECK_GE(delta, 0);
3244 target_size = bytes_allocated + delta * multiplier;
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003245 target_size = std::min(target_size, bytes_allocated + adjusted_max_free);
3246 target_size = std::max(target_size, bytes_allocated + adjusted_min_free);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003247 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003248 next_gc_type_ = collector::kGcTypeSticky;
3249 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003250 collector::GcType non_sticky_gc_type =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07003251 HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003252 // Find what the next non sticky collector will be.
3253 collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
3254 // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
3255 // do another sticky collection next.
3256 // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
3257 // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
3258 // if the sticky GC throughput always remained >= the full/partial throughput.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003259 if (current_gc_iteration_.GetEstimatedThroughput() * kStickyGcThroughputAdjustment >=
Mathieu Chartierafe49982014-03-27 10:55:04 -07003260 non_sticky_collector->GetEstimatedMeanThroughput() &&
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003261 non_sticky_collector->NumberOfIterations() > 0 &&
Mathieu Chartierafe49982014-03-27 10:55:04 -07003262 bytes_allocated <= max_allowed_footprint_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003263 next_gc_type_ = collector::kGcTypeSticky;
3264 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003265 next_gc_type_ = non_sticky_gc_type;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003266 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003267 // If we have freed enough memory, shrink the heap back down.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003268 if (bytes_allocated + adjusted_max_free < max_allowed_footprint_) {
3269 target_size = bytes_allocated + adjusted_max_free;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003270 } else {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003271 target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003272 }
3273 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003274 if (!ignore_max_footprint_) {
3275 SetIdealFootprint(target_size);
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003276 if (IsGcConcurrent()) {
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003277 const uint64_t freed_bytes = current_gc_iteration_.GetFreedBytes() +
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003278 current_gc_iteration_.GetFreedLargeObjectBytes() +
3279 current_gc_iteration_.GetFreedRevokeBytes();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003280 // Bytes allocated will shrink by freed_bytes after the GC runs, so if we want to figure out
3281 // how many bytes were allocated during the GC we need to add freed_bytes back on.
3282 CHECK_GE(bytes_allocated + freed_bytes, bytes_allocated_before_gc);
3283 const uint64_t bytes_allocated_during_gc = bytes_allocated + freed_bytes -
3284 bytes_allocated_before_gc;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003285 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003286 // Calculate the estimated GC duration.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003287 const double gc_duration_seconds = NsToMs(current_gc_iteration_.GetDurationNs()) / 1000.0;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003288 // Estimate how many remaining bytes we will have when we need to start the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003289 size_t remaining_bytes = bytes_allocated_during_gc * gc_duration_seconds;
Mathieu Chartier74762802014-01-24 10:21:35 -08003290 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003291 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
3292 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
3293 // A never going to happen situation that from the estimated allocation rate we will exceed
3294 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08003295 // another GC nearly straight away.
3296 remaining_bytes = kMinConcurrentRemainingBytes;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003297 }
Mathieu Chartier74762802014-01-24 10:21:35 -08003298 DCHECK_LE(remaining_bytes, max_allowed_footprint_);
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003299 DCHECK_LE(max_allowed_footprint_, GetMaxMemory());
Mathieu Chartier74762802014-01-24 10:21:35 -08003300 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
3301 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
3302 // right away.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003303 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
3304 static_cast<size_t>(bytes_allocated));
Mathieu Chartier65db8802012-11-20 12:36:46 -08003305 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08003306 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003307}
3308
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003309void Heap::ClampGrowthLimit() {
Mathieu Chartierddac4232015-04-02 10:08:03 -07003310 // Use heap bitmap lock to guard against races with BindLiveToMarkBitmap.
3311 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003312 capacity_ = growth_limit_;
3313 for (const auto& space : continuous_spaces_) {
3314 if (space->IsMallocSpace()) {
3315 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3316 malloc_space->ClampGrowthLimit();
3317 }
3318 }
3319 // This space isn't added for performance reasons.
3320 if (main_space_backup_.get() != nullptr) {
3321 main_space_backup_->ClampGrowthLimit();
3322 }
3323}
3324
jeffhaoc1160702011-10-27 15:48:45 -07003325void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08003326 growth_limit_ = capacity_;
Mathieu Chartier0310da52014-12-01 13:40:48 -08003327 for (const auto& space : continuous_spaces_) {
3328 if (space->IsMallocSpace()) {
3329 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3330 malloc_space->ClearGrowthLimit();
3331 malloc_space->SetFootprintLimit(malloc_space->Capacity());
3332 }
3333 }
3334 // This space isn't added for performance reasons.
3335 if (main_space_backup_.get() != nullptr) {
3336 main_space_backup_->ClearGrowthLimit();
3337 main_space_backup_->SetFootprintLimit(main_space_backup_->Capacity());
3338 }
jeffhaoc1160702011-10-27 15:48:45 -07003339}
3340
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003341void Heap::AddFinalizerReference(Thread* self, mirror::Object** object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003342 ScopedObjectAccess soa(self);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003343 ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
Ian Rogers53b8b092014-03-13 23:45:53 -07003344 jvalue args[1];
3345 args[0].l = arg.get();
3346 InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003347 // Restore object in case it gets moved.
3348 *object = soa.Decode<mirror::Object*>(arg.get());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003349}
3350
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003351void Heap::RequestConcurrentGCAndSaveObject(Thread* self, bool force_full, mirror::Object** obj) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003352 StackHandleScope<1> hs(self);
3353 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003354 RequestConcurrentGC(self, force_full);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003355}
3356
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003357class Heap::ConcurrentGCTask : public HeapTask {
3358 public:
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003359 explicit ConcurrentGCTask(uint64_t target_time, bool force_full)
3360 : HeapTask(target_time), force_full_(force_full) { }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003361 virtual void Run(Thread* self) OVERRIDE {
3362 gc::Heap* heap = Runtime::Current()->GetHeap();
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003363 heap->ConcurrentGC(self, force_full_);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003364 heap->ClearConcurrentGCRequest();
Ian Rogers120f1c72012-09-28 17:17:10 -07003365 }
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003366
3367 private:
3368 const bool force_full_; // If true, force full (or partial) collection.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003369};
3370
3371static bool CanAddHeapTask(Thread* self) LOCKS_EXCLUDED(Locks::runtime_shutdown_lock_) {
3372 Runtime* runtime = Runtime::Current();
3373 return runtime != nullptr && runtime->IsFinishedStarting() && !runtime->IsShuttingDown(self) &&
3374 !self->IsHandlingStackOverflow();
3375}
3376
3377void Heap::ClearConcurrentGCRequest() {
3378 concurrent_gc_pending_.StoreRelaxed(false);
3379}
3380
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003381void Heap::RequestConcurrentGC(Thread* self, bool force_full) {
Mathieu Chartierac195162015-02-20 18:44:28 +00003382 if (CanAddHeapTask(self) &&
3383 concurrent_gc_pending_.CompareExchangeStrongSequentiallyConsistent(false, true)) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003384 task_processor_->AddTask(self, new ConcurrentGCTask(NanoTime(), // Start straight away.
3385 force_full));
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003386 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003387}
3388
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003389void Heap::ConcurrentGC(Thread* self, bool force_full) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003390 if (!Runtime::Current()->IsShuttingDown(self)) {
3391 // Wait for any GCs currently running to finish.
3392 if (WaitForGcToComplete(kGcCauseBackground, self) == collector::kGcTypeNone) {
3393 // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
3394 // instead. E.g. can't do partial, so do full instead.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003395 collector::GcType next_gc_type = next_gc_type_;
3396 // If forcing full and next gc type is sticky, override with a non-sticky type.
3397 if (force_full && next_gc_type == collector::kGcTypeSticky) {
3398 next_gc_type = HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
3399 }
3400 if (CollectGarbageInternal(next_gc_type, kGcCauseBackground, false) ==
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003401 collector::kGcTypeNone) {
3402 for (collector::GcType gc_type : gc_plan_) {
3403 // Attempt to run the collector, if we succeed, we are done.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003404 if (gc_type > next_gc_type &&
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003405 CollectGarbageInternal(gc_type, kGcCauseBackground, false) !=
3406 collector::kGcTypeNone) {
3407 break;
3408 }
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08003409 }
3410 }
3411 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07003412 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003413}
3414
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003415class Heap::CollectorTransitionTask : public HeapTask {
3416 public:
3417 explicit CollectorTransitionTask(uint64_t target_time) : HeapTask(target_time) { }
3418 virtual void Run(Thread* self) OVERRIDE {
3419 gc::Heap* heap = Runtime::Current()->GetHeap();
3420 heap->DoPendingCollectorTransition();
3421 heap->ClearPendingCollectorTransition(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003422 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003423};
3424
3425void Heap::ClearPendingCollectorTransition(Thread* self) {
3426 MutexLock mu(self, *pending_task_lock_);
3427 pending_collector_transition_ = nullptr;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003428}
3429
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003430void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
3431 Thread* self = Thread::Current();
3432 desired_collector_type_ = desired_collector_type;
3433 if (desired_collector_type_ == collector_type_ || !CanAddHeapTask(self)) {
3434 return;
3435 }
3436 CollectorTransitionTask* added_task = nullptr;
3437 const uint64_t target_time = NanoTime() + delta_time;
3438 {
3439 MutexLock mu(self, *pending_task_lock_);
3440 // If we have an existing collector transition, update the targe time to be the new target.
3441 if (pending_collector_transition_ != nullptr) {
3442 task_processor_->UpdateTargetRunTime(self, pending_collector_transition_, target_time);
3443 return;
3444 }
3445 added_task = new CollectorTransitionTask(target_time);
3446 pending_collector_transition_ = added_task;
3447 }
3448 task_processor_->AddTask(self, added_task);
3449}
3450
3451class Heap::HeapTrimTask : public HeapTask {
3452 public:
3453 explicit HeapTrimTask(uint64_t delta_time) : HeapTask(NanoTime() + delta_time) { }
3454 virtual void Run(Thread* self) OVERRIDE {
3455 gc::Heap* heap = Runtime::Current()->GetHeap();
3456 heap->Trim(self);
3457 heap->ClearPendingTrim(self);
3458 }
3459};
3460
3461void Heap::ClearPendingTrim(Thread* self) {
3462 MutexLock mu(self, *pending_task_lock_);
3463 pending_heap_trim_ = nullptr;
3464}
3465
3466void Heap::RequestTrim(Thread* self) {
3467 if (!CanAddHeapTask(self)) {
3468 return;
3469 }
Ian Rogers48931882013-01-22 14:35:16 -08003470 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3471 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3472 // a space it will hold its lock and can become a cause of jank.
3473 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3474 // forking.
3475
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08003476 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3477 // because that only marks object heads, so a large array looks like lots of empty space. We
3478 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3479 // to utilization (which is probably inversely proportional to how much benefit we can expect).
3480 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3481 // not how much use we're making of those pages.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003482 HeapTrimTask* added_task = nullptr;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003483 {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003484 MutexLock mu(self, *pending_task_lock_);
3485 if (pending_heap_trim_ != nullptr) {
3486 // Already have a heap trim request in task processor, ignore this request.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003487 return;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003488 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003489 added_task = new HeapTrimTask(kHeapTrimWait);
3490 pending_heap_trim_ = added_task;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07003491 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003492 task_processor_->AddTask(self, added_task);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003493}
3494
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003495void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003496 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003497 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3498 if (freed_bytes_revoke > 0U) {
3499 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3500 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3501 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003502 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003503 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003504 CHECK_EQ(bump_pointer_space_->RevokeThreadLocalBuffers(thread), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003505 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003506 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003507 CHECK_EQ(region_space_->RevokeThreadLocalBuffers(thread), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003508 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003509}
3510
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003511void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3512 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003513 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3514 if (freed_bytes_revoke > 0U) {
3515 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3516 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3517 }
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003518 }
3519}
3520
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003521void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003522 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003523 size_t freed_bytes_revoke = rosalloc_space_->RevokeAllThreadLocalBuffers();
3524 if (freed_bytes_revoke > 0U) {
3525 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3526 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3527 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003528 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003529 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003530 CHECK_EQ(bump_pointer_space_->RevokeAllThreadLocalBuffers(), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003531 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003532 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003533 CHECK_EQ(region_space_->RevokeAllThreadLocalBuffers(), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003534 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003535}
3536
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003537bool Heap::IsGCRequestPending() const {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003538 return concurrent_gc_pending_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003539}
3540
Mathieu Chartier590fee92013-09-13 13:46:47 -07003541void Heap::RunFinalization(JNIEnv* env) {
3542 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
3543 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
3544 CHECK(WellKnownClasses::java_lang_System != nullptr);
3545 WellKnownClasses::java_lang_System_runFinalization =
3546 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
3547 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
3548 }
3549 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
3550 WellKnownClasses::java_lang_System_runFinalization);
3551}
3552
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003553void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003554 Thread* self = ThreadForEnv(env);
3555 if (native_need_to_run_finalization_) {
3556 RunFinalization(env);
3557 UpdateMaxNativeFootprint();
3558 native_need_to_run_finalization_ = false;
3559 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003560 // Total number of native bytes allocated.
Ian Rogers3e5cf302014-05-20 16:40:37 -07003561 size_t new_native_bytes_allocated = native_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes);
3562 new_native_bytes_allocated += bytes;
3563 if (new_native_bytes_allocated > native_footprint_gc_watermark_) {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07003564 collector::GcType gc_type = HasZygoteSpace() ? collector::kGcTypePartial :
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08003565 collector::kGcTypeFull;
3566
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003567 // The second watermark is higher than the gc watermark. If you hit this it means you are
3568 // allocating native objects faster than the GC can keep up with.
Mathieu Chartier08487452014-09-02 16:21:01 -07003569 if (new_native_bytes_allocated > growth_limit_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003570 if (WaitForGcToComplete(kGcCauseForNativeAlloc, self) != collector::kGcTypeNone) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003571 // Just finished a GC, attempt to run finalizers.
3572 RunFinalization(env);
3573 CHECK(!env->ExceptionCheck());
Lin Zang60e27162015-03-10 18:53:21 +08003574 // Native bytes allocated may be updated by finalization, refresh it.
3575 new_native_bytes_allocated = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003576 }
3577 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
Mathieu Chartier08487452014-09-02 16:21:01 -07003578 if (new_native_bytes_allocated > growth_limit_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08003579 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003580 RunFinalization(env);
3581 native_need_to_run_finalization_ = false;
3582 CHECK(!env->ExceptionCheck());
3583 }
3584 // We have just run finalizers, update the native watermark since it is very likely that
3585 // finalizers released native managed allocations.
3586 UpdateMaxNativeFootprint();
3587 } else if (!IsGCRequestPending()) {
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003588 if (IsGcConcurrent()) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003589 RequestConcurrentGC(self, true); // Request non-sticky type.
Mathieu Chartier590fee92013-09-13 13:46:47 -07003590 } else {
Hiroshi Yamauchid20aba12014-04-11 15:31:09 -07003591 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003592 }
3593 }
3594 }
3595}
3596
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003597void Heap::RegisterNativeFree(JNIEnv* env, size_t bytes) {
3598 size_t expected_size;
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003599 do {
Ian Rogers3e5cf302014-05-20 16:40:37 -07003600 expected_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003601 if (UNLIKELY(bytes > expected_size)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003602 ScopedObjectAccess soa(env);
3603 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003604 StringPrintf("Attempted to free %zd native bytes with only %zd native bytes "
Mathieu Chartier590fee92013-09-13 13:46:47 -07003605 "registered as allocated", bytes, expected_size).c_str());
3606 break;
3607 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003608 } while (!native_bytes_allocated_.CompareExchangeWeakRelaxed(expected_size,
3609 expected_size - bytes));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003610}
3611
Ian Rogersef7d42f2014-01-06 12:55:46 -08003612size_t Heap::GetTotalMemory() const {
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003613 return std::max(max_allowed_footprint_, GetBytesAllocated());
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07003614}
3615
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003616void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3617 DCHECK(mod_union_table != nullptr);
3618 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3619}
3620
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003621void Heap::CheckPreconditionsForAllocObject(mirror::Class* c, size_t byte_count) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003622 CHECK(c == nullptr || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers1ff3c982014-08-12 02:30:58 -07003623 (c->IsVariableSize() || c->GetObjectSize() == byte_count));
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003624 CHECK_GE(byte_count, sizeof(mirror::Object));
3625}
3626
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003627void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
3628 CHECK(remembered_set != nullptr);
3629 space::Space* space = remembered_set->GetSpace();
3630 CHECK(space != nullptr);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003631 CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003632 remembered_sets_.Put(space, remembered_set);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003633 CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003634}
3635
3636void Heap::RemoveRememberedSet(space::Space* space) {
3637 CHECK(space != nullptr);
3638 auto it = remembered_sets_.find(space);
3639 CHECK(it != remembered_sets_.end());
Mathieu Chartier5189e242014-07-24 11:11:05 -07003640 delete it->second;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003641 remembered_sets_.erase(it);
3642 CHECK(remembered_sets_.find(space) == remembered_sets_.end());
3643}
3644
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003645void Heap::ClearMarkedObjects() {
3646 // Clear all of the spaces' mark bitmaps.
3647 for (const auto& space : GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07003648 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003649 if (space->GetLiveBitmap() != mark_bitmap) {
3650 mark_bitmap->Clear();
3651 }
3652 }
3653 // Clear the marked objects in the discontinous space object sets.
3654 for (const auto& space : GetDiscontinuousSpaces()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07003655 space->GetMarkBitmap()->Clear();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003656 }
3657}
3658
Ian Rogers1d54e732013-05-02 21:10:01 -07003659} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07003660} // namespace art