blob: 2f36d02eef6bfb99c1b3bbd46078dd1cc499532d [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
Brian Carlstrom58ae9412011-10-04 00:56:06 -070019#include <limits>
Ian Rogers700a4022014-05-19 16:49:03 -070020#include <memory>
Carl Shapiro58551df2011-07-24 03:09:51 -070021#include <vector>
22
Andreas Gampe46ee31b2016-12-14 10:11:49 -080023#include "android-base/stringprintf.h"
24
Andreas Gampe27fa96c2016-10-07 15:05:24 -070025#include "allocation_listener.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070026#include "art_field-inl.h"
Mathieu Chartier34583592017-03-23 23:51:34 -070027#include "backtrace_helper.h"
Mathieu Chartierbad02672014-08-25 13:08:22 -070028#include "base/allocator.h"
Mathieu Chartier8d447252015-10-26 10:21:14 -070029#include "base/arena_allocator.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070030#include "base/dumpable.h"
David Sehr891a50e2017-10-27 17:01:07 -070031#include "base/file_utils.h"
Mathieu Chartierb2f99362013-11-20 17:26:00 -080032#include "base/histogram-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080033#include "base/logging.h" // For VLOG.
Hiroshi Yamauchi55113ed2017-02-10 15:12:46 -080034#include "base/memory_tool.h"
David Sehrc431b9d2018-03-02 12:01:51 -080035#include "base/os.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080036#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080037#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010038#include "base/time_utils.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070039#include "common_throws.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070040#include "debugger.h"
David Sehr9e734c72018-01-04 17:56:19 -080041#include "dex/dex_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070042#include "entrypoints/quick/quick_alloc_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070043#include "gc/accounting/card_table-inl.h"
44#include "gc/accounting/heap_bitmap-inl.h"
45#include "gc/accounting/mod_union_table-inl.h"
Andreas Gamped4901292017-05-30 18:41:34 -070046#include "gc/accounting/read_barrier_table.h"
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -080047#include "gc/accounting/remembered_set.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070048#include "gc/accounting/space_bitmap-inl.h"
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070049#include "gc/collector/concurrent_copying.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070050#include "gc/collector/mark_sweep.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070051#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070052#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070053#include "gc/collector/sticky_mark_sweep.h"
Hans Boehmfb8b4e22018-09-05 16:45:42 -070054#include "gc/racing_check.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070055#include "gc/reference_processor.h"
Hiroshi Yamauchi3b1d1b72016-10-12 11:53:57 -070056#include "gc/scoped_gc_critical_section.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070057#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070058#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070059#include "gc/space/image_space.h"
60#include "gc/space/large_object_space.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080061#include "gc/space/region_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070062#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070063#include "gc/space/space-inl.h"
Mathieu Chartiera1602f22014-01-13 17:19:19 -080064#include "gc/space/zygote_space.h"
Mathieu Chartiera5eae692014-12-17 17:56:03 -080065#include "gc/task_processor.h"
Mathieu Chartier1ca68902017-04-18 11:26:22 -070066#include "gc/verification.h"
Andreas Gampe9b8c5882016-10-21 15:27:46 -070067#include "gc_pause_listener.h"
Andreas Gamped4901292017-05-30 18:41:34 -070068#include "gc_root.h"
Steven Morelande431e272017-07-18 16:53:49 -070069#include "handle_scope-inl.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070070#include "heap-inl.h"
Andreas Gampe351c4472017-07-12 19:32:55 -070071#include "heap-visit-objects-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070072#include "image.h"
Mathieu Chartiereb175f72014-10-31 11:49:27 -070073#include "intern_table.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000074#include "jit/jit.h"
75#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010076#include "jni/java_vm_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080077#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080078#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080079#include "mirror/object-refvisitor-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080080#include "mirror/object_array-inl.h"
Mathieu Chartier8fa2dad2014-03-13 12:22:56 -070081#include "mirror/reference-inl.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070082#include "nativehelper/scoped_local_ref.h"
Steven Morelande431e272017-07-18 16:53:49 -070083#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070084#include "reflection.h"
Mathieu Chartier0de9f732013-11-22 17:58:48 -080085#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070086#include "scoped_thread_state_change-inl.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070087#include "thread_list.h"
Andreas Gampe90b936d2017-01-31 08:58:55 -080088#include "verify_object-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070089#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070090
91namespace art {
Mathieu Chartier50482232013-11-21 11:48:14 -080092
Ian Rogers1d54e732013-05-02 21:10:01 -070093namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070094
Mathieu Chartier91e30632014-03-25 15:58:50 -070095static constexpr size_t kCollectorTransitionStressIterations = 0;
96static constexpr size_t kCollectorTransitionStressWait = 10 * 1000; // Microseconds
Andreas Gampeed56b5e2017-10-19 12:58:19 -070097
98DEFINE_RUNTIME_DEBUG_FLAG(Heap, kStressCollectorTransition);
99
Ian Rogers1d54e732013-05-02 21:10:01 -0700100// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -0700101static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier74762802014-01-24 10:21:35 -0800102static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -0700103// Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700104// relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -0700105// threads (lower pauses, use less memory bandwidth).
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700106static constexpr double kStickyGcThroughputAdjustment =
107 kEnableGenerationalConcurrentCopyingCollection ? 0.5 : 1.0;
Mathieu Chartierc1790162014-05-23 10:54:50 -0700108// Whether or not we compact the zygote in PreZygoteFork.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700109static constexpr bool kCompactZygote = kMovingCollector;
Mathieu Chartierc1790162014-05-23 10:54:50 -0700110// How many reserve entries are at the end of the allocation stack, these are only needed if the
111// allocation stack overflows.
112static constexpr size_t kAllocationStackReserveSize = 1024;
113// Default mark stack size in bytes.
114static const size_t kDefaultMarkStackSize = 64 * KB;
Zuo Wangf37a88b2014-07-10 04:26:41 -0700115// Define space name.
116static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
117static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
118static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
Mathieu Chartier7247af52014-11-19 10:51:42 -0800119static const char* kNonMovingSpaceName = "non moving space";
120static const char* kZygoteSpaceName = "zygote space";
Mathieu Chartierb363f662014-07-16 13:28:58 -0700121static constexpr size_t kGSSBumpPointerSpaceCapacity = 32 * MB;
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800122static constexpr bool kGCALotMode = false;
123// GC alot mode uses a small allocation stack to stress test a lot of GC.
124static constexpr size_t kGcAlotAllocationStackSize = 4 * KB /
125 sizeof(mirror::HeapReference<mirror::Object>);
126// Verify objet has a small allocation stack size since searching the allocation stack is slow.
127static constexpr size_t kVerifyObjectAllocationStackSize = 16 * KB /
128 sizeof(mirror::HeapReference<mirror::Object>);
129static constexpr size_t kDefaultAllocationStackSize = 8 * MB /
130 sizeof(mirror::HeapReference<mirror::Object>);
Mathieu Chartier0051be62012-10-12 17:47:11 -0700131
Andreas Gampeace0dc12016-01-20 13:33:13 -0800132// For deterministic compilation, we need the heap to be at a well-known address.
133static constexpr uint32_t kAllocSpaceBeginForDeterministicAoT = 0x40000000;
Hiroshi Yamauchib62f2e62016-03-23 15:51:24 -0700134// Dump the rosalloc stats on SIGQUIT.
135static constexpr bool kDumpRosAllocStatsOnSigQuit = false;
Andreas Gampeace0dc12016-01-20 13:33:13 -0800136
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800137static const char* kRegionSpaceName = "main space (region space)";
138
Mathieu Chartier6bc77742017-04-18 17:46:23 -0700139// If true, we log all GCs in the both the foreground and background. Used for debugging.
140static constexpr bool kLogAllGCs = false;
141
142// How much we grow the TLAB if we can do it.
143static constexpr size_t kPartialTlabSize = 16 * KB;
144static constexpr bool kUsePartialTlabs = true;
145
Mathieu Chartiera98a2822017-05-24 16:14:10 -0700146// Use Max heap for 2 seconds, this is smaller than the usual 5s window since we don't want to leave
147// allocate with relaxed ergonomics for that long.
148static constexpr size_t kPostForkMaxHeapDurationMS = 2000;
149
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800150#if defined(__LP64__) || !defined(ADDRESS_SANITIZER)
151// 300 MB (0x12c00000) - (default non-moving space capacity).
Mathieu Chartierfa4ea822018-03-02 13:48:54 -0800152uint8_t* const Heap::kPreferredAllocSpaceBegin =
153 reinterpret_cast<uint8_t*>(300 * MB - kDefaultNonMovingSpaceCapacity);
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800154#else
Andreas Gampee8857fe2017-05-03 08:28:13 -0700155#ifdef __ANDROID__
156// For 32-bit Android, use 0x20000000 because asan reserves 0x04000000 - 0x20000000.
Mathieu Chartierfa4ea822018-03-02 13:48:54 -0800157uint8_t* const Heap::kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x20000000);
Andreas Gampee8857fe2017-05-03 08:28:13 -0700158#else
159// For 32-bit host, use 0x40000000 because asan uses most of the space below this.
Mathieu Chartierfa4ea822018-03-02 13:48:54 -0800160uint8_t* const Heap::kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x40000000);
Andreas Gampee8857fe2017-05-03 08:28:13 -0700161#endif
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800162#endif
163
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700164static inline bool CareAboutPauseTimes() {
165 return Runtime::Current()->InJankPerceptibleProcessState();
166}
167
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700168Heap::Heap(size_t initial_size,
169 size_t growth_limit,
170 size_t min_free,
171 size_t max_free,
172 double target_utilization,
173 double foreground_heap_growth_multiplier,
174 size_t capacity,
175 size_t non_moving_space_capacity,
Vladimir Markod1908512018-11-22 14:57:28 +0000176 const std::vector<std::string>& boot_class_path,
177 const std::vector<std::string>& boot_class_path_locations,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700178 const std::string& image_file_name,
179 const InstructionSet image_instruction_set,
180 CollectorType foreground_collector_type,
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700181 CollectorType background_collector_type,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700182 space::LargeObjectSpaceType large_object_space_type,
183 size_t large_object_threshold,
184 size_t parallel_gc_threads,
185 size_t conc_gc_threads,
186 bool low_memory_mode,
187 size_t long_pause_log_threshold,
188 size_t long_gc_log_threshold,
189 bool ignore_max_footprint,
190 bool use_tlab,
191 bool verify_pre_gc_heap,
192 bool verify_pre_sweeping_heap,
193 bool verify_post_gc_heap,
194 bool verify_pre_gc_rosalloc,
195 bool verify_pre_sweeping_rosalloc,
196 bool verify_post_gc_rosalloc,
197 bool gc_stress_mode,
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700198 bool measure_gc_performance,
Mathieu Chartier31000802015-06-14 14:14:37 -0700199 bool use_homogeneous_space_compaction_for_oom,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700200 uint64_t min_interval_homogeneous_space_compaction_by_oom)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800201 : non_moving_space_(nullptr),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800202 rosalloc_space_(nullptr),
203 dlmalloc_space_(nullptr),
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800204 main_space_(nullptr),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800205 collector_type_(kCollectorTypeNone),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700206 foreground_collector_type_(foreground_collector_type),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800207 background_collector_type_(background_collector_type),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700208 desired_collector_type_(foreground_collector_type_),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800209 pending_task_lock_(nullptr),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700210 parallel_gc_threads_(parallel_gc_threads),
211 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -0700212 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700213 long_pause_log_threshold_(long_pause_log_threshold),
214 long_gc_log_threshold_(long_gc_log_threshold),
Albert Mingkun Yang2d7329b2018-11-30 19:58:18 +0000215 process_cpu_start_time_ns_(ProcessCpuNanoTime()),
216 last_process_cpu_time_ns_(process_cpu_start_time_ns_),
217 weighted_allocated_bytes_(0u),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700218 ignore_max_footprint_(ignore_max_footprint),
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -0700219 zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700220 zygote_space_(nullptr),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700221 large_object_threshold_(large_object_threshold),
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700222 disable_thread_flip_count_(0),
223 thread_flip_running_(false),
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800224 collector_type_running_(kCollectorTypeNone),
Mathieu Chartier40112dd2017-06-26 17:49:09 -0700225 last_gc_cause_(kGcCauseNone),
Mathieu Chartier183009a2017-02-16 21:19:28 -0800226 thread_running_gc_(nullptr),
Ian Rogers1d54e732013-05-02 21:10:01 -0700227 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700228 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800229 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700230 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700231 max_allowed_footprint_(initial_size),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800232 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700233 total_bytes_freed_ever_(0),
234 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800235 num_bytes_allocated_(0),
Richard Uhlercaaa2b02017-02-01 09:54:17 +0000236 new_native_bytes_allocated_(0),
237 old_native_bytes_allocated_(0),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700238 num_bytes_freed_revoke_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700239 verify_missing_card_marks_(false),
240 verify_system_weaks_(false),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800241 verify_pre_gc_heap_(verify_pre_gc_heap),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700242 verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800243 verify_post_gc_heap_(verify_post_gc_heap),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700244 verify_mod_union_table_(false),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800245 verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700246 verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800247 verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
Mathieu Chartier31000802015-06-14 14:14:37 -0700248 gc_stress_mode_(gc_stress_mode),
Hans Boehmd972b422017-09-11 12:57:00 -0700249 /* For GC a lot mode, we limit the allocation stacks to be kGcAlotInterval allocations. This
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700250 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
251 * verification is enabled, we limit the size of allocation stacks to speed up their
252 * searching.
253 */
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800254 max_allocation_stack_size_(kGCALotMode ? kGcAlotAllocationStackSize
255 : (kVerifyObjectSupport > kVerifyObjectModeFast) ? kVerifyObjectAllocationStackSize :
256 kDefaultAllocationStackSize),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800257 current_allocator_(kAllocatorTypeDlMalloc),
258 current_non_moving_allocator_(kAllocatorTypeNonMoving),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700259 bump_pointer_space_(nullptr),
260 temp_space_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800261 region_space_(nullptr),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700262 min_free_(min_free),
263 max_free_(max_free),
264 target_utilization_(target_utilization),
Mathieu Chartier11c273d2017-10-15 20:54:45 -0700265 foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700266 total_wait_time_(0),
Mathieu Chartier4e305412014-02-19 10:54:44 -0800267 verify_object_mode_(kVerifyObjectModeDisabled),
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800268 disable_moving_gc_count_(0),
Vladimir Marko8da690f2016-08-11 18:25:53 +0100269 semi_space_collector_(nullptr),
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700270 active_concurrent_copying_collector_(nullptr),
271 young_concurrent_copying_collector_(nullptr),
Vladimir Marko8da690f2016-08-11 18:25:53 +0100272 concurrent_copying_collector_(nullptr),
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700273 is_running_on_memory_tool_(Runtime::Current()->IsRunningOnMemoryTool()),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700274 use_tlab_(use_tlab),
275 main_space_backup_(nullptr),
Mathieu Chartierb363f662014-07-16 13:28:58 -0700276 min_interval_homogeneous_space_compaction_by_oom_(
277 min_interval_homogeneous_space_compaction_by_oom),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700278 last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800279 pending_collector_transition_(nullptr),
280 pending_heap_trim_(nullptr),
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700281 use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom),
282 running_collection_is_blocking_(false),
283 blocking_gc_count_(0U),
284 blocking_gc_time_(0U),
285 last_update_time_gc_count_rate_histograms_( // Round down by the window duration.
286 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration),
287 gc_count_last_window_(0U),
288 blocking_gc_count_last_window_(0U),
289 gc_count_rate_histogram_("gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
290 blocking_gc_count_rate_histogram_("blocking gc count rate histogram", 1U,
Man Cao8c2ff642015-05-27 17:25:30 -0700291 kGcCountRateMaxBucketCount),
Mathieu Chartier31000802015-06-14 14:14:37 -0700292 alloc_tracking_enabled_(false),
293 backtrace_lock_(nullptr),
294 seen_backtrace_count_(0u),
Mathieu Chartier51168372015-08-12 16:40:32 -0700295 unique_backtrace_count_(0u),
Jeff Haodcdc85b2015-12-04 14:06:18 -0800296 gc_disabled_for_shutdown_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800297 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800298 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700299 }
Hiroshi Yamauchi1b0adbf2016-11-14 17:35:12 -0800300 if (kUseReadBarrier) {
301 CHECK_EQ(foreground_collector_type_, kCollectorTypeCC);
302 CHECK_EQ(background_collector_type_, kCollectorTypeCCBackground);
303 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -0700304 verification_.reset(new Verification(this));
Mathieu Chartier8261d022016-08-08 09:41:04 -0700305 CHECK_GE(large_object_threshold, kMinLargeObjectThreshold);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800306 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier31000802015-06-14 14:14:37 -0700307 Runtime* const runtime = Runtime::Current();
Mathieu Chartier50482232013-11-21 11:48:14 -0800308 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
309 // entrypoints.
Mathieu Chartier31000802015-06-14 14:14:37 -0700310 const bool is_zygote = runtime->IsZygote();
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700311 if (!is_zygote) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700312 // Background compaction is currently not supported for command line runs.
313 if (background_collector_type_ != foreground_collector_type_) {
Mathieu Chartier52ba1992014-05-07 14:39:21 -0700314 VLOG(heap) << "Disabling background compaction for non zygote";
Mathieu Chartier31f44142014-04-08 14:40:03 -0700315 background_collector_type_ = foreground_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800316 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800317 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800318 ChangeCollector(desired_collector_type_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700319 live_bitmap_.reset(new accounting::HeapBitmap(this));
320 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800321
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800322 // We don't have hspace compaction enabled with GSS or CC.
323 if (foreground_collector_type_ == kCollectorTypeGSS ||
324 foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800325 use_homogeneous_space_compaction_for_oom_ = false;
326 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700327 bool support_homogeneous_space_compaction =
Mathieu Chartier0deeb812014-08-21 18:28:20 -0700328 background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800329 use_homogeneous_space_compaction_for_oom_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700330 // We may use the same space the main space for the non moving space if we don't need to compact
331 // from the main space.
332 // This is not the case if we support homogeneous compaction or have a moving background
333 // collector type.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700334 bool separate_non_moving_space = is_zygote ||
335 support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
336 IsMovingGc(background_collector_type_);
Mathieu Chartier76ce9172016-01-27 10:44:20 -0800337 if (foreground_collector_type_ == kCollectorTypeGSS) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700338 separate_non_moving_space = false;
339 }
Vladimir Markod44d7032018-08-30 13:02:31 +0100340
341 // Requested begin for the alloc space, to follow the mapped image and oat files
342 uint8_t* request_begin = nullptr;
343 // Calculate the extra space required after the boot image, see allocations below.
Vladimir Marko4df2d802018-09-27 16:42:44 +0000344 size_t heap_reservation_size = 0u;
345 if (separate_non_moving_space) {
346 heap_reservation_size = non_moving_space_capacity;
347 } else if ((foreground_collector_type_ != kCollectorTypeCC) &&
348 (is_zygote || foreground_collector_type_ == kCollectorTypeGSS)) {
349 heap_reservation_size = capacity_;
350 }
Vladimir Markod44d7032018-08-30 13:02:31 +0100351 heap_reservation_size = RoundUp(heap_reservation_size, kPageSize);
352 // Load image space(s).
353 std::vector<std::unique_ptr<space::ImageSpace>> boot_image_spaces;
354 MemMap heap_reservation;
Vladimir Markod1908512018-11-22 14:57:28 +0000355 if (space::ImageSpace::LoadBootImage(boot_class_path,
356 boot_class_path_locations,
357 image_file_name,
Vladimir Markod44d7032018-08-30 13:02:31 +0100358 image_instruction_set,
359 heap_reservation_size,
360 &boot_image_spaces,
361 &heap_reservation)) {
362 DCHECK_EQ(heap_reservation_size, heap_reservation.IsValid() ? heap_reservation.Size() : 0u);
363 DCHECK(!boot_image_spaces.empty());
364 request_begin = boot_image_spaces.back()->GetImageHeader().GetOatFileEnd();
365 DCHECK(!heap_reservation.IsValid() || request_begin == heap_reservation.Begin())
366 << "request_begin=" << static_cast<const void*>(request_begin)
367 << " heap_reservation.Begin()=" << static_cast<const void*>(heap_reservation.Begin());
368 for (std::unique_ptr<space::ImageSpace>& space : boot_image_spaces) {
369 boot_image_spaces_.push_back(space.get());
370 AddSpace(space.release());
371 }
372 } else {
373 if (foreground_collector_type_ == kCollectorTypeCC) {
374 // Need to use a low address so that we can allocate a contiguous 2 * Xmx space
375 // when there's no image (dex2oat for target).
376 request_begin = kPreferredAllocSpaceBegin;
377 }
378 // Gross hack to make dex2oat deterministic.
379 if (foreground_collector_type_ == kCollectorTypeMS && Runtime::Current()->IsAotCompiler()) {
380 // Currently only enabled for MS collector since that is what the deterministic dex2oat uses.
381 // b/26849108
382 request_begin = reinterpret_cast<uint8_t*>(kAllocSpaceBeginForDeterministicAoT);
383 }
384 }
385
386 /*
387 requested_alloc_space_begin -> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
388 +- nonmoving space (non_moving_space_capacity)+-
389 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
390 +-????????????????????????????????????????????+-
391 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
392 +-main alloc space / bump space 1 (capacity_) +-
393 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
394 +-????????????????????????????????????????????+-
395 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
396 +-main alloc space2 / bump space 2 (capacity_)+-
397 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
398 */
399
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100400 MemMap main_mem_map_1;
401 MemMap main_mem_map_2;
Andreas Gampeace0dc12016-01-20 13:33:13 -0800402
Mathieu Chartierb363f662014-07-16 13:28:58 -0700403 std::string error_str;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100404 MemMap non_moving_space_mem_map;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700405 if (separate_non_moving_space) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800406 ScopedTrace trace2("Create separate non moving space");
Mathieu Chartier7247af52014-11-19 10:51:42 -0800407 // If we are the zygote, the non moving space becomes the zygote space when we run
408 // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
409 // rename the mem map later.
Roland Levillain5e8d5f02016-10-18 18:03:43 +0100410 const char* space_name = is_zygote ? kZygoteSpaceName : kNonMovingSpaceName;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700411 // Reserve the non moving mem map before the other two since it needs to be at a specific
412 // address.
Vladimir Markod44d7032018-08-30 13:02:31 +0100413 DCHECK_EQ(heap_reservation.IsValid(), !boot_image_spaces_.empty());
414 if (heap_reservation.IsValid()) {
415 non_moving_space_mem_map = heap_reservation.RemapAtEnd(
416 heap_reservation.Begin(), space_name, PROT_READ | PROT_WRITE, &error_str);
417 } else {
418 non_moving_space_mem_map = MapAnonymousPreferredAddress(
419 space_name, request_begin, non_moving_space_capacity, &error_str);
420 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100421 CHECK(non_moving_space_mem_map.IsValid()) << error_str;
Vladimir Markod44d7032018-08-30 13:02:31 +0100422 DCHECK(!heap_reservation.IsValid());
Mathieu Chartierc44ce2e2014-08-25 16:32:41 -0700423 // Try to reserve virtual memory at a lower address if we have a separate non moving space.
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800424 request_begin = kPreferredAllocSpaceBegin + non_moving_space_capacity;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700425 }
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700426 // Attempt to create 2 mem maps at or after the requested begin.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800427 if (foreground_collector_type_ != kCollectorTypeCC) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800428 ScopedTrace trace2("Create main mem map");
Vladimir Marko4df2d802018-09-27 16:42:44 +0000429 if (separate_non_moving_space ||
430 !(is_zygote || foreground_collector_type_ == kCollectorTypeGSS)) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100431 main_mem_map_1 = MapAnonymousPreferredAddress(
432 kMemMapSpaceName[0], request_begin, capacity_, &error_str);
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700433 } else {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000434 // If no separate non-moving space and we are the zygote or the collector type is GSS,
435 // the main space must come right after the image space to avoid a gap.
436 // This is required since we want the zygote space to be adjacent to the image space.
Vladimir Markod44d7032018-08-30 13:02:31 +0100437 DCHECK_EQ(heap_reservation.IsValid(), !boot_image_spaces_.empty());
438 main_mem_map_1 = MemMap::MapAnonymous(
439 kMemMapSpaceName[0],
440 request_begin,
441 capacity_,
442 PROT_READ | PROT_WRITE,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700443 /* low_4gb= */ true,
444 /* reuse= */ false,
Vladimir Markod44d7032018-08-30 13:02:31 +0100445 heap_reservation.IsValid() ? &heap_reservation : nullptr,
446 &error_str);
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700447 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100448 CHECK(main_mem_map_1.IsValid()) << error_str;
Vladimir Markod44d7032018-08-30 13:02:31 +0100449 DCHECK(!heap_reservation.IsValid());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800450 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700451 if (support_homogeneous_space_compaction ||
452 background_collector_type_ == kCollectorTypeSS ||
453 foreground_collector_type_ == kCollectorTypeSS) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800454 ScopedTrace trace2("Create main mem map 2");
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100455 main_mem_map_2 = MapAnonymousPreferredAddress(
456 kMemMapSpaceName[1], main_mem_map_1.End(), capacity_, &error_str);
457 CHECK(main_mem_map_2.IsValid()) << error_str;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700458 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800459
Mathieu Chartierb363f662014-07-16 13:28:58 -0700460 // Create the non moving space first so that bitmaps don't take up the address range.
461 if (separate_non_moving_space) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800462 ScopedTrace trace2("Add non moving space");
Mathieu Chartier31f44142014-04-08 14:40:03 -0700463 // Non moving space is always dlmalloc since we currently don't have support for multiple
Zuo Wangf37a88b2014-07-10 04:26:41 -0700464 // active rosalloc spaces.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100465 const size_t size = non_moving_space_mem_map.Size();
Vladimir Markobd5e5f62018-09-07 11:21:34 +0100466 const void* non_moving_space_mem_map_begin = non_moving_space_mem_map.Begin();
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100467 non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(std::move(non_moving_space_mem_map),
468 "zygote / non moving space",
469 kDefaultStartingSize,
470 initial_size,
471 size,
472 size,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700473 /* can_move_objects= */ false);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700474 CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
Vladimir Markobd5e5f62018-09-07 11:21:34 +0100475 << non_moving_space_mem_map_begin;
476 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Mathieu Chartierb363f662014-07-16 13:28:58 -0700477 AddSpace(non_moving_space_);
478 }
479 // Create other spaces based on whether or not we have a moving GC.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800480 if (foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800481 CHECK(separate_non_moving_space);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +0000482 // Reserve twice the capacity, to allow evacuating every region for explicit GCs.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100483 MemMap region_space_mem_map =
484 space::RegionSpace::CreateMemMap(kRegionSpaceName, capacity_ * 2, request_begin);
485 CHECK(region_space_mem_map.IsValid()) << "No region space mem map";
486 region_space_ = space::RegionSpace::Create(kRegionSpaceName, std::move(region_space_mem_map));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800487 AddSpace(region_space_);
Richard Uhler054a0782015-04-07 10:56:50 -0700488 } else if (IsMovingGc(foreground_collector_type_) &&
489 foreground_collector_type_ != kCollectorTypeGSS) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700490 // Create bump pointer spaces.
491 // We only to create the bump pointer if the foreground collector is a compacting GC.
492 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
493 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100494 std::move(main_mem_map_1));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700495 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
496 AddSpace(bump_pointer_space_);
497 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100498 std::move(main_mem_map_2));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700499 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
500 AddSpace(temp_space_);
501 CHECK(separate_non_moving_space);
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700502 } else {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100503 CreateMainMallocSpace(std::move(main_mem_map_1), initial_size, growth_limit_, capacity_);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700504 CHECK(main_space_ != nullptr);
505 AddSpace(main_space_);
506 if (!separate_non_moving_space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700507 non_moving_space_ = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700508 CHECK(!non_moving_space_->CanMoveObjects());
509 }
510 if (foreground_collector_type_ == kCollectorTypeGSS) {
511 CHECK_EQ(foreground_collector_type_, background_collector_type_);
512 // Create bump pointer spaces instead of a backup space.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100513 main_mem_map_2.Reset();
514 bump_pointer_space_ = space::BumpPointerSpace::Create(
Vladimir Marko11306592018-10-26 14:22:59 +0100515 "Bump pointer space 1", kGSSBumpPointerSpaceCapacity);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700516 CHECK(bump_pointer_space_ != nullptr);
517 AddSpace(bump_pointer_space_);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100518 temp_space_ = space::BumpPointerSpace::Create(
Vladimir Marko11306592018-10-26 14:22:59 +0100519 "Bump pointer space 2", kGSSBumpPointerSpaceCapacity);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700520 CHECK(temp_space_ != nullptr);
521 AddSpace(temp_space_);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100522 } else if (main_mem_map_2.IsValid()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700523 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100524 main_space_backup_.reset(CreateMallocSpaceFromMemMap(std::move(main_mem_map_2),
525 initial_size,
526 growth_limit_,
527 capacity_,
528 name,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700529 /* can_move_objects= */ true));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700530 CHECK(main_space_backup_.get() != nullptr);
531 // Add the space so its accounted for in the heap_begin and heap_end.
532 AddSpace(main_space_backup_.get());
Zuo Wangf37a88b2014-07-10 04:26:41 -0700533 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700534 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700535 CHECK(non_moving_space_ != nullptr);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700536 CHECK(!non_moving_space_->CanMoveObjects());
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700537 // Allocate the large object space.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800538 if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
Vladimir Marko11306592018-10-26 14:22:59 +0100539 large_object_space_ = space::FreeListSpace::Create("free list large object space", capacity_);
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700540 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800541 } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700542 large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
543 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700544 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700545 // Disable the large object space by making the cutoff excessively large.
546 large_object_threshold_ = std::numeric_limits<size_t>::max();
547 large_object_space_ = nullptr;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700548 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700549 if (large_object_space_ != nullptr) {
550 AddSpace(large_object_space_);
551 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700552 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700553 CHECK(!continuous_spaces_.empty());
554 // Relies on the spaces being sorted.
Ian Rogers13735952014-10-08 12:43:28 -0700555 uint8_t* heap_begin = continuous_spaces_.front()->Begin();
556 uint8_t* heap_end = continuous_spaces_.back()->Limit();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700557 size_t heap_capacity = heap_end - heap_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700558 // Remove the main backup space since it slows down the GC to have unused extra spaces.
Mathieu Chartier0310da52014-12-01 13:40:48 -0800559 // TODO: Avoid needing to do this.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700560 if (main_space_backup_.get() != nullptr) {
561 RemoveSpace(main_space_backup_.get());
562 }
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800563 // Allocate the card table.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800564 // We currently don't support dynamically resizing the card table.
565 // Since we don't know where in the low_4gb the app image will be located, make the card table
566 // cover the whole low_4gb. TODO: Extend the card table in AddSpace.
567 UNUSED(heap_capacity);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +0000568 // Start at 4 KB, we can be sure there are no spaces mapped this low since the address range is
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800569 // reserved by the kernel.
570 static constexpr size_t kMinHeapAddress = 4 * KB;
571 card_table_.reset(accounting::CardTable::Create(reinterpret_cast<uint8_t*>(kMinHeapAddress),
572 4 * GB - kMinHeapAddress));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700573 CHECK(card_table_.get() != nullptr) << "Failed to create card table";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800574 if (foreground_collector_type_ == kCollectorTypeCC && kUseTableLookupReadBarrier) {
575 rb_table_.reset(new accounting::ReadBarrierTable());
576 DCHECK(rb_table_->IsAllCleared());
577 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800578 if (HasBootImageSpace()) {
Mathieu Chartier4858a932015-01-23 13:18:53 -0800579 // Don't add the image mod union table if we are running without an image, this can crash if
580 // we use the CardCache implementation.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800581 for (space::ImageSpace* image_space : GetBootImageSpaces()) {
582 accounting::ModUnionTable* mod_union_table = new accounting::ModUnionTableToZygoteAllocspace(
583 "Image mod-union table", this, image_space);
584 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
585 AddModUnionTable(mod_union_table);
586 }
Mathieu Chartier4858a932015-01-23 13:18:53 -0800587 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700588 if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800589 accounting::RememberedSet* non_moving_space_rem_set =
590 new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
591 CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
592 AddRememberedSet(non_moving_space_rem_set);
593 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700594 // TODO: Count objects in the image space here?
Orion Hodson88591fe2018-03-06 13:35:43 +0000595 num_bytes_allocated_.store(0, std::memory_order_relaxed);
Mathieu Chartierc1790162014-05-23 10:54:50 -0700596 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
597 kDefaultMarkStackSize));
598 const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
599 allocation_stack_.reset(accounting::ObjectStack::Create(
600 "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
601 live_stack_.reset(accounting::ObjectStack::Create(
602 "live stack", max_allocation_stack_size_, alloc_stack_capacity));
Mathieu Chartier65db8802012-11-20 12:36:46 -0800603 // It's still too early to take a lock because there are no threads yet, but we can create locks
604 // now. We don't create it earlier to make it clear that you can't use locks during heap
605 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700606 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700607 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
608 *gc_complete_lock_));
Richard Uhlercaaa2b02017-02-01 09:54:17 +0000609
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700610 thread_flip_lock_ = new Mutex("GC thread flip lock");
611 thread_flip_cond_.reset(new ConditionVariable("GC thread flip condition variable",
612 *thread_flip_lock_));
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800613 task_processor_.reset(new TaskProcessor());
Mathieu Chartier3cf22532015-07-09 15:15:09 -0700614 reference_processor_.reset(new ReferenceProcessor());
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800615 pending_task_lock_ = new Mutex("Pending task lock");
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700616 if (ignore_max_footprint_) {
617 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700618 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700619 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700620 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800621 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800622 for (size_t i = 0; i < 2; ++i) {
623 const bool concurrent = i != 0;
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800624 if ((MayUseCollector(kCollectorTypeCMS) && concurrent) ||
625 (MayUseCollector(kCollectorTypeMS) && !concurrent)) {
626 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
627 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
628 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
629 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800630 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800631 if (kMovingCollector) {
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800632 if (MayUseCollector(kCollectorTypeSS) || MayUseCollector(kCollectorTypeGSS) ||
633 MayUseCollector(kCollectorTypeHomogeneousSpaceCompact) ||
634 use_homogeneous_space_compaction_for_oom_) {
635 // TODO: Clean this up.
636 const bool generational = foreground_collector_type_ == kCollectorTypeGSS;
637 semi_space_collector_ = new collector::SemiSpace(this, generational,
638 generational ? "generational" : "");
639 garbage_collectors_.push_back(semi_space_collector_);
640 }
641 if (MayUseCollector(kCollectorTypeCC)) {
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700642 concurrent_copying_collector_ = new collector::ConcurrentCopying(this,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700643 /*young_gen=*/false,
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700644 "",
645 measure_gc_performance);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700646 if (kEnableGenerationalConcurrentCopyingCollection) {
647 young_concurrent_copying_collector_ = new collector::ConcurrentCopying(
648 this,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700649 /*young_gen=*/true,
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700650 "young",
651 measure_gc_performance);
652 }
653 active_concurrent_copying_collector_ = concurrent_copying_collector_;
Hiroshi Yamauchi4af14172016-10-25 11:55:10 -0700654 DCHECK(region_space_ != nullptr);
655 concurrent_copying_collector_->SetRegionSpace(region_space_);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700656 if (kEnableGenerationalConcurrentCopyingCollection) {
657 young_concurrent_copying_collector_->SetRegionSpace(region_space_);
658 }
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800659 garbage_collectors_.push_back(concurrent_copying_collector_);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700660 if (kEnableGenerationalConcurrentCopyingCollection) {
661 garbage_collectors_.push_back(young_concurrent_copying_collector_);
662 }
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800663 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700664 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800665 if (!GetBootImageSpaces().empty() && non_moving_space_ != nullptr &&
Andreas Gampee1cb2982014-08-27 11:01:09 -0700666 (is_zygote || separate_non_moving_space || foreground_collector_type_ == kCollectorTypeGSS)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700667 // 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 -0700668 // immune region won't break (eg. due to a large object allocated in the gap). This is only
669 // required when we're the zygote or using GSS.
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800670 // Space with smallest Begin().
671 space::ImageSpace* first_space = nullptr;
672 for (space::ImageSpace* space : boot_image_spaces_) {
673 if (first_space == nullptr || space->Begin() < first_space->Begin()) {
674 first_space = space;
675 }
676 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100677 bool no_gap = MemMap::CheckNoGaps(*first_space->GetMemMap(), *non_moving_space_->GetMemMap());
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700678 if (!no_gap) {
David Srbecky5dedb802015-06-17 00:08:02 +0100679 PrintFileToLog("/proc/self/maps", LogSeverity::ERROR);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700680 MemMap::DumpMaps(LOG_STREAM(ERROR), /* terse= */ true);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700681 LOG(FATAL) << "There's a gap between the image space and the non-moving space";
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700682 }
683 }
Mathieu Chartier31000802015-06-14 14:14:37 -0700684 instrumentation::Instrumentation* const instrumentation = runtime->GetInstrumentation();
685 if (gc_stress_mode_) {
686 backtrace_lock_ = new Mutex("GC complete lock");
687 }
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700688 if (is_running_on_memory_tool_ || gc_stress_mode_) {
Mathieu Chartier31000802015-06-14 14:14:37 -0700689 instrumentation->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700690 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800691 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800692 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700693 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700694}
695
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100696MemMap Heap::MapAnonymousPreferredAddress(const char* name,
697 uint8_t* request_begin,
698 size_t capacity,
699 std::string* out_error_str) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700700 while (true) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100701 MemMap map = MemMap::MapAnonymous(name,
702 request_begin,
703 capacity,
704 PROT_READ | PROT_WRITE,
Vladimir Marko11306592018-10-26 14:22:59 +0100705 /*low_4gb=*/ true,
706 /*reuse=*/ false,
707 /*reservation=*/ nullptr,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100708 out_error_str);
709 if (map.IsValid() || request_begin == nullptr) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700710 return map;
711 }
712 // Retry a second time with no specified request begin.
713 request_begin = nullptr;
714 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700715}
716
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800717bool Heap::MayUseCollector(CollectorType type) const {
718 return foreground_collector_type_ == type || background_collector_type_ == type;
719}
720
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100721space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap&& mem_map,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700722 size_t initial_size,
723 size_t growth_limit,
724 size_t capacity,
725 const char* name,
726 bool can_move_objects) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700727 space::MallocSpace* malloc_space = nullptr;
728 if (kUseRosAlloc) {
729 // Create rosalloc space.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100730 malloc_space = space::RosAllocSpace::CreateFromMemMap(std::move(mem_map),
731 name,
732 kDefaultStartingSize,
733 initial_size,
734 growth_limit,
735 capacity,
736 low_memory_mode_,
737 can_move_objects);
Zuo Wangf37a88b2014-07-10 04:26:41 -0700738 } else {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100739 malloc_space = space::DlMallocSpace::CreateFromMemMap(std::move(mem_map),
740 name,
741 kDefaultStartingSize,
742 initial_size,
743 growth_limit,
744 capacity,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700745 can_move_objects);
746 }
747 if (collector::SemiSpace::kUseRememberedSet) {
748 accounting::RememberedSet* rem_set =
749 new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
750 CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
751 AddRememberedSet(rem_set);
752 }
753 CHECK(malloc_space != nullptr) << "Failed to create " << name;
754 malloc_space->SetFootprintLimit(malloc_space->Capacity());
755 return malloc_space;
756}
757
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100758void Heap::CreateMainMallocSpace(MemMap&& mem_map,
759 size_t initial_size,
760 size_t growth_limit,
Mathieu Chartier31f44142014-04-08 14:40:03 -0700761 size_t capacity) {
762 // Is background compaction is enabled?
763 bool can_move_objects = IsMovingGc(background_collector_type_) !=
Zuo Wangf37a88b2014-07-10 04:26:41 -0700764 IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700765 // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
766 // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
767 // from the main space to the zygote space. If background compaction is enabled, always pass in
768 // that we can move objets.
769 if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
770 // After the zygote we want this to be false if we don't have background compaction enabled so
771 // that getting primitive array elements is faster.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700772 // We never have homogeneous compaction with GSS and don't need a space with movable objects.
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700773 can_move_objects = !HasZygoteSpace() && foreground_collector_type_ != kCollectorTypeGSS;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700774 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700775 if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
776 RemoveRememberedSet(main_space_);
777 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700778 const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100779 main_space_ = CreateMallocSpaceFromMemMap(std::move(mem_map),
780 initial_size,
781 growth_limit,
782 capacity, name,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700783 can_move_objects);
784 SetSpaceAsDefault(main_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700785 VLOG(heap) << "Created main space " << main_space_;
786}
787
Mathieu Chartier50482232013-11-21 11:48:14 -0800788void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800789 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800790 // These two allocators are only used internally and don't have any entrypoints.
791 CHECK_NE(allocator, kAllocatorTypeLOS);
792 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800793 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800794 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800795 SetQuickAllocEntryPointsAllocator(current_allocator_);
796 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
797 }
798}
799
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700800void Heap::DisableMovingGc() {
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700801 CHECK(!kUseReadBarrier);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700802 if (IsMovingGc(foreground_collector_type_)) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700803 foreground_collector_type_ = kCollectorTypeCMS;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800804 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700805 if (IsMovingGc(background_collector_type_)) {
806 background_collector_type_ = foreground_collector_type_;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800807 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700808 TransitionCollector(foreground_collector_type_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700809 Thread* const self = Thread::Current();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700810 ScopedThreadStateChange tsc(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700811 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700812 // Something may have caused the transition to fail.
Mathieu Chartiere4927f62014-08-23 13:56:03 -0700813 if (!IsMovingGc(collector_type_) && non_moving_space_ != main_space_) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700814 CHECK(main_space_ != nullptr);
815 // The allocation stack may have non movable objects in it. We need to flush it since the GC
816 // can't only handle marking allocation stack objects of one non moving space and one main
817 // space.
818 {
819 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
820 FlushAllocStack();
821 }
822 main_space_->DisableMovingObjects();
823 non_moving_space_ = main_space_;
824 CHECK(!non_moving_space_->CanMoveObjects());
825 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800826}
827
Mathieu Chartier590fee92013-09-13 13:46:47 -0700828bool Heap::IsCompilingBoot() const {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800829 if (!Runtime::Current()->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700830 return false;
831 }
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800832 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700833 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800834 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700835 return false;
836 }
837 }
838 return true;
839}
840
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800841void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700842 // Need to do this holding the lock to prevent races where the GC is about to run / running when
843 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800844 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700845 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800846 ++disable_moving_gc_count_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700847 if (IsMovingGc(collector_type_running_)) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -0700848 WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800849 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700850}
851
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800852void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700853 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierb735bd92015-06-24 17:04:17 -0700854 CHECK_GT(disable_moving_gc_count_, 0U);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800855 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700856}
857
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700858void Heap::IncrementDisableThreadFlip(Thread* self) {
859 // Supposed to be called by mutators. If thread_flip_running_ is true, block. Otherwise, go ahead.
860 CHECK(kUseReadBarrier);
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800861 bool is_nested = self->GetDisableThreadFlipCount() > 0;
862 self->IncrementDisableThreadFlipCount();
863 if (is_nested) {
864 // If this is a nested JNI critical section enter, we don't need to wait or increment the global
865 // counter. The global counter is incremented only once for a thread for the outermost enter.
866 return;
867 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700868 ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
869 MutexLock mu(self, *thread_flip_lock_);
870 bool has_waited = false;
871 uint64_t wait_start = NanoTime();
Hiroshi Yamauchiee235822016-08-19 17:03:27 -0700872 if (thread_flip_running_) {
Andreas Gampe9b827ab2017-12-07 19:32:48 -0800873 ScopedTrace trace("IncrementDisableThreadFlip");
Hiroshi Yamauchiee235822016-08-19 17:03:27 -0700874 while (thread_flip_running_) {
875 has_waited = true;
876 thread_flip_cond_->Wait(self);
877 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700878 }
879 ++disable_thread_flip_count_;
880 if (has_waited) {
881 uint64_t wait_time = NanoTime() - wait_start;
882 total_wait_time_ += wait_time;
883 if (wait_time > long_pause_log_threshold_) {
884 LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
885 }
886 }
887}
888
889void Heap::DecrementDisableThreadFlip(Thread* self) {
890 // Supposed to be called by mutators. Decrement disable_thread_flip_count_ and potentially wake up
891 // the GC waiting before doing a thread flip.
892 CHECK(kUseReadBarrier);
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800893 self->DecrementDisableThreadFlipCount();
894 bool is_outermost = self->GetDisableThreadFlipCount() == 0;
895 if (!is_outermost) {
896 // If this is not an outermost JNI critical exit, we don't need to decrement the global counter.
897 // The global counter is decremented only once for a thread for the outermost exit.
898 return;
899 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700900 MutexLock mu(self, *thread_flip_lock_);
901 CHECK_GT(disable_thread_flip_count_, 0U);
902 --disable_thread_flip_count_;
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800903 if (disable_thread_flip_count_ == 0) {
904 // Potentially notify the GC thread blocking to begin a thread flip.
905 thread_flip_cond_->Broadcast(self);
906 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700907}
908
909void Heap::ThreadFlipBegin(Thread* self) {
910 // Supposed to be called by GC. Set thread_flip_running_ to be true. If disable_thread_flip_count_
911 // > 0, block. Otherwise, go ahead.
912 CHECK(kUseReadBarrier);
913 ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
914 MutexLock mu(self, *thread_flip_lock_);
915 bool has_waited = false;
916 uint64_t wait_start = NanoTime();
917 CHECK(!thread_flip_running_);
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800918 // Set this to true before waiting so that frequent JNI critical enter/exits won't starve
919 // GC. This like a writer preference of a reader-writer lock.
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700920 thread_flip_running_ = true;
921 while (disable_thread_flip_count_ > 0) {
922 has_waited = true;
923 thread_flip_cond_->Wait(self);
924 }
925 if (has_waited) {
926 uint64_t wait_time = NanoTime() - wait_start;
927 total_wait_time_ += wait_time;
928 if (wait_time > long_pause_log_threshold_) {
929 LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
930 }
931 }
932}
933
934void Heap::ThreadFlipEnd(Thread* self) {
935 // Supposed to be called by GC. Set thread_flip_running_ to false and potentially wake up mutators
936 // waiting before doing a JNI critical.
937 CHECK(kUseReadBarrier);
938 MutexLock mu(self, *thread_flip_lock_);
939 CHECK(thread_flip_running_);
940 thread_flip_running_ = false;
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800941 // Potentially notify mutator threads blocking to enter a JNI critical section.
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700942 thread_flip_cond_->Broadcast(self);
943}
944
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700945void Heap::UpdateProcessState(ProcessState old_process_state, ProcessState new_process_state) {
946 if (old_process_state != new_process_state) {
947 const bool jank_perceptible = new_process_state == kProcessStateJankPerceptible;
Mathieu Chartier91e30632014-03-25 15:58:50 -0700948 for (size_t i = 1; i <= kCollectorTransitionStressIterations; ++i) {
949 // Start at index 1 to avoid "is always false" warning.
950 // Have iteration 1 always transition the collector.
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700951 TransitionCollector((((i & 1) == 1) == jank_perceptible)
952 ? foreground_collector_type_
953 : background_collector_type_);
Mathieu Chartier91e30632014-03-25 15:58:50 -0700954 usleep(kCollectorTransitionStressWait);
955 }
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700956 if (jank_perceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800957 // Transition back to foreground right away to prevent jank.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700958 RequestCollectorTransition(foreground_collector_type_, 0);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800959 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800960 // Don't delay for debug builds since we may want to stress test the GC.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700961 // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
962 // special handling which does a homogenous space compaction once but then doesn't transition
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700963 // the collector. Similarly, we invoke a full compaction for kCollectorTypeCC but don't
964 // transition the collector.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700965 RequestCollectorTransition(background_collector_type_,
Andreas Gampeed56b5e2017-10-19 12:58:19 -0700966 kStressCollectorTransition
967 ? 0
968 : kCollectorTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800969 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800970 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800971}
972
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700973void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700974 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
975 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800976 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700977 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700978}
979
Mathieu Chartier590fee92013-09-13 13:46:47 -0700980void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartier00b59152014-07-25 10:13:51 -0700981 space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
982 space::ContinuousSpace* space2 = non_moving_space_;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800983 // TODO: Generalize this to n bitmaps?
Mathieu Chartier00b59152014-07-25 10:13:51 -0700984 CHECK(space1 != nullptr);
985 CHECK(space2 != nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800986 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700987 (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
988 stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700989}
990
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700991void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700992 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700993}
994
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700995void Heap::AddSpace(space::Space* space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700996 CHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700997 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
998 if (space->IsContinuousSpace()) {
999 DCHECK(!space->IsDiscontinuousSpace());
1000 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1001 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001002 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1003 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartierecc82302017-02-16 10:20:12 -08001004 // The region space bitmap is not added since VisitObjects visits the region space objects with
1005 // special handling.
1006 if (live_bitmap != nullptr && !space->IsRegionSpace()) {
Mathieu Chartier2796a162014-07-25 11:50:47 -07001007 CHECK(mark_bitmap != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001008 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
1009 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001010 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001011 continuous_spaces_.push_back(continuous_space);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001012 // Ensure that spaces remain sorted in increasing order of start address.
1013 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
1014 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
1015 return a->Begin() < b->Begin();
1016 });
Mathieu Chartier590fee92013-09-13 13:46:47 -07001017 } else {
Mathieu Chartier2796a162014-07-25 11:50:47 -07001018 CHECK(space->IsDiscontinuousSpace());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001019 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001020 live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1021 mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001022 discontinuous_spaces_.push_back(discontinuous_space);
1023 }
1024 if (space->IsAllocSpace()) {
1025 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001026 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001027}
1028
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001029void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
1030 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1031 if (continuous_space->IsDlMallocSpace()) {
1032 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
1033 } else if (continuous_space->IsRosAllocSpace()) {
1034 rosalloc_space_ = continuous_space->AsRosAllocSpace();
1035 }
1036}
1037
1038void Heap::RemoveSpace(space::Space* space) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001039 DCHECK(space != nullptr);
1040 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1041 if (space->IsContinuousSpace()) {
1042 DCHECK(!space->IsDiscontinuousSpace());
1043 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1044 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001045 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1046 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartierecc82302017-02-16 10:20:12 -08001047 if (live_bitmap != nullptr && !space->IsRegionSpace()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001048 DCHECK(mark_bitmap != nullptr);
1049 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
1050 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
1051 }
1052 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
1053 DCHECK(it != continuous_spaces_.end());
1054 continuous_spaces_.erase(it);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001055 } else {
1056 DCHECK(space->IsDiscontinuousSpace());
1057 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001058 live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1059 mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001060 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
1061 discontinuous_space);
1062 DCHECK(it != discontinuous_spaces_.end());
1063 discontinuous_spaces_.erase(it);
1064 }
1065 if (space->IsAllocSpace()) {
1066 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
1067 DCHECK(it != alloc_spaces_.end());
1068 alloc_spaces_.erase(it);
1069 }
1070}
1071
Albert Mingkun Yang2d7329b2018-11-30 19:58:18 +00001072void Heap::CalculateWeightedAllocatedBytes() {
1073 uint64_t current_process_cpu_time = ProcessCpuNanoTime();
1074 uint64_t bytes_allocated = GetBytesAllocated();
1075 uint64_t weight = current_process_cpu_time - last_process_cpu_time_ns_;
1076 weighted_allocated_bytes_ += weight * bytes_allocated;
1077 last_process_cpu_time_ns_ = current_process_cpu_time;
1078}
1079
Albert Mingkun Yangd6e178e2018-11-19 12:58:30 +00001080uint64_t Heap::GetTotalGcCpuTime() {
1081 uint64_t sum = 0;
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001082 for (auto* collector : garbage_collectors_) {
Albert Mingkun Yangd6e178e2018-11-19 12:58:30 +00001083 sum += collector->GetTotalCpuTime();
1084 }
1085 return sum;
1086}
1087
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001088void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001089 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001090 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001091 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001092 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001093 uint64_t total_paused_time = 0;
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001094 for (auto* collector : garbage_collectors_) {
Mathieu Chartier104fa0c2014-08-07 14:26:27 -07001095 total_duration += collector->GetCumulativeTimings().GetTotalNs();
1096 total_paused_time += collector->GetTotalPausedTimeNs();
1097 collector->DumpPerformanceInfo(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001098 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001099 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -07001100 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001101 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
1102 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -07001103 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001104 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -07001105 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001106 }
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001107 uint64_t total_objects_allocated = GetObjectsAllocatedEver();
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001108 os << "Total number of allocations " << total_objects_allocated << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001109 os << "Total bytes allocated " << PrettySize(GetBytesAllocatedEver()) << "\n";
1110 os << "Total bytes freed " << PrettySize(GetBytesFreedEver()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001111 os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001112 os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
1113 os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001114 os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
1115 os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
Mathieu Chartiere4cab172014-08-19 18:24:04 -07001116 if (HasZygoteSpace()) {
1117 os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
1118 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001119 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001120 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
1121 os << "Total GC count: " << GetGcCount() << "\n";
1122 os << "Total GC time: " << PrettyDuration(GetGcTime()) << "\n";
1123 os << "Total blocking GC count: " << GetBlockingGcCount() << "\n";
1124 os << "Total blocking GC time: " << PrettyDuration(GetBlockingGcTime()) << "\n";
1125
1126 {
1127 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1128 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1129 os << "Histogram of GC count per " << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1130 gc_count_rate_histogram_.DumpBins(os);
1131 os << "\n";
1132 }
1133 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1134 os << "Histogram of blocking GC count per "
1135 << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1136 blocking_gc_count_rate_histogram_.DumpBins(os);
1137 os << "\n";
1138 }
1139 }
1140
Hiroshi Yamauchib62f2e62016-03-23 15:51:24 -07001141 if (kDumpRosAllocStatsOnSigQuit && rosalloc_space_ != nullptr) {
1142 rosalloc_space_->DumpStats(os);
1143 }
1144
Richard Uhlercaaa2b02017-02-01 09:54:17 +00001145 os << "Registered native bytes allocated: "
Orion Hodson88591fe2018-03-06 13:35:43 +00001146 << (old_native_bytes_allocated_.load(std::memory_order_relaxed) +
1147 new_native_bytes_allocated_.load(std::memory_order_relaxed))
Richard Uhlercaaa2b02017-02-01 09:54:17 +00001148 << "\n";
Mathieu Chartier5d2a3f72016-05-11 11:35:39 -07001149
Mathieu Chartier73d1e172014-04-11 17:53:48 -07001150 BaseMutex::DumpAll(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001151}
1152
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001153void Heap::ResetGcPerformanceInfo() {
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001154 for (auto* collector : garbage_collectors_) {
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001155 collector->ResetMeasurements();
1156 }
Albert Mingkun Yang2d7329b2018-11-30 19:58:18 +00001157
1158 process_cpu_start_time_ns_ = ProcessCpuNanoTime();
1159 last_process_cpu_time_ns_ = process_cpu_start_time_ns_;
1160 weighted_allocated_bytes_ = 0u;
1161
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001162 total_bytes_freed_ever_ = 0;
1163 total_objects_freed_ever_ = 0;
1164 total_wait_time_ = 0;
1165 blocking_gc_count_ = 0;
1166 blocking_gc_time_ = 0;
1167 gc_count_last_window_ = 0;
1168 blocking_gc_count_last_window_ = 0;
1169 last_update_time_gc_count_rate_histograms_ = // Round down by the window duration.
1170 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
1171 {
1172 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1173 gc_count_rate_histogram_.Reset();
1174 blocking_gc_count_rate_histogram_.Reset();
1175 }
1176}
1177
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001178uint64_t Heap::GetGcCount() const {
1179 uint64_t gc_count = 0U;
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001180 for (auto* collector : garbage_collectors_) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001181 gc_count += collector->GetCumulativeTimings().GetIterations();
1182 }
1183 return gc_count;
1184}
1185
1186uint64_t Heap::GetGcTime() const {
1187 uint64_t gc_time = 0U;
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001188 for (auto* collector : garbage_collectors_) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001189 gc_time += collector->GetCumulativeTimings().GetTotalNs();
1190 }
1191 return gc_time;
1192}
1193
1194uint64_t Heap::GetBlockingGcCount() const {
1195 return blocking_gc_count_;
1196}
1197
1198uint64_t Heap::GetBlockingGcTime() const {
1199 return blocking_gc_time_;
1200}
1201
1202void Heap::DumpGcCountRateHistogram(std::ostream& os) const {
1203 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1204 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1205 gc_count_rate_histogram_.DumpBins(os);
1206 }
1207}
1208
1209void Heap::DumpBlockingGcCountRateHistogram(std::ostream& os) const {
1210 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1211 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1212 blocking_gc_count_rate_histogram_.DumpBins(os);
1213 }
1214}
1215
Andreas Gampe27fa96c2016-10-07 15:05:24 -07001216ALWAYS_INLINE
1217static inline AllocationListener* GetAndOverwriteAllocationListener(
1218 Atomic<AllocationListener*>* storage, AllocationListener* new_value) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001219 return storage->exchange(new_value);
Andreas Gampe27fa96c2016-10-07 15:05:24 -07001220}
1221
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001222Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001223 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001224 STLDeleteElements(&garbage_collectors_);
1225 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001226 allocation_stack_->Reset();
Man Cao8c2ff642015-05-27 17:25:30 -07001227 allocation_records_.reset();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001228 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001229 STLDeleteValues(&mod_union_tables_);
Mathieu Chartier0767c9a2014-03-26 12:53:19 -07001230 STLDeleteValues(&remembered_sets_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001231 STLDeleteElements(&continuous_spaces_);
1232 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001233 delete gc_complete_lock_;
Andreas Gampe6be4f2a2015-11-10 13:34:17 -08001234 delete thread_flip_lock_;
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001235 delete pending_task_lock_;
Mathieu Chartier31000802015-06-14 14:14:37 -07001236 delete backtrace_lock_;
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001237 uint64_t unique_count = unique_backtrace_count_.load();
1238 uint64_t seen_count = seen_backtrace_count_.load();
Orion Hodson88591fe2018-03-06 13:35:43 +00001239 if (unique_count != 0 || seen_count != 0) {
1240 LOG(INFO) << "gc stress unique=" << unique_count << " total=" << (unique_count + seen_count);
Mathieu Chartier31000802015-06-14 14:14:37 -07001241 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001242 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001243}
1244
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001245
1246space::ContinuousSpace* Heap::FindContinuousSpaceFromAddress(const mirror::Object* addr) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001247 for (const auto& space : continuous_spaces_) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001248 if (space->Contains(addr)) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001249 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001250 }
1251 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001252 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001253}
1254
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001255space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
1256 bool fail_ok) const {
1257 space::ContinuousSpace* space = FindContinuousSpaceFromAddress(obj.Ptr());
1258 if (space != nullptr) {
1259 return space;
1260 }
1261 if (!fail_ok) {
1262 LOG(FATAL) << "object " << obj << " not inside any spaces!";
1263 }
1264 return nullptr;
1265}
1266
1267space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
Ian Rogers1d54e732013-05-02 21:10:01 -07001268 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001269 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001270 if (space->Contains(obj.Ptr())) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001271 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -07001272 }
1273 }
1274 if (!fail_ok) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001275 LOG(FATAL) << "object " << obj << " not inside any spaces!";
Ian Rogers1d54e732013-05-02 21:10:01 -07001276 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001277 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001278}
1279
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001280space::Space* Heap::FindSpaceFromObject(ObjPtr<mirror::Object> obj, bool fail_ok) const {
Ian Rogers1d54e732013-05-02 21:10:01 -07001281 space::Space* result = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001282 if (result != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001283 return result;
1284 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001285 return FindDiscontinuousSpaceFromObject(obj, fail_ok);
Ian Rogers1d54e732013-05-02 21:10:01 -07001286}
1287
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001288space::Space* Heap::FindSpaceFromAddress(const void* addr) const {
1289 for (const auto& space : continuous_spaces_) {
1290 if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1291 return space;
1292 }
1293 }
1294 for (const auto& space : discontinuous_spaces_) {
1295 if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1296 return space;
1297 }
1298 }
1299 return nullptr;
1300}
1301
Roland Levillain5fcf1ea2018-10-30 11:58:08 +00001302std::string Heap::DumpSpaceNameFromAddress(const void* addr) const {
1303 space::Space* space = FindSpaceFromAddress(addr);
1304 return (space != nullptr) ? space->GetName() : "no space";
1305}
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001306
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001307void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
Mathieu Chartiere8f3f032016-04-04 16:49:44 -07001308 // If we're in a stack overflow, do not create a new exception. It would require running the
1309 // constructor, which will of course still be in a stack overflow.
1310 if (self->IsHandlingStackOverflow()) {
Roland Levillain7b0e8442018-04-11 18:27:47 +01001311 self->SetException(
1312 Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow());
Mathieu Chartiere8f3f032016-04-04 16:49:44 -07001313 return;
1314 }
1315
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001316 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001317 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001318 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
Mathieu Chartiera9033d72016-12-01 17:41:17 -08001319 << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM,"
1320 << " max allowed footprint " << max_allowed_footprint_ << ", growth limit "
1321 << growth_limit_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001322 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001323 if (total_bytes_free >= byte_count) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001324 space::AllocSpace* space = nullptr;
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001325 if (allocator_type == kAllocatorTypeNonMoving) {
1326 space = non_moving_space_;
1327 } else if (allocator_type == kAllocatorTypeRosAlloc ||
1328 allocator_type == kAllocatorTypeDlMalloc) {
1329 space = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -07001330 } else if (allocator_type == kAllocatorTypeBumpPointer ||
1331 allocator_type == kAllocatorTypeTLAB) {
1332 space = bump_pointer_space_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001333 } else if (allocator_type == kAllocatorTypeRegion ||
1334 allocator_type == kAllocatorTypeRegionTLAB) {
1335 space = region_space_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001336 }
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001337 if (space != nullptr) {
1338 space->LogFragmentationAllocFailure(oss, byte_count);
1339 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001340 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001341 self->ThrowOutOfMemoryError(oss.str().c_str());
1342}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001343
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001344void Heap::DoPendingCollectorTransition() {
1345 CollectorType desired_collector_type = desired_collector_type_;
Mathieu Chartierb2728552014-09-08 20:08:41 +00001346 // Launch homogeneous space compaction if it is desired.
1347 if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
1348 if (!CareAboutPauseTimes()) {
1349 PerformHomogeneousSpaceCompact();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001350 } else {
1351 VLOG(gc) << "Homogeneous compaction ignored due to jank perceptible process state";
Mathieu Chartierb2728552014-09-08 20:08:41 +00001352 }
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07001353 } else if (desired_collector_type == kCollectorTypeCCBackground) {
1354 DCHECK(kUseReadBarrier);
1355 if (!CareAboutPauseTimes()) {
1356 // Invoke CC full compaction.
1357 CollectGarbageInternal(collector::kGcTypeFull,
1358 kGcCauseCollectorTransition,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001359 /*clear_soft_references=*/false);
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07001360 } else {
1361 VLOG(gc) << "CC background compaction ignored due to jank perceptible process state";
1362 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001363 } else {
1364 TransitionCollector(desired_collector_type);
Mathieu Chartierb2728552014-09-08 20:08:41 +00001365 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001366}
1367
1368void Heap::Trim(Thread* self) {
Mathieu Chartier8d447252015-10-26 10:21:14 -07001369 Runtime* const runtime = Runtime::Current();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001370 if (!CareAboutPauseTimes()) {
1371 // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
1372 // about pauses.
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001373 ScopedTrace trace("Deflating monitors");
Hiroshi Yamauchi3b1d1b72016-10-12 11:53:57 -07001374 // Avoid race conditions on the lock word for CC.
1375 ScopedGCCriticalSection gcs(self, kGcCauseTrim, kCollectorTypeHeapTrim);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001376 ScopedSuspendAll ssa(__FUNCTION__);
1377 uint64_t start_time = NanoTime();
1378 size_t count = runtime->GetMonitorList()->DeflateMonitors();
1379 VLOG(heap) << "Deflating " << count << " monitors took "
1380 << PrettyDuration(NanoTime() - start_time);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001381 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001382 TrimIndirectReferenceTables(self);
1383 TrimSpaces(self);
Mathieu Chartier8d447252015-10-26 10:21:14 -07001384 // Trim arenas that may have been used by JIT or verifier.
Mathieu Chartier8d447252015-10-26 10:21:14 -07001385 runtime->GetArenaPool()->TrimMaps();
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001386}
1387
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001388class TrimIndirectReferenceTableClosure : public Closure {
1389 public:
1390 explicit TrimIndirectReferenceTableClosure(Barrier* barrier) : barrier_(barrier) {
1391 }
Roland Levillainf73caca2018-08-24 17:19:07 +01001392 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers55256cb2017-12-21 17:07:11 -08001393 thread->GetJniEnv()->TrimLocals();
Lei Lidd9943d2015-02-02 14:24:44 +08001394 // If thread is a running mutator, then act on behalf of the trim thread.
1395 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001396 barrier_->Pass(Thread::Current());
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001397 }
1398
1399 private:
1400 Barrier* const barrier_;
1401};
1402
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001403void Heap::TrimIndirectReferenceTables(Thread* self) {
1404 ScopedObjectAccess soa(self);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001405 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001406 JavaVMExt* vm = soa.Vm();
1407 // Trim globals indirect reference table.
1408 vm->TrimGlobals();
1409 // Trim locals indirect reference tables.
1410 Barrier barrier(0);
1411 TrimIndirectReferenceTableClosure closure(&barrier);
1412 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1413 size_t barrier_count = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
Lei Lidd9943d2015-02-02 14:24:44 +08001414 if (barrier_count != 0) {
1415 barrier.Increment(self, barrier_count);
1416 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001417}
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001418
Mathieu Chartieraa516822015-10-02 15:53:37 -07001419void Heap::StartGC(Thread* self, GcCause cause, CollectorType collector_type) {
Mathieu Chartierb93d5b12017-05-19 13:05:06 -07001420 // Need to do this before acquiring the locks since we don't want to get suspended while
1421 // holding any locks.
1422 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartieraa516822015-10-02 15:53:37 -07001423 MutexLock mu(self, *gc_complete_lock_);
1424 // Ensure there is only one GC at a time.
1425 WaitForGcToCompleteLocked(cause, self);
1426 collector_type_running_ = collector_type;
Mathieu Chartier40112dd2017-06-26 17:49:09 -07001427 last_gc_cause_ = cause;
Mathieu Chartier183009a2017-02-16 21:19:28 -08001428 thread_running_gc_ = self;
Mathieu Chartieraa516822015-10-02 15:53:37 -07001429}
1430
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001431void Heap::TrimSpaces(Thread* self) {
Mathieu Chartierb93d5b12017-05-19 13:05:06 -07001432 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1433 // trimming.
1434 StartGC(self, kGcCauseTrim, kCollectorTypeHeapTrim);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001435 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001436 const uint64_t start_ns = NanoTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001437 // Trim the managed spaces.
1438 uint64_t total_alloc_space_allocated = 0;
1439 uint64_t total_alloc_space_size = 0;
1440 uint64_t managed_reclaimed = 0;
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001441 {
1442 ScopedObjectAccess soa(self);
1443 for (const auto& space : continuous_spaces_) {
1444 if (space->IsMallocSpace()) {
1445 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1446 if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1447 // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1448 // for a long period of time.
1449 managed_reclaimed += malloc_space->Trim();
1450 }
1451 total_alloc_space_size += malloc_space->Size();
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001452 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001453 }
1454 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001455 total_alloc_space_allocated = GetBytesAllocated();
1456 if (large_object_space_ != nullptr) {
1457 total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1458 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07001459 if (bump_pointer_space_ != nullptr) {
1460 total_alloc_space_allocated -= bump_pointer_space_->Size();
1461 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001462 if (region_space_ != nullptr) {
1463 total_alloc_space_allocated -= region_space_->GetBytesAllocated();
1464 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001465 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1466 static_cast<float>(total_alloc_space_size);
1467 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001468 // We never move things in the native heap, so we can finish the GC at this point.
1469 FinishGC(self, collector::kGcTypeNone);
Ian Rogers872dd822014-10-30 11:19:14 -07001470
Mathieu Chartier590fee92013-09-13 13:46:47 -07001471 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08001472 << ", advised=" << PrettySize(managed_reclaimed) << ") heap. Managed heap utilization of "
1473 << static_cast<int>(100 * managed_utilization) << "%.";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001474}
1475
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001476bool Heap::IsValidObjectAddress(const void* addr) const {
1477 if (addr == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -07001478 return true;
1479 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001480 return IsAligned<kObjectAlignment>(addr) && FindSpaceFromAddress(addr) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001481}
1482
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001483bool Heap::IsNonDiscontinuousSpaceHeapAddress(const void* addr) const {
1484 return FindContinuousSpaceFromAddress(reinterpret_cast<const mirror::Object*>(addr)) != nullptr;
Mathieu Chartierd68ac702014-02-11 14:50:51 -08001485}
1486
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001487bool Heap::IsLiveObjectLocked(ObjPtr<mirror::Object> obj,
1488 bool search_allocation_stack,
1489 bool search_live_stack,
1490 bool sorted) {
1491 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj.Ptr()))) {
Mathieu Chartier15d34022014-02-26 17:16:38 -08001492 return false;
1493 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001494 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj.Ptr())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001495 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001496 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08001497 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001498 return true;
1499 }
1500 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001501 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj.Ptr())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001502 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1503 // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001504 return temp_space_->Contains(obj.Ptr());
Ian Rogers1d54e732013-05-02 21:10:01 -07001505 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001506 if (region_space_ != nullptr && region_space_->HasAddress(obj.Ptr())) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001507 return true;
1508 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001509 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001510 space::DiscontinuousSpace* d_space = nullptr;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001511 if (c_space != nullptr) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001512 if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001513 return true;
1514 }
1515 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001516 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001517 if (d_space != nullptr) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001518 if (d_space->GetLiveBitmap()->Test(obj.Ptr())) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001519 return true;
1520 }
1521 }
1522 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001523 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001524 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1525 if (i > 0) {
1526 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -07001527 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001528 if (search_allocation_stack) {
1529 if (sorted) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001530 if (allocation_stack_->ContainsSorted(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001531 return true;
1532 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001533 } else if (allocation_stack_->Contains(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001534 return true;
1535 }
1536 }
1537
1538 if (search_live_stack) {
1539 if (sorted) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001540 if (live_stack_->ContainsSorted(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001541 return true;
1542 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001543 } else if (live_stack_->Contains(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001544 return true;
1545 }
1546 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001547 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001548 // We need to check the bitmaps again since there is a race where we mark something as live and
1549 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001550 if (c_space != nullptr) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001551 if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001552 return true;
1553 }
1554 } else {
1555 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001556 if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj.Ptr())) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001557 return true;
1558 }
1559 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001560 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001561}
1562
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001563std::string Heap::DumpSpaces() const {
1564 std::ostringstream oss;
1565 DumpSpaces(oss);
1566 return oss.str();
1567}
1568
1569void Heap::DumpSpaces(std::ostream& stream) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001570 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001571 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1572 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001573 stream << space << " " << *space << "\n";
1574 if (live_bitmap != nullptr) {
1575 stream << live_bitmap << " " << *live_bitmap << "\n";
1576 }
1577 if (mark_bitmap != nullptr) {
1578 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1579 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001580 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001581 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001582 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001583 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001584}
1585
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001586void Heap::VerifyObjectBody(ObjPtr<mirror::Object> obj) {
Stephen Hines22c6a812014-07-16 11:03:43 -07001587 if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1588 return;
1589 }
1590
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001591 // Ignore early dawn of the universe verifications.
Orion Hodson88591fe2018-03-06 13:35:43 +00001592 if (UNLIKELY(num_bytes_allocated_.load(std::memory_order_relaxed) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001593 return;
1594 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001595 CHECK_ALIGNED(obj.Ptr(), kObjectAlignment) << "Object isn't aligned";
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001596 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
Mathieu Chartier4e305412014-02-19 10:54:44 -08001597 CHECK(c != nullptr) << "Null class in object " << obj;
Roland Levillain14d90572015-07-16 10:52:26 +01001598 CHECK_ALIGNED(c, kObjectAlignment) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001599 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001600
Mathieu Chartier4e305412014-02-19 10:54:44 -08001601 if (verify_object_mode_ > kVerifyObjectModeFast) {
1602 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001603 CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001604 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001605}
1606
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001607void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001608 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001609 auto visitor = [&](mirror::Object* obj) {
1610 VerifyObjectBody(obj);
1611 };
1612 // Technically we need the mutator lock here to call Visit. However, VerifyObjectBody is already
1613 // NO_THREAD_SAFETY_ANALYSIS.
1614 auto no_thread_safety_analysis = [&]() NO_THREAD_SAFETY_ANALYSIS {
1615 GetLiveBitmap()->Visit(visitor);
1616 };
1617 no_thread_safety_analysis();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001618}
1619
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001620void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
Mathieu Chartier601276a2014-03-20 15:12:30 -07001621 // Use signed comparison since freed bytes can be negative when background compaction foreground
1622 // transitions occurs. This is caused by the moving objects from a bump pointer space to a
1623 // free list backed space typically increasing memory footprint due to padding and binning.
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001624 RACING_DCHECK_LE(freed_bytes,
1625 static_cast<int64_t>(num_bytes_allocated_.load(std::memory_order_relaxed)));
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001626 // Note: This relies on 2s complement for handling negative freed_bytes.
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001627 num_bytes_allocated_.fetch_sub(static_cast<ssize_t>(freed_bytes), std::memory_order_relaxed);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001628 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001629 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001630 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001631 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001632 // TODO: Do this concurrently.
1633 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1634 global_stats->freed_objects += freed_objects;
1635 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001636 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001637}
1638
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001639void Heap::RecordFreeRevoke() {
1640 // Subtract num_bytes_freed_revoke_ from num_bytes_allocated_ to cancel out the
Roland Levillainef012222017-06-21 16:28:06 +01001641 // ahead-of-time, bulk counting of bytes allocated in rosalloc thread-local buffers.
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001642 // If there's a concurrent revoke, ok to not necessarily reset num_bytes_freed_revoke_
1643 // all the way to zero exactly as the remainder will be subtracted at the next GC.
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001644 size_t bytes_freed = num_bytes_freed_revoke_.load(std::memory_order_relaxed);
1645 CHECK_GE(num_bytes_freed_revoke_.fetch_sub(bytes_freed, std::memory_order_relaxed),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001646 bytes_freed) << "num_bytes_freed_revoke_ underflow";
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001647 CHECK_GE(num_bytes_allocated_.fetch_sub(bytes_freed, std::memory_order_relaxed),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001648 bytes_freed) << "num_bytes_allocated_ underflow";
1649 GetCurrentGcIteration()->SetFreedRevoke(bytes_freed);
1650}
1651
Zuo Wangf37a88b2014-07-10 04:26:41 -07001652space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001653 if (rosalloc_space_ != nullptr && rosalloc_space_->GetRosAlloc() == rosalloc) {
1654 return rosalloc_space_;
1655 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001656 for (const auto& space : continuous_spaces_) {
1657 if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1658 if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1659 return space->AsContinuousSpace()->AsRosAllocSpace();
1660 }
1661 }
1662 }
1663 return nullptr;
1664}
1665
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001666static inline bool EntrypointsInstrumented() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001667 instrumentation::Instrumentation* const instrumentation =
1668 Runtime::Current()->GetInstrumentation();
1669 return instrumentation != nullptr && instrumentation->AllocEntrypointsInstrumented();
1670}
1671
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001672mirror::Object* Heap::AllocateInternalWithGc(Thread* self,
1673 AllocatorType allocator,
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001674 bool instrumented,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001675 size_t alloc_size,
1676 size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001677 size_t* usable_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001678 size_t* bytes_tl_bulk_allocated,
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001679 ObjPtr<mirror::Class>* klass) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001680 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierf4f38432014-09-03 11:21:08 -07001681 // Make sure there is no pending exception since we may need to throw an OOME.
1682 self->AssertNoPendingException();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001683 DCHECK(klass != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001684 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001685 HandleWrapperObjPtr<mirror::Class> h(hs.NewHandleWrapper(klass));
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001686 // The allocation failed. If the GC is running, block until it completes, and then retry the
1687 // allocation.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001688 collector::GcType last_gc = WaitForGcToComplete(kGcCauseForAlloc, self);
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001689 // If we were the default allocator but the allocator changed while we were suspended,
1690 // abort the allocation.
1691 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1692 (!instrumented && EntrypointsInstrumented())) {
1693 return nullptr;
1694 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001695 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001696 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001697 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001698 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001699 if (ptr != nullptr) {
1700 return ptr;
1701 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001702 }
1703
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001704 collector::GcType tried_type = next_gc_type_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001705 const bool gc_ran =
1706 CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001707 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1708 (!instrumented && EntrypointsInstrumented())) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001709 return nullptr;
1710 }
1711 if (gc_ran) {
1712 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001713 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001714 if (ptr != nullptr) {
1715 return ptr;
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001716 }
1717 }
1718
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001719 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001720 for (collector::GcType gc_type : gc_plan_) {
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001721 if (gc_type == tried_type) {
1722 continue;
1723 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001724 // Attempt to run the collector, if we succeed, re-try the allocation.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001725 const bool plan_gc_ran =
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001726 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001727 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1728 (!instrumented && EntrypointsInstrumented())) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001729 return nullptr;
1730 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001731 if (plan_gc_ran) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001732 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001733 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001734 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001735 if (ptr != nullptr) {
1736 return ptr;
1737 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001738 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001739 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001740 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001741 // Try harder, growing the heap if necessary.
1742 mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001743 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001744 if (ptr != nullptr) {
1745 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001746 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001747 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1748 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1749 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1750 // OOME.
1751 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1752 << " allocation";
1753 // TODO: Run finalization, but this may cause more allocations to occur.
1754 // We don't need a WaitForGcToComplete here either.
1755 DCHECK(!gc_plan_.empty());
1756 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001757 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1758 (!instrumented && EntrypointsInstrumented())) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001759 return nullptr;
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001760 }
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001761 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size,
1762 bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001763 if (ptr == nullptr) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001764 const uint64_t current_time = NanoTime();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001765 switch (allocator) {
1766 case kAllocatorTypeRosAlloc:
1767 // Fall-through.
1768 case kAllocatorTypeDlMalloc: {
1769 if (use_homogeneous_space_compaction_for_oom_ &&
1770 current_time - last_time_homogeneous_space_compaction_by_oom_ >
1771 min_interval_homogeneous_space_compaction_by_oom_) {
1772 last_time_homogeneous_space_compaction_by_oom_ = current_time;
1773 HomogeneousSpaceCompactResult result = PerformHomogeneousSpaceCompact();
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001774 // Thread suspension could have occurred.
1775 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1776 (!instrumented && EntrypointsInstrumented())) {
1777 return nullptr;
1778 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001779 switch (result) {
1780 case HomogeneousSpaceCompactResult::kSuccess:
1781 // If the allocation succeeded, we delayed an oom.
1782 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001783 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001784 if (ptr != nullptr) {
1785 count_delayed_oom_++;
1786 }
1787 break;
1788 case HomogeneousSpaceCompactResult::kErrorReject:
1789 // Reject due to disabled moving GC.
1790 break;
1791 case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1792 // Throw OOM by default.
1793 break;
1794 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07001795 UNIMPLEMENTED(FATAL) << "homogeneous space compaction result: "
1796 << static_cast<size_t>(result);
1797 UNREACHABLE();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001798 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001799 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001800 // Always print that we ran homogeneous space compation since this can cause jank.
1801 VLOG(heap) << "Ran heap homogeneous space compaction, "
1802 << " requested defragmentation "
Orion Hodson88591fe2018-03-06 13:35:43 +00001803 << count_requested_homogeneous_space_compaction_.load()
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001804 << " performed defragmentation "
Orion Hodson88591fe2018-03-06 13:35:43 +00001805 << count_performed_homogeneous_space_compaction_.load()
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001806 << " ignored homogeneous space compaction "
Orion Hodson88591fe2018-03-06 13:35:43 +00001807 << count_ignored_homogeneous_space_compaction_.load()
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001808 << " delayed count = "
Orion Hodson88591fe2018-03-06 13:35:43 +00001809 << count_delayed_oom_.load();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001810 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001811 break;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001812 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001813 case kAllocatorTypeNonMoving: {
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07001814 if (kUseReadBarrier) {
1815 // DisableMovingGc() isn't compatible with CC.
1816 break;
1817 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001818 // Try to transition the heap if the allocation failure was due to the space being full.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001819 if (!IsOutOfMemoryOnAllocation(allocator, alloc_size, /*grow=*/ false)) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001820 // If we aren't out of memory then the OOM was probably from the non moving space being
1821 // full. Attempt to disable compaction and turn the main space into a non moving space.
1822 DisableMovingGc();
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001823 // Thread suspension could have occurred.
1824 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1825 (!instrumented && EntrypointsInstrumented())) {
1826 return nullptr;
1827 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001828 // If we are still a moving GC then something must have caused the transition to fail.
1829 if (IsMovingGc(collector_type_)) {
1830 MutexLock mu(self, *gc_complete_lock_);
1831 // If we couldn't disable moving GC, just throw OOME and return null.
1832 LOG(WARNING) << "Couldn't disable moving GC with disable GC count "
1833 << disable_moving_gc_count_;
1834 } else {
1835 LOG(WARNING) << "Disabled moving GC due to the non moving space being full";
1836 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001837 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001838 }
1839 }
1840 break;
1841 }
1842 default: {
1843 // Do nothing for others allocators.
1844 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001845 }
1846 }
1847 // If the allocation hasn't succeeded by this point, throw an OOM error.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001848 if (ptr == nullptr) {
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001849 ThrowOutOfMemoryError(self, alloc_size, allocator);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001850 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001851 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001852}
1853
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001854void Heap::SetTargetHeapUtilization(float target) {
1855 DCHECK_GT(target, 0.0f); // asserted in Java code
1856 DCHECK_LT(target, 1.0f);
1857 target_utilization_ = target;
1858}
1859
Ian Rogers1d54e732013-05-02 21:10:01 -07001860size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001861 Thread* const self = Thread::Current();
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001862 ScopedThreadStateChange tsc(self, kWaitingForGetObjectsAllocated);
Roland Levillainef012222017-06-21 16:28:06 +01001863 // Prevent GC running during GetObjectsAllocated since we may get a checkpoint request that tells
Mathieu Chartiere8649c72017-03-03 18:02:18 -08001864 // us to suspend while we are doing SuspendAll. b/35232978
1865 gc::ScopedGCCriticalSection gcs(Thread::Current(),
1866 gc::kGcCauseGetObjectsAllocated,
1867 gc::kCollectorTypeGetObjectsAllocated);
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001868 // Need SuspendAll here to prevent lock violation if RosAlloc does it during InspectAll.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001869 ScopedSuspendAll ssa(__FUNCTION__);
1870 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001871 size_t total = 0;
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001872 for (space::AllocSpace* space : alloc_spaces_) {
1873 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001874 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001875 return total;
1876}
1877
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001878uint64_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier4edd8472015-06-01 10:47:36 -07001879 uint64_t total = GetObjectsFreedEver();
1880 // If we are detached, we can't use GetObjectsAllocated since we can't change thread states.
1881 if (Thread::Current() != nullptr) {
1882 total += GetObjectsAllocated();
1883 }
1884 return total;
Ian Rogers1d54e732013-05-02 21:10:01 -07001885}
1886
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001887uint64_t Heap::GetBytesAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001888 return GetBytesFreedEver() + GetBytesAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001889}
1890
Richard Uhler660be6f2017-11-22 16:12:29 +00001891// Check whether the given object is an instance of the given class.
1892static bool MatchesClass(mirror::Object* obj,
1893 Handle<mirror::Class> h_class,
1894 bool use_is_assignable_from) REQUIRES_SHARED(Locks::mutator_lock_) {
1895 mirror::Class* instance_class = obj->GetClass();
1896 CHECK(instance_class != nullptr);
1897 ObjPtr<mirror::Class> klass = h_class.Get();
1898 if (use_is_assignable_from) {
1899 return klass != nullptr && klass->IsAssignableFrom(instance_class);
1900 }
1901 return instance_class == klass;
1902}
1903
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001904void Heap::CountInstances(const std::vector<Handle<mirror::Class>>& classes,
1905 bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001906 uint64_t* counts) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001907 auto instance_counter = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001908 for (size_t i = 0; i < classes.size(); ++i) {
Richard Uhler660be6f2017-11-22 16:12:29 +00001909 if (MatchesClass(obj, classes[i], use_is_assignable_from)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001910 ++counts[i];
Elliott Hughes3b78c942013-01-15 17:35:41 -08001911 }
1912 }
Andreas Gampe1c158a02017-07-13 17:26:19 -07001913 };
1914 VisitObjects(instance_counter);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001915}
1916
Andreas Gampe1c158a02017-07-13 17:26:19 -07001917void Heap::GetInstances(VariableSizedHandleScope& scope,
1918 Handle<mirror::Class> h_class,
Richard Uhler660be6f2017-11-22 16:12:29 +00001919 bool use_is_assignable_from,
Andreas Gampe1c158a02017-07-13 17:26:19 -07001920 int32_t max_count,
1921 std::vector<Handle<mirror::Object>>& instances) {
1922 DCHECK_GE(max_count, 0);
1923 auto instance_collector = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Richard Uhler660be6f2017-11-22 16:12:29 +00001924 if (MatchesClass(obj, h_class, use_is_assignable_from)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001925 if (max_count == 0 || instances.size() < static_cast<size_t>(max_count)) {
1926 instances.push_back(scope.NewHandle(obj));
1927 }
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001928 }
Andreas Gampe1c158a02017-07-13 17:26:19 -07001929 };
1930 VisitObjects(instance_collector);
1931}
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001932
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001933void Heap::GetReferringObjects(VariableSizedHandleScope& scope,
1934 Handle<mirror::Object> o,
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001935 int32_t max_count,
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001936 std::vector<Handle<mirror::Object>>& referring_objects) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001937 class ReferringObjectsFinder {
1938 public:
1939 ReferringObjectsFinder(VariableSizedHandleScope& scope_in,
1940 Handle<mirror::Object> object_in,
1941 int32_t max_count_in,
1942 std::vector<Handle<mirror::Object>>& referring_objects_in)
1943 REQUIRES_SHARED(Locks::mutator_lock_)
1944 : scope_(scope_in),
1945 object_(object_in),
1946 max_count_(max_count_in),
1947 referring_objects_(referring_objects_in) {}
1948
1949 // For Object::VisitReferences.
1950 void operator()(ObjPtr<mirror::Object> obj,
1951 MemberOffset offset,
1952 bool is_static ATTRIBUTE_UNUSED) const
1953 REQUIRES_SHARED(Locks::mutator_lock_) {
1954 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
1955 if (ref == object_.Get() && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1956 referring_objects_.push_back(scope_.NewHandle(obj));
1957 }
1958 }
1959
1960 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1961 const {}
1962 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1963
1964 private:
1965 VariableSizedHandleScope& scope_;
1966 Handle<mirror::Object> const object_;
1967 const uint32_t max_count_;
1968 std::vector<Handle<mirror::Object>>& referring_objects_;
1969 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1970 };
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001971 ReferringObjectsFinder finder(scope, o, max_count, referring_objects);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001972 auto referring_objects_finder = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1973 obj->VisitReferences(finder, VoidFunctor());
1974 };
1975 VisitObjects(referring_objects_finder);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001976}
1977
Andreas Gampe94c589d2017-12-27 12:43:01 -08001978void Heap::CollectGarbage(bool clear_soft_references, GcCause cause) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001979 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1980 // last GC will not have necessarily been cleared.
Andreas Gampe94c589d2017-12-27 12:43:01 -08001981 CollectGarbageInternal(gc_plan_.back(), cause, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001982}
1983
Mathieu Chartierdb00eaf2015-08-31 17:10:05 -07001984bool Heap::SupportHomogeneousSpaceCompactAndCollectorTransitions() const {
1985 return main_space_backup_.get() != nullptr && main_space_ != nullptr &&
1986 foreground_collector_type_ == kCollectorTypeCMS;
1987}
1988
Zuo Wangf37a88b2014-07-10 04:26:41 -07001989HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
1990 Thread* self = Thread::Current();
1991 // Inc requested homogeneous space compaction.
1992 count_requested_homogeneous_space_compaction_++;
1993 // Store performed homogeneous space compaction at a new request arrival.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001994 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Yi Konge11d50f2018-01-09 16:55:04 -08001995 // TODO: Clang prebuilt for r316199 produces bogus thread safety analysis warning for holding both
1996 // exclusive and shared lock in the same scope. Remove the assertion as a temporary workaround.
1997 // http://b/71769596
1998 // Locks::mutator_lock_->AssertNotHeld(self);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001999 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002000 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002001 MutexLock mu(self, *gc_complete_lock_);
2002 // Ensure there is only one GC at a time.
2003 WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
Roland Levillain2ae376f2018-01-30 11:35:11 +00002004 // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable
2005 // count is non zero.
2006 // If the collector type changed to something which doesn't benefit from homogeneous space
2007 // compaction, exit.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002008 if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
2009 !main_space_->CanMoveObjects()) {
Mathieu Chartierdb00eaf2015-08-31 17:10:05 -07002010 return kErrorReject;
2011 }
2012 if (!SupportHomogeneousSpaceCompactAndCollectorTransitions()) {
2013 return kErrorUnsupported;
Zuo Wangf37a88b2014-07-10 04:26:41 -07002014 }
2015 collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
2016 }
2017 if (Runtime::Current()->IsShuttingDown(self)) {
2018 // Don't allow heap transitions to happen if the runtime is shutting down since these can
2019 // cause objects to get finalized.
2020 FinishGC(self, collector::kGcTypeNone);
2021 return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
2022 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002023 collector::GarbageCollector* collector;
2024 {
2025 ScopedSuspendAll ssa(__FUNCTION__);
2026 uint64_t start_time = NanoTime();
2027 // Launch compaction.
2028 space::MallocSpace* to_space = main_space_backup_.release();
2029 space::MallocSpace* from_space = main_space_;
2030 to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2031 const uint64_t space_size_before_compaction = from_space->Size();
2032 AddSpace(to_space);
2033 // Make sure that we will have enough room to copy.
2034 CHECK_GE(to_space->GetFootprintLimit(), from_space->GetFootprintLimit());
2035 collector = Compact(to_space, from_space, kGcCauseHomogeneousSpaceCompact);
2036 const uint64_t space_size_after_compaction = to_space->Size();
2037 main_space_ = to_space;
2038 main_space_backup_.reset(from_space);
2039 RemoveSpace(from_space);
2040 SetSpaceAsDefault(main_space_); // Set as default to reset the proper dlmalloc space.
2041 // Update performed homogeneous space compaction count.
2042 count_performed_homogeneous_space_compaction_++;
2043 // Print statics log and resume all threads.
2044 uint64_t duration = NanoTime() - start_time;
2045 VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
2046 << PrettySize(space_size_before_compaction) << " -> "
2047 << PrettySize(space_size_after_compaction) << " compact-ratio: "
2048 << std::fixed << static_cast<double>(space_size_after_compaction) /
2049 static_cast<double>(space_size_before_compaction);
2050 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07002051 // Finish GC.
Mathieu Chartier3cf22532015-07-09 15:15:09 -07002052 reference_processor_->EnqueueClearedReferences(self);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002053 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002054 LogGC(kGcCauseHomogeneousSpaceCompact, collector);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002055 FinishGC(self, collector::kGcTypeFull);
Mathieu Chartier598302a2015-09-23 14:52:39 -07002056 {
2057 ScopedObjectAccess soa(self);
2058 soa.Vm()->UnloadNativeLibraries();
2059 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07002060 return HomogeneousSpaceCompactResult::kSuccess;
2061}
2062
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002063void Heap::TransitionCollector(CollectorType collector_type) {
2064 if (collector_type == collector_type_) {
2065 return;
2066 }
Hiroshi Yamauchia01d0662016-08-30 17:44:41 -07002067 // Collector transition must not happen with CC
2068 CHECK(!kUseReadBarrier);
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002069 VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
2070 << " -> " << static_cast<int>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002071 uint64_t start_time = NanoTime();
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002072 uint32_t before_allocated = num_bytes_allocated_.load(std::memory_order_relaxed);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002073 Runtime* const runtime = Runtime::Current();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002074 Thread* const self = Thread::Current();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002075 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Yi Konge11d50f2018-01-09 16:55:04 -08002076 // TODO: Clang prebuilt for r316199 produces bogus thread safety analysis warning for holding both
2077 // exclusive and shared lock in the same scope. Remove the assertion as a temporary workaround.
2078 // http://b/71769596
2079 // Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002080 // Busy wait until we can GC (StartGC can fail if we have a non-zero
2081 // compacting_gc_disable_count_, this should rarely occurs).
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002082 for (;;) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002083 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002084 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002085 MutexLock mu(self, *gc_complete_lock_);
2086 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002087 WaitForGcToCompleteLocked(kGcCauseCollectorTransition, self);
Mathieu Chartiere4927f62014-08-23 13:56:03 -07002088 // Currently we only need a heap transition if we switch from a moving collector to a
2089 // non-moving one, or visa versa.
2090 const bool copying_transition = IsMovingGc(collector_type_) != IsMovingGc(collector_type);
Mathieu Chartierb38d4832014-04-10 10:56:55 -07002091 // If someone else beat us to it and changed the collector before we could, exit.
2092 // This is safe to do before the suspend all since we set the collector_type_running_ before
2093 // we exit the loop. If another thread attempts to do the heap transition before we exit,
2094 // then it would get blocked on WaitForGcToCompleteLocked.
2095 if (collector_type == collector_type_) {
2096 return;
2097 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002098 // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
2099 if (!copying_transition || disable_moving_gc_count_ == 0) {
2100 // TODO: Not hard code in semi-space collector?
2101 collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
2102 break;
2103 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002104 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002105 usleep(1000);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002106 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002107 if (runtime->IsShuttingDown(self)) {
Hiroshi Yamauchia6a8d142014-05-12 16:57:33 -07002108 // Don't allow heap transitions to happen if the runtime is shutting down since these can
2109 // cause objects to get finalized.
2110 FinishGC(self, collector::kGcTypeNone);
2111 return;
2112 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002113 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002114 {
2115 ScopedSuspendAll ssa(__FUNCTION__);
2116 switch (collector_type) {
2117 case kCollectorTypeSS: {
2118 if (!IsMovingGc(collector_type_)) {
2119 // Create the bump pointer space from the backup space.
2120 CHECK(main_space_backup_ != nullptr);
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002121 MemMap mem_map = main_space_backup_->ReleaseMemMap();
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002122 // We are transitioning from non moving GC -> moving GC, since we copied from the bump
2123 // pointer space last transition it will be protected.
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002124 CHECK(mem_map.IsValid());
2125 mem_map.Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002126 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space",
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002127 std::move(mem_map));
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002128 AddSpace(bump_pointer_space_);
2129 collector = Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
2130 // Use the now empty main space mem map for the bump pointer temp space.
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002131 mem_map = main_space_->ReleaseMemMap();
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002132 // Unset the pointers just in case.
2133 if (dlmalloc_space_ == main_space_) {
2134 dlmalloc_space_ = nullptr;
2135 } else if (rosalloc_space_ == main_space_) {
2136 rosalloc_space_ = nullptr;
2137 }
2138 // Remove the main space so that we don't try to trim it, this doens't work for debug
2139 // builds since RosAlloc attempts to read the magic number from a protected page.
2140 RemoveSpace(main_space_);
2141 RemoveRememberedSet(main_space_);
2142 delete main_space_; // Delete the space since it has been removed.
2143 main_space_ = nullptr;
2144 RemoveRememberedSet(main_space_backup_.get());
2145 main_space_backup_.reset(nullptr); // Deletes the space.
2146 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002147 std::move(mem_map));
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002148 AddSpace(temp_space_);
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07002149 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002150 break;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002151 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002152 case kCollectorTypeMS:
2153 // Fall through.
2154 case kCollectorTypeCMS: {
2155 if (IsMovingGc(collector_type_)) {
2156 CHECK(temp_space_ != nullptr);
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002157 MemMap mem_map = temp_space_->ReleaseMemMap();
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002158 RemoveSpace(temp_space_);
2159 temp_space_ = nullptr;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002160 mem_map.Protect(PROT_READ | PROT_WRITE);
2161 CreateMainMallocSpace(std::move(mem_map),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002162 kDefaultInitialSize,
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002163 std::min(mem_map.Size(), growth_limit_),
2164 mem_map.Size());
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002165 // Compact to the main space from the bump pointer space, don't need to swap semispaces.
2166 AddSpace(main_space_);
2167 collector = Compact(main_space_, bump_pointer_space_, kGcCauseCollectorTransition);
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002168 mem_map = bump_pointer_space_->ReleaseMemMap();
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002169 RemoveSpace(bump_pointer_space_);
2170 bump_pointer_space_ = nullptr;
2171 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
2172 // Temporarily unprotect the backup mem map so rosalloc can write the debug magic number.
2173 if (kIsDebugBuild && kUseRosAlloc) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002174 mem_map.Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002175 }
2176 main_space_backup_.reset(CreateMallocSpaceFromMemMap(
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002177 std::move(mem_map),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002178 kDefaultInitialSize,
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002179 std::min(mem_map.Size(), growth_limit_),
2180 mem_map.Size(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002181 name,
2182 true));
2183 if (kIsDebugBuild && kUseRosAlloc) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002184 main_space_backup_->GetMemMap()->Protect(PROT_NONE);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002185 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002186 }
2187 break;
2188 }
2189 default: {
2190 LOG(FATAL) << "Attempted to transition to invalid collector type "
2191 << static_cast<size_t>(collector_type);
Elliott Hughesc1896c92018-11-29 11:33:18 -08002192 UNREACHABLE();
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002193 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002194 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002195 ChangeCollector(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002196 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002197 // Can't call into java code with all threads suspended.
Mathieu Chartier3cf22532015-07-09 15:15:09 -07002198 reference_processor_->EnqueueClearedReferences(self);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002199 uint64_t duration = NanoTime() - start_time;
Mathieu Chartierafe49982014-03-27 10:55:04 -07002200 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002201 DCHECK(collector != nullptr);
2202 LogGC(kGcCauseCollectorTransition, collector);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002203 FinishGC(self, collector::kGcTypeFull);
Mathieu Chartier598302a2015-09-23 14:52:39 -07002204 {
2205 ScopedObjectAccess soa(self);
2206 soa.Vm()->UnloadNativeLibraries();
2207 }
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002208 int32_t after_allocated = num_bytes_allocated_.load(std::memory_order_relaxed);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002209 int32_t delta_allocated = before_allocated - after_allocated;
Mathieu Chartier19d46b42014-06-17 15:04:40 -07002210 std::string saved_str;
2211 if (delta_allocated >= 0) {
2212 saved_str = " saved at least " + PrettySize(delta_allocated);
2213 } else {
2214 saved_str = " expanded " + PrettySize(-delta_allocated);
2215 }
Mathieu Chartierf8cb1782016-03-18 18:45:41 -07002216 VLOG(heap) << "Collector transition to " << collector_type << " took "
2217 << PrettyDuration(duration) << saved_str;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002218}
2219
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002220void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002221 // TODO: Only do this with all mutators suspended to avoid races.
2222 if (collector_type != collector_type_) {
2223 collector_type_ = collector_type;
2224 gc_plan_.clear();
2225 switch (collector_type_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002226 case kCollectorTypeCC: {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002227 if (kEnableGenerationalConcurrentCopyingCollection) {
2228 gc_plan_.push_back(collector::kGcTypeSticky);
2229 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002230 gc_plan_.push_back(collector::kGcTypeFull);
2231 if (use_tlab_) {
2232 ChangeAllocator(kAllocatorTypeRegionTLAB);
2233 } else {
2234 ChangeAllocator(kAllocatorTypeRegion);
2235 }
2236 break;
2237 }
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002238 case kCollectorTypeSS: // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002239 case kCollectorTypeGSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002240 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002241 if (use_tlab_) {
2242 ChangeAllocator(kAllocatorTypeTLAB);
2243 } else {
2244 ChangeAllocator(kAllocatorTypeBumpPointer);
2245 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002246 break;
2247 }
2248 case kCollectorTypeMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002249 gc_plan_.push_back(collector::kGcTypeSticky);
2250 gc_plan_.push_back(collector::kGcTypePartial);
2251 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002252 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002253 break;
2254 }
2255 case kCollectorTypeCMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002256 gc_plan_.push_back(collector::kGcTypeSticky);
2257 gc_plan_.push_back(collector::kGcTypePartial);
2258 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002259 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002260 break;
2261 }
2262 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07002263 UNIMPLEMENTED(FATAL);
2264 UNREACHABLE();
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002265 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002266 }
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002267 if (IsGcConcurrent()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002268 concurrent_start_bytes_ =
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002269 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) -
2270 kMinConcurrentRemainingBytes;
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002271 } else {
2272 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002273 }
2274 }
2275}
2276
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002277// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002278class ZygoteCompactingCollector final : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002279 public:
Roland Levillain3887c462015-08-12 18:15:42 +01002280 ZygoteCompactingCollector(gc::Heap* heap, bool is_running_on_memory_tool)
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002281 : SemiSpace(heap, false, "zygote collector"),
2282 bin_live_bitmap_(nullptr),
2283 bin_mark_bitmap_(nullptr),
2284 is_running_on_memory_tool_(is_running_on_memory_tool) {}
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002285
Andreas Gampe0c183382017-07-13 22:26:24 -07002286 void BuildBins(space::ContinuousSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002287 bin_live_bitmap_ = space->GetLiveBitmap();
2288 bin_mark_bitmap_ = space->GetMarkBitmap();
Andreas Gampe0c183382017-07-13 22:26:24 -07002289 uintptr_t prev = reinterpret_cast<uintptr_t>(space->Begin());
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002290 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2291 // Note: This requires traversing the space in increasing order of object addresses.
Andreas Gampe0c183382017-07-13 22:26:24 -07002292 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2293 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
2294 size_t bin_size = object_addr - prev;
2295 // Add the bin consisting of the end of the previous object to the start of the current object.
2296 AddBin(bin_size, prev);
2297 prev = object_addr + RoundUp(obj->SizeOf<kDefaultVerifyFlags>(), kObjectAlignment);
2298 };
2299 bin_live_bitmap_->Walk(visitor);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002300 // Add the last bin which spans after the last object to the end of the space.
Andreas Gampe0c183382017-07-13 22:26:24 -07002301 AddBin(reinterpret_cast<uintptr_t>(space->End()) - prev, prev);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002302 }
2303
2304 private:
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002305 // Maps from bin sizes to locations.
2306 std::multimap<size_t, uintptr_t> bins_;
2307 // Live bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002308 accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002309 // Mark bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002310 accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002311 const bool is_running_on_memory_tool_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002312
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002313 void AddBin(size_t size, uintptr_t position) {
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002314 if (is_running_on_memory_tool_) {
2315 MEMORY_TOOL_MAKE_DEFINED(reinterpret_cast<void*>(position), size);
2316 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002317 if (size != 0) {
2318 bins_.insert(std::make_pair(size, position));
2319 }
2320 }
2321
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002322 bool ShouldSweepSpace(space::ContinuousSpace* space ATTRIBUTE_UNUSED) const override {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002323 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
2324 // allocator.
2325 return false;
2326 }
2327
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002328 mirror::Object* MarkNonForwardedObject(mirror::Object* obj) override
Mathieu Chartier90443472015-07-16 20:32:27 -07002329 REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002330 size_t obj_size = obj->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002331 size_t alloc_size = RoundUp(obj_size, kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08002332 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002333 // Find the smallest bin which we can move obj in.
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002334 auto it = bins_.lower_bound(alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002335 if (it == bins_.end()) {
2336 // No available space in the bins, place it in the target space instead (grows the zygote
2337 // space).
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002338 size_t bytes_allocated, dummy;
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002339 forward_address = to_space_->Alloc(self_, alloc_size, &bytes_allocated, nullptr, &dummy);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002340 if (to_space_live_bitmap_ != nullptr) {
2341 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002342 } else {
2343 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
2344 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002345 }
2346 } else {
2347 size_t size = it->first;
2348 uintptr_t pos = it->second;
2349 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
2350 forward_address = reinterpret_cast<mirror::Object*>(pos);
2351 // Set the live and mark bits so that sweeping system weaks works properly.
2352 bin_live_bitmap_->Set(forward_address);
2353 bin_mark_bitmap_->Set(forward_address);
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002354 DCHECK_GE(size, alloc_size);
2355 // Add a new bin with the remaining space.
2356 AddBin(size - alloc_size, pos + alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002357 }
Roland Levillain05e34f42018-05-24 13:19:05 +00002358 // Copy the object over to its new location.
2359 // Historical note: We did not use `alloc_size` to avoid a Valgrind error.
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002360 memcpy(reinterpret_cast<void*>(forward_address), obj, obj_size);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002361 if (kUseBakerReadBarrier) {
2362 obj->AssertReadBarrierState();
2363 forward_address->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002364 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002365 return forward_address;
2366 }
2367};
2368
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002369void Heap::UnBindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002370 TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002371 for (const auto& space : GetContinuousSpaces()) {
2372 if (space->IsContinuousMemMapAllocSpace()) {
2373 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2374 if (alloc_space->HasBoundBitmaps()) {
2375 alloc_space->UnBindBitmaps();
2376 }
2377 }
2378 }
2379}
2380
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002381void Heap::PreZygoteFork() {
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002382 if (!HasZygoteSpace()) {
2383 // We still want to GC in case there is some unreachable non moving objects that could cause a
2384 // suboptimal bin packing when we compact the zygote space.
2385 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
Mathieu Chartier76ce9172016-01-27 10:44:20 -08002386 // Trim the pages at the end of the non moving space. Trim while not holding zygote lock since
2387 // the trim process may require locking the mutator lock.
2388 non_moving_space_->Trim();
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002389 }
Ian Rogers81d425b2012-09-27 16:03:43 -07002390 Thread* self = Thread::Current();
2391 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002392 // Try to see if we have any Zygote spaces.
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002393 if (HasZygoteSpace()) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002394 return;
2395 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002396 Runtime::Current()->GetInternTable()->AddNewTable();
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002397 Runtime::Current()->GetClassLinker()->MoveClassTableToPreZygote();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002398 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002399 // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
2400 // there.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002401 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002402 const bool same_space = non_moving_space_ == main_space_;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002403 if (kCompactZygote) {
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002404 // Temporarily disable rosalloc verification because the zygote
2405 // compaction will mess up the rosalloc internal metadata.
2406 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002407 ZygoteCompactingCollector zygote_collector(this, is_running_on_memory_tool_);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002408 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08002409 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002410 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
2411 non_moving_space_->Limit());
2412 // Compact the bump pointer space to a new zygote bump pointer space.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002413 bool reset_main_space = false;
2414 if (IsMovingGc(collector_type_)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002415 if (collector_type_ == kCollectorTypeCC) {
2416 zygote_collector.SetFromSpace(region_space_);
2417 } else {
2418 zygote_collector.SetFromSpace(bump_pointer_space_);
2419 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002420 } else {
2421 CHECK(main_space_ != nullptr);
Hiroshi Yamauchid04495e2015-03-11 19:09:07 -07002422 CHECK_NE(main_space_, non_moving_space_)
2423 << "Does not make sense to compact within the same space";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002424 // Copy from the main space.
2425 zygote_collector.SetFromSpace(main_space_);
2426 reset_main_space = true;
2427 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002428 zygote_collector.SetToSpace(&target_space);
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07002429 zygote_collector.SetSwapSemiSpaces(false);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002430 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002431 if (reset_main_space) {
2432 main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2433 madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002434 MemMap mem_map = main_space_->ReleaseMemMap();
Mathieu Chartier31f44142014-04-08 14:40:03 -07002435 RemoveSpace(main_space_);
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002436 space::Space* old_main_space = main_space_;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002437 CreateMainMallocSpace(std::move(mem_map),
2438 kDefaultInitialSize,
2439 std::min(mem_map.Size(), growth_limit_),
2440 mem_map.Size());
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002441 delete old_main_space;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002442 AddSpace(main_space_);
2443 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002444 if (collector_type_ == kCollectorTypeCC) {
2445 region_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07002446 // Evacuated everything out of the region space, clear the mark bitmap.
2447 region_space_->GetMarkBitmap()->Clear();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002448 } else {
2449 bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2450 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002451 }
2452 if (temp_space_ != nullptr) {
2453 CHECK(temp_space_->IsEmpty());
2454 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002455 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2456 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002457 // Update the end and write out image.
2458 non_moving_space_->SetEnd(target_space.End());
2459 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002460 VLOG(heap) << "Create zygote space with size=" << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002461 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002462 // Change the collector to the post zygote one.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002463 ChangeCollector(foreground_collector_type_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002464 // Save the old space so that we can remove it after we complete creating the zygote space.
2465 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002466 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002467 // the remaining available space.
2468 // Remove the old space before creating the zygote space since creating the zygote space sets
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002469 // the old alloc space's bitmaps to null.
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002470 RemoveSpace(old_alloc_space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002471 if (collector::SemiSpace::kUseRememberedSet) {
2472 // Sanity bound check.
2473 FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
2474 // Remove the remembered set for the now zygote space (the old
2475 // non-moving space). Note now that we have compacted objects into
2476 // the zygote space, the data in the remembered set is no longer
2477 // needed. The zygote space will instead have a mod-union table
2478 // from this point on.
2479 RemoveRememberedSet(old_alloc_space);
2480 }
Mathieu Chartier7247af52014-11-19 10:51:42 -08002481 // Remaining space becomes the new non moving space.
2482 zygote_space_ = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName, low_memory_mode_,
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002483 &non_moving_space_);
Mathieu Chartierb363f662014-07-16 13:28:58 -07002484 CHECK(!non_moving_space_->CanMoveObjects());
2485 if (same_space) {
2486 main_space_ = non_moving_space_;
2487 SetSpaceAsDefault(main_space_);
2488 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002489 delete old_alloc_space;
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002490 CHECK(HasZygoteSpace()) << "Failed creating zygote space";
2491 AddSpace(zygote_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002492 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2493 AddSpace(non_moving_space_);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002494 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2495 // Treat all of the objects in the zygote as marked to avoid unnecessary dirty pages. This is
2496 // safe since we mark all of the objects that may reference non immune objects as gray.
2497 zygote_space_->GetLiveBitmap()->VisitMarkedRange(
2498 reinterpret_cast<uintptr_t>(zygote_space_->Begin()),
2499 reinterpret_cast<uintptr_t>(zygote_space_->Limit()),
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002500 [](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002501 CHECK(obj->AtomicSetMarkBit(0, 1));
2502 });
2503 }
2504
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002505 // Create the zygote space mod union table.
2506 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002507 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002508 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002509
2510 if (collector_type_ != kCollectorTypeCC) {
2511 // Set all the cards in the mod-union table since we don't know which objects contain references
2512 // to large objects.
2513 mod_union_table->SetCards();
2514 } else {
Mathieu Chartier55c05f52017-04-11 11:12:28 -07002515 // Make sure to clear the zygote space cards so that we don't dirty pages in the next GC. There
2516 // may be dirty cards from the zygote compaction or reference processing. These cards are not
2517 // necessary to have marked since the zygote space may not refer to any objects not in the
2518 // zygote or image spaces at this point.
2519 mod_union_table->ProcessCards();
2520 mod_union_table->ClearTable();
2521
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002522 // For CC we never collect zygote large objects. This means we do not need to set the cards for
2523 // the zygote mod-union table and we can also clear all of the existing image mod-union tables.
2524 // The existing mod-union tables are only for image spaces and may only reference zygote and
2525 // image objects.
2526 for (auto& pair : mod_union_tables_) {
2527 CHECK(pair.first->IsImageSpace());
2528 CHECK(!pair.first->AsImageSpace()->GetImageHeader().IsAppImage());
2529 accounting::ModUnionTable* table = pair.second;
2530 table->ClearTable();
2531 }
2532 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002533 AddModUnionTable(mod_union_table);
Mathieu Chartierf6c2a272015-06-03 17:32:42 -07002534 large_object_space_->SetAllLargeObjectsAsZygoteObjects(self);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002535 if (collector::SemiSpace::kUseRememberedSet) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002536 // Add a new remembered set for the post-zygote non-moving space.
2537 accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2538 new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2539 non_moving_space_);
2540 CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2541 << "Failed to create post-zygote non-moving space remembered set";
2542 AddRememberedSet(post_zygote_non_moving_space_rem_set);
2543 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002544}
2545
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002546void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002547 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002548 allocation_stack_->Reset();
2549}
2550
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002551void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2552 accounting::ContinuousSpaceBitmap* bitmap2,
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07002553 accounting::LargeObjectBitmap* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07002554 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002555 DCHECK(bitmap1 != nullptr);
2556 DCHECK(bitmap2 != nullptr);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002557 const auto* limit = stack->End();
2558 for (auto* it = stack->Begin(); it != limit; ++it) {
2559 const mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002560 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2561 if (bitmap1->HasAddress(obj)) {
2562 bitmap1->Set(obj);
2563 } else if (bitmap2->HasAddress(obj)) {
2564 bitmap2->Set(obj);
2565 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07002566 DCHECK(large_objects != nullptr);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002567 large_objects->Set(obj);
2568 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07002569 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002570 }
2571}
2572
Mathieu Chartier590fee92013-09-13 13:46:47 -07002573void Heap::SwapSemiSpaces() {
Mathieu Chartier31f44142014-04-08 14:40:03 -07002574 CHECK(bump_pointer_space_ != nullptr);
2575 CHECK(temp_space_ != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002576 std::swap(bump_pointer_space_, temp_space_);
2577}
2578
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002579collector::GarbageCollector* Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2580 space::ContinuousMemMapAllocSpace* source_space,
2581 GcCause gc_cause) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002582 CHECK(kMovingCollector);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002583 if (target_space != source_space) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002584 // Don't swap spaces since this isn't a typical semi space collection.
2585 semi_space_collector_->SetSwapSemiSpaces(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002586 semi_space_collector_->SetFromSpace(source_space);
2587 semi_space_collector_->SetToSpace(target_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002588 semi_space_collector_->Run(gc_cause, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002589 return semi_space_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002590 }
Mathieu Chartierf8e5d8c2018-04-06 13:35:37 -07002591 LOG(FATAL) << "Unsupported";
2592 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002593}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002594
Mathieu Chartier34afcde2017-06-30 15:31:11 -07002595void Heap::TraceHeapSize(size_t heap_size) {
2596 ATRACE_INT("Heap size (KB)", heap_size / KB);
2597}
2598
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07002599collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type,
2600 GcCause gc_cause,
Ian Rogers1d54e732013-05-02 21:10:01 -07002601 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002602 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002603 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002604 // If the heap can't run the GC, silently fail and return that no GC was run.
2605 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002606 case collector::kGcTypePartial: {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002607 if (!HasZygoteSpace()) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002608 return collector::kGcTypeNone;
2609 }
2610 break;
2611 }
2612 default: {
2613 // Other GC types don't have any special cases which makes them not runnable. The main case
2614 // here is full GC.
2615 }
2616 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002617 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Yi Konge11d50f2018-01-09 16:55:04 -08002618 // TODO: Clang prebuilt for r316199 produces bogus thread safety analysis warning for holding both
2619 // exclusive and shared lock in the same scope. Remove the assertion as a temporary workaround.
2620 // http://b/71769596
2621 // Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002622 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier50c138f2015-01-07 16:00:03 -08002623 // If we are throwing a stack overflow error we probably don't have enough remaining stack
2624 // space to run the GC.
2625 return collector::kGcTypeNone;
Ian Rogers120f1c72012-09-28 17:17:10 -07002626 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002627 bool compacting_gc;
2628 {
2629 gc_complete_lock_->AssertNotHeld(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002630 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002631 MutexLock mu(self, *gc_complete_lock_);
2632 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002633 WaitForGcToCompleteLocked(gc_cause, self);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002634 compacting_gc = IsMovingGc(collector_type_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002635 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2636 if (compacting_gc && disable_moving_gc_count_ != 0) {
2637 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2638 return collector::kGcTypeNone;
2639 }
Mathieu Chartier51168372015-08-12 16:40:32 -07002640 if (gc_disabled_for_shutdown_) {
2641 return collector::kGcTypeNone;
2642 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002643 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002644 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002645 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2646 ++runtime->GetStats()->gc_for_alloc_count;
2647 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002648 }
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002649 const uint64_t bytes_allocated_before_gc = GetBytesAllocated();
Mathieu Chartier65db8802012-11-20 12:36:46 -08002650
Richard Uhlercaaa2b02017-02-01 09:54:17 +00002651 if (gc_type == NonStickyGcType()) {
2652 // Move all bytes from new_native_bytes_allocated_ to
2653 // old_native_bytes_allocated_ now that GC has been triggered, resetting
2654 // new_native_bytes_allocated_ to zero in the process.
Orion Hodson88591fe2018-03-06 13:35:43 +00002655 old_native_bytes_allocated_.fetch_add(
2656 new_native_bytes_allocated_.exchange(0, std::memory_order_relaxed),
2657 std::memory_order_relaxed);
Richard Uhlercaaa2b02017-02-01 09:54:17 +00002658 }
2659
Ian Rogers1d54e732013-05-02 21:10:01 -07002660 DCHECK_LT(gc_type, collector::kGcTypeMax);
2661 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002662
Mathieu Chartier590fee92013-09-13 13:46:47 -07002663 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08002664 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002665 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002666 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002667 current_allocator_ == kAllocatorTypeTLAB ||
2668 current_allocator_ == kAllocatorTypeRegion ||
2669 current_allocator_ == kAllocatorTypeRegionTLAB);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002670 switch (collector_type_) {
2671 case kCollectorTypeSS:
2672 // Fall-through.
2673 case kCollectorTypeGSS:
2674 semi_space_collector_->SetFromSpace(bump_pointer_space_);
2675 semi_space_collector_->SetToSpace(temp_space_);
2676 semi_space_collector_->SetSwapSemiSpaces(true);
2677 collector = semi_space_collector_;
2678 break;
2679 case kCollectorTypeCC:
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002680 if (kEnableGenerationalConcurrentCopyingCollection) {
2681 // TODO: Other threads must do the flip checkpoint before they start poking at
2682 // active_concurrent_copying_collector_. So we should not concurrency here.
2683 active_concurrent_copying_collector_ = (gc_type == collector::kGcTypeSticky) ?
2684 young_concurrent_copying_collector_ : concurrent_copying_collector_;
2685 active_concurrent_copying_collector_->SetRegionSpace(region_space_);
2686 }
2687 collector = active_concurrent_copying_collector_;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002688 break;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002689 default:
2690 LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002691 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002692 if (collector != active_concurrent_copying_collector_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002693 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Hiroshi Yamauchi6edb9ae2016-02-08 14:18:21 -08002694 if (kIsDebugBuild) {
2695 // Try to read each page of the memory map in case mprotect didn't work properly b/19894268.
2696 temp_space_->GetMemMap()->TryReadable();
2697 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002698 CHECK(temp_space_->IsEmpty());
2699 }
2700 gc_type = collector::kGcTypeFull; // TODO: Not hard code this in.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002701 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2702 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002703 collector = FindCollectorByGcType(gc_type);
Mathieu Chartier50482232013-11-21 11:48:14 -08002704 } else {
2705 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002706 }
Mathieu Chartier08cef222014-10-22 17:18:34 -07002707 if (IsGcConcurrent()) {
2708 // Disable concurrent GC check so that we don't have spammy JNI requests.
2709 // This gets recalculated in GrowForUtilization. It is important that it is disabled /
2710 // calculated in the same thread so that there aren't any races that can cause it to become
2711 // permanantly disabled. b/17942071
2712 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2713 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00002714
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002715 CHECK(collector != nullptr)
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002716 << "Could not find garbage collector with collector_type="
2717 << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002718 collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002719 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2720 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08002721 RequestTrim(self);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002722 // Enqueue cleared references.
Mathieu Chartier3cf22532015-07-09 15:15:09 -07002723 reference_processor_->EnqueueClearedReferences(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002724 // Grow the heap so that we know when to perform the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002725 GrowForUtilization(collector, bytes_allocated_before_gc);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002726 LogGC(gc_cause, collector);
2727 FinishGC(self, gc_type);
2728 // Inform DDMS that a GC completed.
2729 Dbg::GcDidFinish();
Mathieu Chartier598302a2015-09-23 14:52:39 -07002730 // Unload native libraries for class unloading. We do this after calling FinishGC to prevent
2731 // deadlocks in case the JNI_OnUnload function does allocations.
2732 {
2733 ScopedObjectAccess soa(self);
2734 soa.Vm()->UnloadNativeLibraries();
2735 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002736 return gc_type;
2737}
2738
2739void Heap::LogGC(GcCause gc_cause, collector::GarbageCollector* collector) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002740 const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2741 const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002742 // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002743 // (mutator time blocked >= long_pause_log_threshold_).
Mathieu Chartier6bc77742017-04-18 17:46:23 -07002744 bool log_gc = kLogAllGCs || gc_cause == kGcCauseExplicit;
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002745 if (!log_gc && CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002746 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002747 log_gc = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002748 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002749 for (uint64_t pause : pause_times) {
2750 log_gc = log_gc || pause >= long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002751 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002752 }
2753 if (log_gc) {
2754 const size_t percent_free = GetPercentFree();
2755 const size_t current_heap_size = GetBytesAllocated();
2756 const size_t total_memory = GetTotalMemory();
2757 std::ostringstream pause_string;
2758 for (size_t i = 0; i < pause_times.size(); ++i) {
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002759 pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2760 << ((i != pause_times.size() - 1) ? "," : "");
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002761 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002762 LOG(INFO) << gc_cause << " " << collector->GetName()
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002763 << " GC freed " << current_gc_iteration_.GetFreedObjects() << "("
2764 << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2765 << current_gc_iteration_.GetFreedLargeObjects() << "("
2766 << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002767 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2768 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2769 << " total " << PrettyDuration((duration / 1000) * 1000);
Ian Rogersc7dd2952014-10-21 23:31:19 -07002770 VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002771 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002772}
Mathieu Chartiera6399032012-06-11 18:49:50 -07002773
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002774void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2775 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002776 collector_type_running_ = kCollectorTypeNone;
2777 if (gc_type != collector::kGcTypeNone) {
2778 last_gc_type_ = gc_type;
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002779
2780 // Update stats.
2781 ++gc_count_last_window_;
2782 if (running_collection_is_blocking_) {
2783 // If the currently running collection was a blocking one,
2784 // increment the counters and reset the flag.
2785 ++blocking_gc_count_;
2786 blocking_gc_time_ += GetCurrentGcIteration()->GetDurationNs();
2787 ++blocking_gc_count_last_window_;
2788 }
2789 // Update the gc count rate histograms if due.
2790 UpdateGcCountRateHistograms();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002791 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002792 // Reset.
2793 running_collection_is_blocking_ = false;
Mathieu Chartier183009a2017-02-16 21:19:28 -08002794 thread_running_gc_ = nullptr;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002795 // Wake anyone who may have been waiting for the GC to complete.
2796 gc_complete_cond_->Broadcast(self);
2797}
2798
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002799void Heap::UpdateGcCountRateHistograms() {
2800 // Invariant: if the time since the last update includes more than
2801 // one windows, all the GC runs (if > 0) must have happened in first
2802 // window because otherwise the update must have already taken place
2803 // at an earlier GC run. So, we report the non-first windows with
2804 // zero counts to the histograms.
2805 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2806 uint64_t now = NanoTime();
2807 DCHECK_GE(now, last_update_time_gc_count_rate_histograms_);
2808 uint64_t time_since_last_update = now - last_update_time_gc_count_rate_histograms_;
2809 uint64_t num_of_windows = time_since_last_update / kGcCountRateHistogramWindowDuration;
2810 if (time_since_last_update >= kGcCountRateHistogramWindowDuration) {
2811 // Record the first window.
2812 gc_count_rate_histogram_.AddValue(gc_count_last_window_ - 1); // Exclude the current run.
2813 blocking_gc_count_rate_histogram_.AddValue(running_collection_is_blocking_ ?
2814 blocking_gc_count_last_window_ - 1 : blocking_gc_count_last_window_);
2815 // Record the other windows (with zero counts).
2816 for (uint64_t i = 0; i < num_of_windows - 1; ++i) {
2817 gc_count_rate_histogram_.AddValue(0);
2818 blocking_gc_count_rate_histogram_.AddValue(0);
2819 }
2820 // Update the last update time and reset the counters.
2821 last_update_time_gc_count_rate_histograms_ =
2822 (now / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
2823 gc_count_last_window_ = 1; // Include the current run.
2824 blocking_gc_count_last_window_ = running_collection_is_blocking_ ? 1 : 0;
2825 }
2826 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2827}
2828
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002829class RootMatchesObjectVisitor : public SingleRootVisitor {
2830 public:
2831 explicit RootMatchesObjectVisitor(const mirror::Object* obj) : obj_(obj) { }
2832
2833 void VisitRoot(mirror::Object* root, const RootInfo& info)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002834 override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002835 if (root == obj_) {
2836 LOG(INFO) << "Object " << obj_ << " is a root " << info.ToString();
2837 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002838 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002839
2840 private:
2841 const mirror::Object* const obj_;
2842};
2843
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002844
2845class ScanVisitor {
2846 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07002847 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002848 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002849 }
2850};
2851
Ian Rogers1d54e732013-05-02 21:10:01 -07002852// Verify a reference from an object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002853class VerifyReferenceVisitor : public SingleRootVisitor {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002854 public:
Orion Hodson4a01cc32018-03-26 15:46:18 +01002855 VerifyReferenceVisitor(Thread* self, Heap* heap, size_t* fail_count, bool verify_referent)
Andreas Gampe351c4472017-07-12 19:32:55 -07002856 REQUIRES_SHARED(Locks::mutator_lock_)
Orion Hodson4a01cc32018-03-26 15:46:18 +01002857 : self_(self), heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
2858 CHECK_EQ(self_, Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002859 }
2860
Mathieu Chartier31e88222016-10-14 18:43:19 -07002861 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002862 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002863 if (verify_referent_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002864 VerifyReference(ref.Ptr(), ref->GetReferent(), mirror::Reference::ReferentOffset());
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002865 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08002866 }
2867
Mathieu Chartier31e88222016-10-14 18:43:19 -07002868 void operator()(ObjPtr<mirror::Object> obj,
2869 MemberOffset offset,
2870 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002871 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002872 VerifyReference(obj.Ptr(), obj->GetFieldObject<mirror::Object>(offset), offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08002873 }
2874
Mathieu Chartier31e88222016-10-14 18:43:19 -07002875 bool IsLive(ObjPtr<mirror::Object> obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002876 return heap_->IsLiveObjectLocked(obj, true, false, true);
2877 }
2878
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002879 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002880 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002881 if (!root->IsNull()) {
2882 VisitRoot(root);
2883 }
2884 }
2885 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002886 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002887 const_cast<VerifyReferenceVisitor*>(this)->VisitRoot(
2888 root->AsMirrorPtr(), RootInfo(kRootVMInternal));
2889 }
2890
Roland Levillainf73caca2018-08-24 17:19:07 +01002891 void VisitRoot(mirror::Object* root, const RootInfo& root_info) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002892 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002893 if (root == nullptr) {
2894 LOG(ERROR) << "Root is null with info " << root_info.GetType();
2895 } else if (!VerifyReference(nullptr, root, MemberOffset(0))) {
David Sehr709b0702016-10-13 09:12:37 -07002896 LOG(ERROR) << "Root " << root << " is dead with type " << mirror::Object::PrettyTypeOf(root)
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002897 << " thread_id= " << root_info.GetThreadId() << " root_type= " << root_info.GetType();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002898 }
2899 }
2900
2901 private:
Mathieu Chartier407f7022014-02-18 14:37:05 -08002902 // TODO: Fix the no thread safety analysis.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002903 // Returns false on failure.
2904 bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002905 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002906 if (ref == nullptr || IsLive(ref)) {
2907 // Verify that the reference is live.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002908 return true;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002909 }
Orion Hodson4a01cc32018-03-26 15:46:18 +01002910 CHECK_EQ(self_, Thread::Current()); // fail_count_ is private to the calling thread.
2911 *fail_count_ += 1;
2912 if (*fail_count_ == 1) {
2913 // Only print message for the first failure to prevent spam.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002914 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002915 }
2916 if (obj != nullptr) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002917 // Only do this part for non roots.
Ian Rogers1d54e732013-05-02 21:10:01 -07002918 accounting::CardTable* card_table = heap_->GetCardTable();
2919 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2920 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Ian Rogers13735952014-10-08 12:43:28 -07002921 uint8_t* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002922 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2923 << offset << "\n card value = " << static_cast<int>(*card_addr);
2924 if (heap_->IsValidObjectAddress(obj->GetClass())) {
David Sehr709b0702016-10-13 09:12:37 -07002925 LOG(ERROR) << "Obj type " << obj->PrettyTypeOf();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002926 } else {
2927 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002928 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002929
Mathieu Chartierb363f662014-07-16 13:28:58 -07002930 // Attempt to find the class inside of the recently freed objects.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002931 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2932 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2933 space::MallocSpace* space = ref_space->AsMallocSpace();
2934 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2935 if (ref_class != nullptr) {
2936 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
David Sehr709b0702016-10-13 09:12:37 -07002937 << ref_class->PrettyClass();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002938 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002939 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002940 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002941 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002942
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002943 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2944 ref->GetClass()->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002945 LOG(ERROR) << "Ref type " << ref->PrettyTypeOf();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002946 } else {
2947 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2948 << ") is not a valid heap address";
2949 }
2950
Ian Rogers13735952014-10-08 12:43:28 -07002951 card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002952 void* cover_begin = card_table->AddrFromCard(card_addr);
2953 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2954 accounting::CardTable::kCardSize);
2955 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2956 << "-" << cover_end;
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002957 accounting::ContinuousSpaceBitmap* bitmap =
2958 heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002959
2960 if (bitmap == nullptr) {
2961 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08002962 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002963 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002964 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002965 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07002966 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002967 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002968 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2969 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002970 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002971 LOG(ERROR) << "Object " << obj << " found in allocation stack";
2972 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002973 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002974 LOG(ERROR) << "Object " << obj << " found in live stack";
2975 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002976 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2977 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2978 }
2979 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2980 LOG(ERROR) << "Ref " << ref << " found in live stack";
2981 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002982 // Attempt to see if the card table missed the reference.
2983 ScanVisitor scan_visitor;
Ian Rogers13735952014-10-08 12:43:28 -07002984 uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
Lei Li727b2942015-01-15 11:26:34 +08002985 card_table->Scan<false>(bitmap, byte_cover_begin,
2986 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002987 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002988
2989 // Search to see if any of the roots reference our object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002990 RootMatchesObjectVisitor visitor1(obj);
2991 Runtime::Current()->VisitRoots(&visitor1);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002992 // Search to see if any of the roots reference our reference.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002993 RootMatchesObjectVisitor visitor2(ref);
2994 Runtime::Current()->VisitRoots(&visitor2);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002995 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002996 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002997 }
2998
Orion Hodson4a01cc32018-03-26 15:46:18 +01002999 Thread* const self_;
Ian Rogers1d54e732013-05-02 21:10:01 -07003000 Heap* const heap_;
Orion Hodson4a01cc32018-03-26 15:46:18 +01003001 size_t* const fail_count_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003002 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003003};
3004
Ian Rogers1d54e732013-05-02 21:10:01 -07003005// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003006class VerifyObjectVisitor {
3007 public:
Orion Hodson4a01cc32018-03-26 15:46:18 +01003008 VerifyObjectVisitor(Thread* self, Heap* heap, size_t* fail_count, bool verify_referent)
3009 : self_(self), heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003010
Andreas Gampe351c4472017-07-12 19:32:55 -07003011 void operator()(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003012 // Note: we are verifying the references in obj but not obj itself, this is because obj must
3013 // be live or else how did we find it in the live bitmap?
Orion Hodson4a01cc32018-03-26 15:46:18 +01003014 VerifyReferenceVisitor visitor(self_, heap_, fail_count_, verify_referent_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07003015 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07003016 obj->VisitReferences(visitor, visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003017 }
3018
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003019 void VerifyRoots() REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003020 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Orion Hodson4a01cc32018-03-26 15:46:18 +01003021 VerifyReferenceVisitor visitor(self_, heap_, fail_count_, verify_referent_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003022 Runtime::Current()->VisitRoots(&visitor);
3023 }
3024
Orion Hodson4a01cc32018-03-26 15:46:18 +01003025 uint32_t GetFailureCount() const REQUIRES(Locks::mutator_lock_) {
3026 CHECK_EQ(self_, Thread::Current());
3027 return *fail_count_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003028 }
3029
3030 private:
Orion Hodson4a01cc32018-03-26 15:46:18 +01003031 Thread* const self_;
Ian Rogers1d54e732013-05-02 21:10:01 -07003032 Heap* const heap_;
Orion Hodson4a01cc32018-03-26 15:46:18 +01003033 size_t* const fail_count_;
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07003034 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003035};
3036
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003037void Heap::PushOnAllocationStackWithInternalGC(Thread* self, ObjPtr<mirror::Object>* obj) {
Mathieu Chartierc1790162014-05-23 10:54:50 -07003038 // Slow path, the allocation stack push back must have already failed.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003039 DCHECK(!allocation_stack_->AtomicPushBack(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07003040 do {
3041 // TODO: Add handle VerifyObject.
3042 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003043 HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Hans Boehmd972b422017-09-11 12:57:00 -07003044 // Push our object into the reserve region of the allocation stack. This is only required due
Mathieu Chartierc1790162014-05-23 10:54:50 -07003045 // to heap verification requiring that roots are live (either in the live bitmap or in the
3046 // allocation stack).
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003047 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07003048 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003049 } while (!allocation_stack_->AtomicPushBack(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07003050}
3051
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003052void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self,
3053 ObjPtr<mirror::Object>* obj) {
Mathieu Chartierc1790162014-05-23 10:54:50 -07003054 // Slow path, the allocation stack push back must have already failed.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003055 DCHECK(!self->PushOnThreadLocalAllocationStack(obj->Ptr()));
Mathieu Chartiercb535da2015-01-23 13:50:03 -08003056 StackReference<mirror::Object>* start_address;
3057 StackReference<mirror::Object>* end_address;
Mathieu Chartierc1790162014-05-23 10:54:50 -07003058 while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
3059 &end_address)) {
3060 // TODO: Add handle VerifyObject.
3061 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003062 HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Mathieu Chartierc1790162014-05-23 10:54:50 -07003063 // Push our object into the reserve region of the allocaiton stack. This is only required due
3064 // to heap verification requiring that roots are live (either in the live bitmap or in the
3065 // allocation stack).
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003066 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07003067 // Push into the reserve allocation stack.
3068 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
3069 }
3070 self->SetThreadLocalAllocationStack(start_address, end_address);
3071 // Retry on the new thread-local allocation stack.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003072 CHECK(self->PushOnThreadLocalAllocationStack(obj->Ptr())); // Must succeed.
Mathieu Chartierc1790162014-05-23 10:54:50 -07003073}
3074
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003075// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003076size_t Heap::VerifyHeapReferences(bool verify_referents) {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003077 Thread* self = Thread::Current();
3078 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003079 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07003080 allocation_stack_->Sort();
3081 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003082 // Since we sorted the allocation stack content, need to revoke all
3083 // thread-local allocation stacks.
3084 RevokeAllThreadLocalAllocationStacks(self);
Orion Hodson4a01cc32018-03-26 15:46:18 +01003085 size_t fail_count = 0;
3086 VerifyObjectVisitor visitor(self, this, &fail_count, verify_referents);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07003087 // Verify objects in the allocation stack since these will be objects which were:
3088 // 1. Allocated prior to the GC (pre GC verification).
3089 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07003090 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003091 // pointing to dead objects if they are not reachable.
Andreas Gampe351c4472017-07-12 19:32:55 -07003092 VisitObjectsPaused(visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003093 // Verify the roots:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003094 visitor.VerifyRoots();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003095 if (visitor.GetFailureCount() > 0) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07003096 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003097 for (const auto& table_pair : mod_union_tables_) {
3098 accounting::ModUnionTable* mod_union_table = table_pair.second;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003099 mod_union_table->Dump(LOG_STREAM(ERROR) << mod_union_table->GetName() << ": ");
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003100 }
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003101 // Dump remembered sets.
3102 for (const auto& table_pair : remembered_sets_) {
3103 accounting::RememberedSet* remembered_set = table_pair.second;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003104 remembered_set->Dump(LOG_STREAM(ERROR) << remembered_set->GetName() << ": ");
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003105 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003106 DumpSpaces(LOG_STREAM(ERROR));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003107 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003108 return visitor.GetFailureCount();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003109}
3110
3111class VerifyReferenceCardVisitor {
3112 public:
3113 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003114 REQUIRES_SHARED(Locks::mutator_lock_,
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003115 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07003116 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003117 }
3118
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003119 // There is no card marks for native roots on a class.
3120 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
3121 const {}
3122 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
3123
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003124 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
3125 // annotalysis on visitors.
Mathieu Chartier407f7022014-02-18 14:37:05 -08003126 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
3127 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07003128 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003129 // Filter out class references since changing an object's class does not mark the card as dirty.
3130 // Also handles large objects, since the only reference they hold is a class reference.
Mathieu Chartier407f7022014-02-18 14:37:05 -08003131 if (ref != nullptr && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003132 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003133 // If the object is not dirty and it is referencing something in the live stack other than
3134 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003135 if (!card_table->AddrIsInCardTable(obj)) {
3136 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
3137 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003138 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08003139 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003140 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
3141 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07003142 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier407f7022014-02-18 14:37:05 -08003143 if (live_stack->ContainsSorted(ref)) {
3144 if (live_stack->ContainsSorted(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003145 LOG(ERROR) << "Object " << obj << " found in live stack";
3146 }
3147 if (heap_->GetLiveBitmap()->Test(obj)) {
3148 LOG(ERROR) << "Object " << obj << " found in live bitmap";
3149 }
David Sehr709b0702016-10-13 09:12:37 -07003150 LOG(ERROR) << "Object " << obj << " " << mirror::Object::PrettyTypeOf(obj)
3151 << " references " << ref << " " << mirror::Object::PrettyTypeOf(ref)
3152 << " in live stack";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003153
3154 // Print which field of the object is dead.
3155 if (!obj->IsObjectArray()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003156 mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003157 CHECK(klass != nullptr);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07003158 for (ArtField& field : (is_static ? klass->GetSFields() : klass->GetIFields())) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003159 if (field.GetOffset().Int32Value() == offset.Int32Value()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003160 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
David Sehr709b0702016-10-13 09:12:37 -07003161 << field.PrettyField();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003162 break;
3163 }
3164 }
3165 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003166 mirror::ObjectArray<mirror::Object>* object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003167 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003168 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
3169 if (object_array->Get(i) == ref) {
3170 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
3171 }
3172 }
3173 }
3174
3175 *failed_ = true;
3176 }
3177 }
3178 }
3179 }
3180
3181 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07003182 Heap* const heap_;
3183 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003184};
3185
3186class VerifyLiveStackReferences {
3187 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07003188 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003189 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07003190 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003191
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003192 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003193 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003194 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07003195 obj->VisitReferences(visitor, VoidFunctor());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003196 }
3197
3198 bool Failed() const {
3199 return failed_;
3200 }
3201
3202 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07003203 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003204 bool failed_;
3205};
3206
3207bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003208 Thread* self = Thread::Current();
3209 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003210 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07003211 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003212 // Since we sorted the allocation stack content, need to revoke all
3213 // thread-local allocation stacks.
3214 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003215 VerifyLiveStackReferences visitor(this);
3216 GetLiveBitmap()->Visit(visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003217 // We can verify objects in the live stack since none of these should reference dead objects.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08003218 for (auto* it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
3219 if (!kUseThreadLocalAllocationStack || it->AsMirrorPtr() != nullptr) {
3220 visitor(it->AsMirrorPtr());
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003221 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003222 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003223 return !visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003224}
3225
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003226void Heap::SwapStacks() {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003227 if (kUseThreadLocalAllocationStack) {
3228 live_stack_->AssertAllZero();
3229 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08003230 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003231}
3232
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003233void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003234 // This must be called only during the pause.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003235 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003236 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
3237 MutexLock mu2(self, *Locks::thread_list_lock_);
3238 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
3239 for (Thread* t : thread_list) {
3240 t->RevokeThreadLocalAllocationStack();
3241 }
3242}
3243
Ian Rogers68d8b422014-07-17 11:09:10 -07003244void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
3245 if (kIsDebugBuild) {
3246 if (rosalloc_space_ != nullptr) {
3247 rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
3248 }
3249 if (bump_pointer_space_ != nullptr) {
3250 bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
3251 }
3252 }
3253}
3254
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003255void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
3256 if (kIsDebugBuild) {
3257 if (bump_pointer_space_ != nullptr) {
3258 bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
3259 }
3260 }
3261}
3262
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003263accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
3264 auto it = mod_union_tables_.find(space);
3265 if (it == mod_union_tables_.end()) {
3266 return nullptr;
3267 }
3268 return it->second;
3269}
3270
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003271accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
3272 auto it = remembered_sets_.find(space);
3273 if (it == remembered_sets_.end()) {
3274 return nullptr;
3275 }
3276 return it->second;
3277}
3278
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003279void Heap::ProcessCards(TimingLogger* timings,
3280 bool use_rem_sets,
3281 bool process_alloc_space_cards,
Lei Li4add3b42015-01-15 11:55:26 +08003282 bool clear_alloc_space_cards) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003283 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003284 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07003285 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003286 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003287 accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003288 if (table != nullptr) {
3289 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
3290 "ImageModUnionClearCards";
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003291 TimingLogger::ScopedTiming t2(name, timings);
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003292 table->ProcessCards();
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003293 } else if (use_rem_sets && rem_set != nullptr) {
3294 DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
3295 << static_cast<int>(collector_type_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003296 TimingLogger::ScopedTiming t2("AllocSpaceRemSetClearCards", timings);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003297 rem_set->ClearCards();
Lei Li4add3b42015-01-15 11:55:26 +08003298 } else if (process_alloc_space_cards) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003299 TimingLogger::ScopedTiming t2("AllocSpaceClearCards", timings);
Lei Li4add3b42015-01-15 11:55:26 +08003300 if (clear_alloc_space_cards) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003301 uint8_t* end = space->End();
3302 if (space->IsImageSpace()) {
3303 // Image space end is the end of the mirror objects, it is not necessarily page or card
3304 // aligned. Align up so that the check in ClearCardRange does not fail.
3305 end = AlignUp(end, accounting::CardTable::kCardSize);
3306 }
3307 card_table_->ClearCardRange(space->Begin(), end);
Lei Li4add3b42015-01-15 11:55:26 +08003308 } else {
3309 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these
3310 // cards were dirty before the GC started.
3311 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
3312 // -> clean(cleaning thread).
3313 // The races are we either end up with: Aged card, unaged card. Since we have the
3314 // checkpoint roots and then we scan / update mod union tables after. We will always
3315 // scan either card. If we end up with the non aged card, we scan it it in the pause.
3316 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
3317 VoidFunctor());
3318 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003319 }
3320 }
3321}
3322
Mathieu Chartier97509952015-07-13 14:35:43 -07003323struct IdentityMarkHeapReferenceVisitor : public MarkObjectVisitor {
Roland Levillainf73caca2018-08-24 17:19:07 +01003324 mirror::Object* MarkObject(mirror::Object* obj) override {
Mathieu Chartier97509952015-07-13 14:35:43 -07003325 return obj;
3326 }
Roland Levillainf73caca2018-08-24 17:19:07 +01003327 void MarkHeapReference(mirror::HeapReference<mirror::Object>*, bool) override {
Mathieu Chartier97509952015-07-13 14:35:43 -07003328 }
3329};
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003330
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003331void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
3332 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003333 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003334 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003335 if (verify_pre_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003336 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003337 size_t failures = VerifyHeapReferences();
3338 if (failures > 0) {
3339 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3340 << " failures";
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003341 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003342 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003343 // Check that all objects which reference things in the live stack are on dirty cards.
3344 if (verify_missing_card_marks_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003345 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyMissingCardMarks", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003346 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003347 SwapStacks();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003348 // Sort the live stack so that we can quickly binary search it later.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003349 CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
3350 << " missing card mark verification failed\n" << DumpSpaces();
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003351 SwapStacks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003352 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003353 if (verify_mod_union_table_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003354 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyModUnionTables", timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003355 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003356 for (const auto& table_pair : mod_union_tables_) {
3357 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier97509952015-07-13 14:35:43 -07003358 IdentityMarkHeapReferenceVisitor visitor;
3359 mod_union_table->UpdateAndMarkReferences(&visitor);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003360 mod_union_table->Verify();
3361 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003362 }
3363}
3364
3365void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier0651d412014-04-29 14:37:57 -07003366 if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
Andreas Gampe4934eb12017-01-30 13:15:26 -08003367 collector::GarbageCollector::ScopedPause pause(gc, false);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003368 PreGcVerificationPaused(gc);
3369 }
3370}
3371
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003372void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc ATTRIBUTE_UNUSED) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003373 // TODO: Add a new runtime option for this?
3374 if (verify_pre_gc_rosalloc_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003375 RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003376 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003377}
3378
Ian Rogers1d54e732013-05-02 21:10:01 -07003379void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003380 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003381 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003382 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003383 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
3384 // reachable objects.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003385 if (verify_pre_sweeping_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003386 TimingLogger::ScopedTiming t2("(Paused)PostSweepingVerifyHeapReferences", timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003387 CHECK_NE(self->GetState(), kRunnable);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003388 {
3389 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3390 // Swapping bound bitmaps does nothing.
3391 gc->SwapBitmaps();
3392 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07003393 // Pass in false since concurrent reference processing can mean that the reference referents
3394 // may point to dead objects at the point which PreSweepingGcVerification is called.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003395 size_t failures = VerifyHeapReferences(false);
3396 if (failures > 0) {
3397 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
3398 << " failures";
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003399 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003400 {
3401 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3402 gc->SwapBitmaps();
3403 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003404 }
3405 if (verify_pre_sweeping_rosalloc_) {
3406 RosAllocVerification(timings, "PreSweepingRosAllocVerification");
3407 }
3408}
3409
3410void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
3411 // Only pause if we have to do some verification.
3412 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003413 TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003414 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003415 if (verify_system_weaks_) {
3416 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3417 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
3418 mark_sweep->VerifySystemWeaks();
3419 }
3420 if (verify_post_gc_rosalloc_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003421 RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003422 }
3423 if (verify_post_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003424 TimingLogger::ScopedTiming t2("(Paused)PostGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003425 size_t failures = VerifyHeapReferences();
3426 if (failures > 0) {
3427 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3428 << " failures";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003429 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003430 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003431}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003432
Ian Rogers1d54e732013-05-02 21:10:01 -07003433void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003434 if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
Andreas Gampe4934eb12017-01-30 13:15:26 -08003435 collector::GarbageCollector::ScopedPause pause(gc, false);
Mathieu Chartierd35326f2014-08-18 15:02:59 -07003436 PostGcVerificationPaused(gc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003437 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003438}
3439
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003440void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003441 TimingLogger::ScopedTiming t(name, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003442 for (const auto& space : continuous_spaces_) {
3443 if (space->IsRosAllocSpace()) {
3444 VLOG(heap) << name << " : " << space->GetName();
3445 space->AsRosAllocSpace()->Verify();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08003446 }
3447 }
3448}
3449
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003450collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08003451 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003452 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003453 return WaitForGcToCompleteLocked(cause, self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003454}
3455
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003456collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003457 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier40112dd2017-06-26 17:49:09 -07003458 GcCause last_gc_cause = kGcCauseNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003459 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08003460 while (collector_type_running_ != kCollectorTypeNone) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003461 if (self != task_processor_->GetRunningThread()) {
3462 // The current thread is about to wait for a currently running
3463 // collection to finish. If the waiting thread is not the heap
3464 // task daemon thread, the currently running collection is
3465 // considered as a blocking GC.
3466 running_collection_is_blocking_ = true;
3467 VLOG(gc) << "Waiting for a blocking GC " << cause;
3468 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08003469 ScopedTrace trace("GC: Wait For Completion");
Mathieu Chartier590fee92013-09-13 13:46:47 -07003470 // We must wait, change thread state then sleep on gc_complete_cond_;
3471 gc_complete_cond_->Wait(self);
3472 last_gc_type = last_gc_type_;
Mathieu Chartier40112dd2017-06-26 17:49:09 -07003473 last_gc_cause = last_gc_cause_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003474 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003475 uint64_t wait_time = NanoTime() - wait_start;
3476 total_wait_time_ += wait_time;
3477 if (wait_time > long_pause_log_threshold_) {
Mathieu Chartier40112dd2017-06-26 17:49:09 -07003478 LOG(INFO) << "WaitForGcToComplete blocked " << cause << " on " << last_gc_cause << " for "
3479 << PrettyDuration(wait_time);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003480 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003481 if (self != task_processor_->GetRunningThread()) {
3482 // The current thread is about to run a collection. If the thread
3483 // is not the heap task daemon thread, it's considered as a
3484 // blocking GC (i.e., blocking itself).
3485 running_collection_is_blocking_ = true;
Mathieu Chartierb166f412017-04-25 16:31:20 -07003486 // Don't log fake "GC" types that are only used for debugger or hidden APIs. If we log these,
3487 // it results in log spam. kGcCauseExplicit is already logged in LogGC, so avoid it here too.
3488 if (cause == kGcCauseForAlloc ||
3489 cause == kGcCauseForNativeAlloc ||
3490 cause == kGcCauseDisableMovingGc) {
3491 VLOG(gc) << "Starting a blocking GC " << cause;
3492 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003493 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07003494 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07003495}
3496
Elliott Hughesc967f782012-04-16 10:23:15 -07003497void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003498 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003499 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07003500 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07003501}
3502
3503size_t Heap::GetPercentFree() {
Mathieu Chartierd30e1d62014-06-09 13:25:22 -07003504 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / max_allowed_footprint_);
Elliott Hughesc967f782012-04-16 10:23:15 -07003505}
3506
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003507void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003508 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003509 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003510 << PrettySize(GetMaxMemory());
3511 max_allowed_footprint = GetMaxMemory();
3512 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07003513 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07003514}
3515
Mathieu Chartier0795f232016-09-27 18:43:30 -07003516bool Heap::IsMovableObject(ObjPtr<mirror::Object> obj) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003517 if (kMovingCollector) {
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07003518 space::Space* space = FindContinuousSpaceFromObject(obj.Ptr(), true);
Mathieu Chartier31f44142014-04-08 14:40:03 -07003519 if (space != nullptr) {
3520 // TODO: Check large object?
3521 return space->CanMoveObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003522 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003523 }
3524 return false;
3525}
3526
Mathieu Chartierafe49982014-03-27 10:55:04 -07003527collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00003528 for (auto* collector : garbage_collectors_) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003529 if (collector->GetCollectorType() == collector_type_ &&
3530 collector->GetGcType() == gc_type) {
3531 return collector;
3532 }
3533 }
3534 return nullptr;
3535}
3536
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003537double Heap::HeapGrowthMultiplier() const {
3538 // If we don't care about pause times we are background, so return 1.0.
Mathieu Chartier11c273d2017-10-15 20:54:45 -07003539 if (!CareAboutPauseTimes()) {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003540 return 1.0;
3541 }
3542 return foreground_heap_growth_multiplier_;
3543}
3544
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003545void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran,
3546 uint64_t bytes_allocated_before_gc) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003547 // We know what our utilization is at this moment.
3548 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003549 const uint64_t bytes_allocated = GetBytesAllocated();
Mathieu Chartier34afcde2017-06-30 15:31:11 -07003550 // Trace the new heap size after the GC is finished.
3551 TraceHeapSize(bytes_allocated);
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003552 uint64_t target_size;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003553 collector::GcType gc_type = collector_ran->GetGcType();
Roland Levillain2ae376f2018-01-30 11:35:11 +00003554 // Use the multiplier to grow more for foreground.
Roland Levillainc5249b82018-08-15 17:43:34 +01003555 const double multiplier = HeapGrowthMultiplier(); // Use the multiplier to grow more for
3556 // foreground.
Hiroshi Yamauchi6711cd82017-02-23 15:11:56 -08003557 const uint64_t adjusted_min_free = static_cast<uint64_t>(min_free_ * multiplier);
3558 const uint64_t adjusted_max_free = static_cast<uint64_t>(max_free_ * multiplier);
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003559 if (gc_type != collector::kGcTypeSticky) {
3560 // Grow the heap for non sticky GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003561 ssize_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
Roland Levillain99bd16b2018-02-21 14:18:15 +00003562 CHECK_GE(delta, 0) << "bytes_allocated=" << bytes_allocated
3563 << " target_utilization_=" << target_utilization_;
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003564 target_size = bytes_allocated + delta * multiplier;
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003565 target_size = std::min(target_size, bytes_allocated + adjusted_max_free);
3566 target_size = std::max(target_size, bytes_allocated + adjusted_min_free);
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003567 next_gc_type_ = collector::kGcTypeSticky;
3568 } else {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003569 collector::GcType non_sticky_gc_type = NonStickyGcType();
Mathieu Chartierafe49982014-03-27 10:55:04 -07003570 // Find what the next non sticky collector will be.
3571 collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003572 if (kEnableGenerationalConcurrentCopyingCollection) {
3573 if (non_sticky_collector == nullptr) {
3574 non_sticky_collector = FindCollectorByGcType(collector::kGcTypePartial);
3575 }
3576 CHECK(non_sticky_collector != nullptr);
3577 }
Mathieu Chartierafe49982014-03-27 10:55:04 -07003578 // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
3579 // do another sticky collection next.
3580 // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
3581 // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
3582 // if the sticky GC throughput always remained >= the full/partial throughput.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003583 if (current_gc_iteration_.GetEstimatedThroughput() * kStickyGcThroughputAdjustment >=
Mathieu Chartierafe49982014-03-27 10:55:04 -07003584 non_sticky_collector->GetEstimatedMeanThroughput() &&
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003585 non_sticky_collector->NumberOfIterations() > 0 &&
Mathieu Chartierafe49982014-03-27 10:55:04 -07003586 bytes_allocated <= max_allowed_footprint_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003587 next_gc_type_ = collector::kGcTypeSticky;
3588 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003589 next_gc_type_ = non_sticky_gc_type;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003590 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003591 // If we have freed enough memory, shrink the heap back down.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003592 if (bytes_allocated + adjusted_max_free < max_allowed_footprint_) {
3593 target_size = bytes_allocated + adjusted_max_free;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003594 } else {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003595 target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003596 }
3597 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003598 if (!ignore_max_footprint_) {
3599 SetIdealFootprint(target_size);
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003600 if (IsGcConcurrent()) {
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003601 const uint64_t freed_bytes = current_gc_iteration_.GetFreedBytes() +
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003602 current_gc_iteration_.GetFreedLargeObjectBytes() +
3603 current_gc_iteration_.GetFreedRevokeBytes();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003604 // Bytes allocated will shrink by freed_bytes after the GC runs, so if we want to figure out
3605 // how many bytes were allocated during the GC we need to add freed_bytes back on.
3606 CHECK_GE(bytes_allocated + freed_bytes, bytes_allocated_before_gc);
3607 const uint64_t bytes_allocated_during_gc = bytes_allocated + freed_bytes -
3608 bytes_allocated_before_gc;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003609 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003610 // Estimate how many remaining bytes we will have when we need to start the next GC.
Lokesh Gidra1144b632018-01-18 10:12:38 -08003611 size_t remaining_bytes = bytes_allocated_during_gc;
Mathieu Chartier74762802014-01-24 10:21:35 -08003612 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003613 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
3614 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
3615 // A never going to happen situation that from the estimated allocation rate we will exceed
3616 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08003617 // another GC nearly straight away.
3618 remaining_bytes = kMinConcurrentRemainingBytes;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003619 }
Mathieu Chartier74762802014-01-24 10:21:35 -08003620 DCHECK_LE(remaining_bytes, max_allowed_footprint_);
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003621 DCHECK_LE(max_allowed_footprint_, GetMaxMemory());
Mathieu Chartier74762802014-01-24 10:21:35 -08003622 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
3623 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
3624 // right away.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003625 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
3626 static_cast<size_t>(bytes_allocated));
Mathieu Chartier65db8802012-11-20 12:36:46 -08003627 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08003628 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003629}
3630
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003631void Heap::ClampGrowthLimit() {
Mathieu Chartierddac4232015-04-02 10:08:03 -07003632 // Use heap bitmap lock to guard against races with BindLiveToMarkBitmap.
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003633 ScopedObjectAccess soa(Thread::Current());
3634 WriterMutexLock mu(soa.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003635 capacity_ = growth_limit_;
3636 for (const auto& space : continuous_spaces_) {
3637 if (space->IsMallocSpace()) {
3638 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3639 malloc_space->ClampGrowthLimit();
3640 }
3641 }
Lokesh Gidra5f0b71a2018-02-06 18:01:35 -08003642 if (collector_type_ == kCollectorTypeCC) {
3643 DCHECK(region_space_ != nullptr);
3644 // Twice the capacity as CC needs extra space for evacuating objects.
3645 region_space_->ClampGrowthLimit(2 * capacity_);
3646 }
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003647 // This space isn't added for performance reasons.
3648 if (main_space_backup_.get() != nullptr) {
3649 main_space_backup_->ClampGrowthLimit();
3650 }
3651}
3652
jeffhaoc1160702011-10-27 15:48:45 -07003653void Heap::ClearGrowthLimit() {
Mathieu Chartiera98a2822017-05-24 16:14:10 -07003654 if (max_allowed_footprint_ == growth_limit_ && growth_limit_ < capacity_) {
3655 max_allowed_footprint_ = capacity_;
3656 concurrent_start_bytes_ =
3657 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) -
3658 kMinConcurrentRemainingBytes;
3659 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -08003660 growth_limit_ = capacity_;
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003661 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0310da52014-12-01 13:40:48 -08003662 for (const auto& space : continuous_spaces_) {
3663 if (space->IsMallocSpace()) {
3664 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3665 malloc_space->ClearGrowthLimit();
3666 malloc_space->SetFootprintLimit(malloc_space->Capacity());
3667 }
3668 }
3669 // This space isn't added for performance reasons.
3670 if (main_space_backup_.get() != nullptr) {
3671 main_space_backup_->ClearGrowthLimit();
3672 main_space_backup_->SetFootprintLimit(main_space_backup_->Capacity());
3673 }
jeffhaoc1160702011-10-27 15:48:45 -07003674}
3675
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003676void Heap::AddFinalizerReference(Thread* self, ObjPtr<mirror::Object>* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003677 ScopedObjectAccess soa(self);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003678 ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
Ian Rogers53b8b092014-03-13 23:45:53 -07003679 jvalue args[1];
3680 args[0].l = arg.get();
3681 InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003682 // Restore object in case it gets moved.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07003683 *object = soa.Decode<mirror::Object>(arg.get());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003684}
3685
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003686void Heap::RequestConcurrentGCAndSaveObject(Thread* self,
3687 bool force_full,
3688 ObjPtr<mirror::Object>* obj) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003689 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003690 HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003691 RequestConcurrentGC(self, kGcCauseBackground, force_full);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003692}
3693
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003694class Heap::ConcurrentGCTask : public HeapTask {
3695 public:
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003696 ConcurrentGCTask(uint64_t target_time, GcCause cause, bool force_full)
3697 : HeapTask(target_time), cause_(cause), force_full_(force_full) {}
Roland Levillainf73caca2018-08-24 17:19:07 +01003698 void Run(Thread* self) override {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003699 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003700 heap->ConcurrentGC(self, cause_, force_full_);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003701 heap->ClearConcurrentGCRequest();
Ian Rogers120f1c72012-09-28 17:17:10 -07003702 }
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003703
3704 private:
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003705 const GcCause cause_;
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003706 const bool force_full_; // If true, force full (or partial) collection.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003707};
3708
Mathieu Chartier90443472015-07-16 20:32:27 -07003709static bool CanAddHeapTask(Thread* self) REQUIRES(!Locks::runtime_shutdown_lock_) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003710 Runtime* runtime = Runtime::Current();
3711 return runtime != nullptr && runtime->IsFinishedStarting() && !runtime->IsShuttingDown(self) &&
3712 !self->IsHandlingStackOverflow();
3713}
3714
3715void Heap::ClearConcurrentGCRequest() {
Orion Hodson88591fe2018-03-06 13:35:43 +00003716 concurrent_gc_pending_.store(false, std::memory_order_relaxed);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003717}
3718
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003719void Heap::RequestConcurrentGC(Thread* self, GcCause cause, bool force_full) {
Mathieu Chartierac195162015-02-20 18:44:28 +00003720 if (CanAddHeapTask(self) &&
Orion Hodson4557b382018-01-03 11:47:54 +00003721 concurrent_gc_pending_.CompareAndSetStrongSequentiallyConsistent(false, true)) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003722 task_processor_->AddTask(self, new ConcurrentGCTask(NanoTime(), // Start straight away.
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003723 cause,
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003724 force_full));
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003725 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003726}
3727
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003728void Heap::ConcurrentGC(Thread* self, GcCause cause, bool force_full) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003729 if (!Runtime::Current()->IsShuttingDown(self)) {
3730 // Wait for any GCs currently running to finish.
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003731 if (WaitForGcToComplete(cause, self) == collector::kGcTypeNone) {
Roland Levillainb81e9e92017-04-20 17:35:32 +01003732 // If the we can't run the GC type we wanted to run, find the next appropriate one and try
3733 // that instead. E.g. can't do partial, so do full instead.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003734 collector::GcType next_gc_type = next_gc_type_;
3735 // If forcing full and next gc type is sticky, override with a non-sticky type.
3736 if (force_full && next_gc_type == collector::kGcTypeSticky) {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003737 next_gc_type = NonStickyGcType();
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003738 }
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003739 if (CollectGarbageInternal(next_gc_type, cause, false) == collector::kGcTypeNone) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003740 for (collector::GcType gc_type : gc_plan_) {
3741 // Attempt to run the collector, if we succeed, we are done.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003742 if (gc_type > next_gc_type &&
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003743 CollectGarbageInternal(gc_type, cause, false) != collector::kGcTypeNone) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003744 break;
3745 }
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08003746 }
3747 }
3748 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07003749 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003750}
3751
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003752class Heap::CollectorTransitionTask : public HeapTask {
3753 public:
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003754 explicit CollectorTransitionTask(uint64_t target_time) : HeapTask(target_time) {}
3755
Roland Levillainf73caca2018-08-24 17:19:07 +01003756 void Run(Thread* self) override {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003757 gc::Heap* heap = Runtime::Current()->GetHeap();
3758 heap->DoPendingCollectorTransition();
3759 heap->ClearPendingCollectorTransition(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003760 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003761};
3762
3763void Heap::ClearPendingCollectorTransition(Thread* self) {
3764 MutexLock mu(self, *pending_task_lock_);
3765 pending_collector_transition_ = nullptr;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003766}
3767
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003768void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
3769 Thread* self = Thread::Current();
3770 desired_collector_type_ = desired_collector_type;
3771 if (desired_collector_type_ == collector_type_ || !CanAddHeapTask(self)) {
3772 return;
3773 }
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07003774 if (collector_type_ == kCollectorTypeCC) {
3775 // For CC, we invoke a full compaction when going to the background, but the collector type
3776 // doesn't change.
3777 DCHECK_EQ(desired_collector_type_, kCollectorTypeCCBackground);
3778 }
3779 DCHECK_NE(collector_type_, kCollectorTypeCCBackground);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003780 CollectorTransitionTask* added_task = nullptr;
3781 const uint64_t target_time = NanoTime() + delta_time;
3782 {
3783 MutexLock mu(self, *pending_task_lock_);
3784 // If we have an existing collector transition, update the targe time to be the new target.
3785 if (pending_collector_transition_ != nullptr) {
3786 task_processor_->UpdateTargetRunTime(self, pending_collector_transition_, target_time);
3787 return;
3788 }
3789 added_task = new CollectorTransitionTask(target_time);
3790 pending_collector_transition_ = added_task;
3791 }
3792 task_processor_->AddTask(self, added_task);
3793}
3794
3795class Heap::HeapTrimTask : public HeapTask {
3796 public:
3797 explicit HeapTrimTask(uint64_t delta_time) : HeapTask(NanoTime() + delta_time) { }
Roland Levillainf73caca2018-08-24 17:19:07 +01003798 void Run(Thread* self) override {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003799 gc::Heap* heap = Runtime::Current()->GetHeap();
3800 heap->Trim(self);
3801 heap->ClearPendingTrim(self);
3802 }
3803};
3804
3805void Heap::ClearPendingTrim(Thread* self) {
3806 MutexLock mu(self, *pending_task_lock_);
3807 pending_heap_trim_ = nullptr;
3808}
3809
3810void Heap::RequestTrim(Thread* self) {
3811 if (!CanAddHeapTask(self)) {
3812 return;
3813 }
Ian Rogers48931882013-01-22 14:35:16 -08003814 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3815 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3816 // a space it will hold its lock and can become a cause of jank.
3817 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3818 // forking.
3819
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08003820 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3821 // because that only marks object heads, so a large array looks like lots of empty space. We
3822 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3823 // to utilization (which is probably inversely proportional to how much benefit we can expect).
3824 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3825 // not how much use we're making of those pages.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003826 HeapTrimTask* added_task = nullptr;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003827 {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003828 MutexLock mu(self, *pending_task_lock_);
3829 if (pending_heap_trim_ != nullptr) {
3830 // Already have a heap trim request in task processor, ignore this request.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003831 return;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003832 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003833 added_task = new HeapTrimTask(kHeapTrimWait);
3834 pending_heap_trim_ = added_task;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07003835 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003836 task_processor_->AddTask(self, added_task);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003837}
3838
Orion Hodson82cf9a22018-03-27 16:36:32 +01003839void Heap::IncrementNumberOfBytesFreedRevoke(size_t freed_bytes_revoke) {
3840 size_t previous_num_bytes_freed_revoke =
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003841 num_bytes_freed_revoke_.fetch_add(freed_bytes_revoke, std::memory_order_relaxed);
Orion Hodson82cf9a22018-03-27 16:36:32 +01003842 // Check the updated value is less than the number of bytes allocated. There is a risk of
3843 // execution being suspended between the increment above and the CHECK below, leading to
3844 // the use of previous_num_bytes_freed_revoke in the comparison.
3845 CHECK_GE(num_bytes_allocated_.load(std::memory_order_relaxed),
3846 previous_num_bytes_freed_revoke + freed_bytes_revoke);
3847}
3848
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003849void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003850 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003851 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3852 if (freed_bytes_revoke > 0U) {
Orion Hodson82cf9a22018-03-27 16:36:32 +01003853 IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003854 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003855 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003856 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003857 CHECK_EQ(bump_pointer_space_->RevokeThreadLocalBuffers(thread), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003858 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003859 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003860 CHECK_EQ(region_space_->RevokeThreadLocalBuffers(thread), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003861 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003862}
3863
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003864void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3865 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003866 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3867 if (freed_bytes_revoke > 0U) {
Orion Hodson82cf9a22018-03-27 16:36:32 +01003868 IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003869 }
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003870 }
3871}
3872
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003873void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003874 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003875 size_t freed_bytes_revoke = rosalloc_space_->RevokeAllThreadLocalBuffers();
3876 if (freed_bytes_revoke > 0U) {
Orion Hodson82cf9a22018-03-27 16:36:32 +01003877 IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003878 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003879 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003880 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003881 CHECK_EQ(bump_pointer_space_->RevokeAllThreadLocalBuffers(), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003882 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003883 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003884 CHECK_EQ(region_space_->RevokeAllThreadLocalBuffers(), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003885 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003886}
3887
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003888bool Heap::IsGCRequestPending() const {
Orion Hodson88591fe2018-03-06 13:35:43 +00003889 return concurrent_gc_pending_.load(std::memory_order_relaxed);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003890}
3891
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003892void Heap::RunFinalization(JNIEnv* env, uint64_t timeout) {
3893 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
3894 WellKnownClasses::dalvik_system_VMRuntime_runFinalization,
3895 static_cast<jlong>(timeout));
Mathieu Chartier590fee92013-09-13 13:46:47 -07003896}
3897
Richard Uhler36bdbd22017-01-24 14:17:05 +00003898void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003899 size_t old_value = new_native_bytes_allocated_.fetch_add(bytes, std::memory_order_relaxed);
Richard Uhler36bdbd22017-01-24 14:17:05 +00003900
Richard Uhlerf4eedfe2017-12-29 14:48:42 +00003901 if (old_value > NativeAllocationGcWatermark() * HeapGrowthMultiplier() &&
Mathieu Chartier75e4b2a2017-05-24 12:01:04 -07003902 !IsGCRequestPending()) {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003903 // Trigger another GC because there have been enough native bytes
3904 // allocated since the last GC.
3905 if (IsGcConcurrent()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003906 RequestConcurrentGC(ThreadForEnv(env), kGcCauseForNativeAlloc, /*force_full=*/true);
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003907 } else {
3908 CollectGarbageInternal(NonStickyGcType(), kGcCauseForNativeAlloc, false);
3909 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003910 }
3911}
3912
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003913void Heap::RegisterNativeFree(JNIEnv*, size_t bytes) {
3914 // Take the bytes freed out of new_native_bytes_allocated_ first. If
3915 // new_native_bytes_allocated_ reaches zero, take the remaining bytes freed
3916 // out of old_native_bytes_allocated_ to ensure all freed bytes are
3917 // accounted for.
3918 size_t allocated;
3919 size_t new_freed_bytes;
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003920 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00003921 allocated = new_native_bytes_allocated_.load(std::memory_order_relaxed);
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003922 new_freed_bytes = std::min(allocated, bytes);
Orion Hodson4557b382018-01-03 11:47:54 +00003923 } while (!new_native_bytes_allocated_.CompareAndSetWeakRelaxed(allocated,
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003924 allocated - new_freed_bytes));
3925 if (new_freed_bytes < bytes) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003926 old_native_bytes_allocated_.fetch_sub(bytes - new_freed_bytes, std::memory_order_relaxed);
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003927 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003928}
3929
Ian Rogersef7d42f2014-01-06 12:55:46 -08003930size_t Heap::GetTotalMemory() const {
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003931 return std::max(max_allowed_footprint_, GetBytesAllocated());
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07003932}
3933
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003934void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3935 DCHECK(mod_union_table != nullptr);
3936 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3937}
3938
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003939void Heap::CheckPreconditionsForAllocObject(ObjPtr<mirror::Class> c, size_t byte_count) {
Mathieu Chartierdf7f7f02017-10-05 09:47:58 -07003940 // Compare rounded sizes since the allocation may have been retried after rounding the size.
3941 // See b/37885600
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003942 CHECK(c == nullptr || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Mathieu Chartieraac90122017-10-04 14:58:34 -07003943 (c->IsVariableSize() ||
3944 RoundUp(c->GetObjectSize(), kObjectAlignment) ==
3945 RoundUp(byte_count, kObjectAlignment)))
Mathieu Chartier8876fb72017-02-24 12:39:53 -08003946 << "ClassFlags=" << c->GetClassFlags()
3947 << " IsClassClass=" << c->IsClassClass()
3948 << " byte_count=" << byte_count
3949 << " IsVariableSize=" << c->IsVariableSize()
3950 << " ObjectSize=" << c->GetObjectSize()
3951 << " sizeof(Class)=" << sizeof(mirror::Class)
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003952 << " " << verification_->DumpObjectInfo(c.Ptr(), /*tag=*/ "klass");
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003953 CHECK_GE(byte_count, sizeof(mirror::Object));
3954}
3955
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003956void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
3957 CHECK(remembered_set != nullptr);
3958 space::Space* space = remembered_set->GetSpace();
3959 CHECK(space != nullptr);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003960 CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003961 remembered_sets_.Put(space, remembered_set);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003962 CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003963}
3964
3965void Heap::RemoveRememberedSet(space::Space* space) {
3966 CHECK(space != nullptr);
3967 auto it = remembered_sets_.find(space);
3968 CHECK(it != remembered_sets_.end());
Mathieu Chartier5189e242014-07-24 11:11:05 -07003969 delete it->second;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003970 remembered_sets_.erase(it);
3971 CHECK(remembered_sets_.find(space) == remembered_sets_.end());
3972}
3973
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003974void Heap::ClearMarkedObjects() {
3975 // Clear all of the spaces' mark bitmaps.
3976 for (const auto& space : GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07003977 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003978 if (space->GetLiveBitmap() != mark_bitmap) {
3979 mark_bitmap->Clear();
3980 }
3981 }
3982 // Clear the marked objects in the discontinous space object sets.
3983 for (const auto& space : GetDiscontinuousSpaces()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07003984 space->GetMarkBitmap()->Clear();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003985 }
3986}
3987
Man Cao8c2ff642015-05-27 17:25:30 -07003988void Heap::SetAllocationRecords(AllocRecordObjectMap* records) {
3989 allocation_records_.reset(records);
3990}
3991
Man Cao1ed11b92015-06-11 22:47:35 -07003992void Heap::VisitAllocationRecords(RootVisitor* visitor) const {
3993 if (IsAllocTrackingEnabled()) {
3994 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3995 if (IsAllocTrackingEnabled()) {
3996 GetAllocationRecords()->VisitRoots(visitor);
3997 }
3998 }
3999}
4000
Mathieu Chartier97509952015-07-13 14:35:43 -07004001void Heap::SweepAllocationRecords(IsMarkedVisitor* visitor) const {
Man Cao8c2ff642015-05-27 17:25:30 -07004002 if (IsAllocTrackingEnabled()) {
4003 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4004 if (IsAllocTrackingEnabled()) {
Mathieu Chartier97509952015-07-13 14:35:43 -07004005 GetAllocationRecords()->SweepAllocationRecords(visitor);
Man Cao8c2ff642015-05-27 17:25:30 -07004006 }
4007 }
4008}
4009
Man Cao42c3c332015-06-23 16:38:25 -07004010void Heap::AllowNewAllocationRecords() const {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07004011 CHECK(!kUseReadBarrier);
Hiroshi Yamauchi6f0c6cd2016-03-18 17:17:52 -07004012 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4013 AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4014 if (allocation_records != nullptr) {
4015 allocation_records->AllowNewAllocationRecords();
Man Cao42c3c332015-06-23 16:38:25 -07004016 }
4017}
4018
4019void Heap::DisallowNewAllocationRecords() const {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07004020 CHECK(!kUseReadBarrier);
Hiroshi Yamauchi6f0c6cd2016-03-18 17:17:52 -07004021 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4022 AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4023 if (allocation_records != nullptr) {
4024 allocation_records->DisallowNewAllocationRecords();
Man Cao42c3c332015-06-23 16:38:25 -07004025 }
4026}
4027
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07004028void Heap::BroadcastForNewAllocationRecords() const {
Hiroshi Yamauchi6f0c6cd2016-03-18 17:17:52 -07004029 // Always broadcast without checking IsAllocTrackingEnabled() because IsAllocTrackingEnabled() may
4030 // be set to false while some threads are waiting for system weak access in
4031 // AllocRecordObjectMap::RecordAllocation() and we may fail to wake them up. b/27467554.
4032 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4033 AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4034 if (allocation_records != nullptr) {
4035 allocation_records->BroadcastForNewAllocationRecords();
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07004036 }
4037}
4038
Mathieu Chartier9d156d52016-10-06 17:44:26 -07004039void Heap::CheckGcStressMode(Thread* self, ObjPtr<mirror::Object>* obj) {
Vladimir Marko317892b2018-05-31 11:11:32 +01004040 DCHECK(gc_stress_mode_);
Mathieu Chartier31000802015-06-14 14:14:37 -07004041 auto* const runtime = Runtime::Current();
Vladimir Marko317892b2018-05-31 11:11:32 +01004042 if (runtime->GetClassLinker()->IsInitialized() && !runtime->IsActiveTransaction()) {
Mathieu Chartier31000802015-06-14 14:14:37 -07004043 // Check if we should GC.
4044 bool new_backtrace = false;
4045 {
4046 static constexpr size_t kMaxFrames = 16u;
Mathieu Chartier34583592017-03-23 23:51:34 -07004047 FixedSizeBacktrace<kMaxFrames> backtrace;
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004048 backtrace.Collect(/* skip_count= */ 2);
Mathieu Chartier34583592017-03-23 23:51:34 -07004049 uint64_t hash = backtrace.Hash();
Mathieu Chartier31000802015-06-14 14:14:37 -07004050 MutexLock mu(self, *backtrace_lock_);
4051 new_backtrace = seen_backtraces_.find(hash) == seen_backtraces_.end();
4052 if (new_backtrace) {
4053 seen_backtraces_.insert(hash);
4054 }
4055 }
4056 if (new_backtrace) {
4057 StackHandleScope<1> hs(self);
4058 auto h = hs.NewHandleWrapper(obj);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004059 CollectGarbage(/* clear_soft_references= */ false);
Hans Boehmfb8b4e22018-09-05 16:45:42 -07004060 unique_backtrace_count_.fetch_add(1);
Mathieu Chartier31000802015-06-14 14:14:37 -07004061 } else {
Hans Boehmfb8b4e22018-09-05 16:45:42 -07004062 seen_backtrace_count_.fetch_add(1);
Mathieu Chartier31000802015-06-14 14:14:37 -07004063 }
4064 }
4065}
4066
Mathieu Chartier51168372015-08-12 16:40:32 -07004067void Heap::DisableGCForShutdown() {
4068 Thread* const self = Thread::Current();
4069 CHECK(Runtime::Current()->IsShuttingDown(self));
4070 MutexLock mu(self, *gc_complete_lock_);
4071 gc_disabled_for_shutdown_ = true;
4072}
4073
Mathieu Chartier9d156d52016-10-06 17:44:26 -07004074bool Heap::ObjectIsInBootImageSpace(ObjPtr<mirror::Object> obj) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004075 for (gc::space::ImageSpace* space : boot_image_spaces_) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07004076 if (space->HasAddress(obj.Ptr())) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004077 return true;
4078 }
4079 }
4080 return false;
4081}
4082
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -08004083bool Heap::IsInBootImageOatFile(const void* p) const {
4084 for (gc::space::ImageSpace* space : boot_image_spaces_) {
4085 if (space->GetOatFile()->Contains(p)) {
4086 return true;
4087 }
4088 }
4089 return false;
4090}
4091
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004092void Heap::GetBootImagesSize(uint32_t* boot_image_begin,
4093 uint32_t* boot_image_end,
4094 uint32_t* boot_oat_begin,
4095 uint32_t* boot_oat_end) {
4096 DCHECK(boot_image_begin != nullptr);
4097 DCHECK(boot_image_end != nullptr);
4098 DCHECK(boot_oat_begin != nullptr);
4099 DCHECK(boot_oat_end != nullptr);
4100 *boot_image_begin = 0u;
4101 *boot_image_end = 0u;
4102 *boot_oat_begin = 0u;
4103 *boot_oat_end = 0u;
4104 for (gc::space::ImageSpace* space_ : GetBootImageSpaces()) {
4105 const uint32_t image_begin = PointerToLowMemUInt32(space_->Begin());
4106 const uint32_t image_size = space_->GetImageHeader().GetImageSize();
4107 if (*boot_image_begin == 0 || image_begin < *boot_image_begin) {
4108 *boot_image_begin = image_begin;
4109 }
4110 *boot_image_end = std::max(*boot_image_end, image_begin + image_size);
4111 const OatFile* boot_oat_file = space_->GetOatFile();
4112 const uint32_t oat_begin = PointerToLowMemUInt32(boot_oat_file->Begin());
4113 const uint32_t oat_size = boot_oat_file->Size();
4114 if (*boot_oat_begin == 0 || oat_begin < *boot_oat_begin) {
4115 *boot_oat_begin = oat_begin;
4116 }
4117 *boot_oat_end = std::max(*boot_oat_end, oat_begin + oat_size);
4118 }
4119}
4120
Andreas Gampe27fa96c2016-10-07 15:05:24 -07004121void Heap::SetAllocationListener(AllocationListener* l) {
4122 AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, l);
4123
4124 if (old == nullptr) {
4125 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
4126 }
4127}
4128
4129void Heap::RemoveAllocationListener() {
4130 AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, nullptr);
4131
4132 if (old != nullptr) {
Andreas Gampe172ec8e2016-10-12 13:50:20 -07004133 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Andreas Gampe27fa96c2016-10-07 15:05:24 -07004134 }
4135}
4136
Andreas Gampe9b8c5882016-10-21 15:27:46 -07004137void Heap::SetGcPauseListener(GcPauseListener* l) {
Orion Hodson88591fe2018-03-06 13:35:43 +00004138 gc_pause_listener_.store(l, std::memory_order_relaxed);
Andreas Gampe9b8c5882016-10-21 15:27:46 -07004139}
4140
4141void Heap::RemoveGcPauseListener() {
Orion Hodson88591fe2018-03-06 13:35:43 +00004142 gc_pause_listener_.store(nullptr, std::memory_order_relaxed);
Andreas Gampe9b8c5882016-10-21 15:27:46 -07004143}
Andreas Gampe27fa96c2016-10-07 15:05:24 -07004144
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004145mirror::Object* Heap::AllocWithNewTLAB(Thread* self,
4146 size_t alloc_size,
4147 bool grow,
4148 size_t* bytes_allocated,
4149 size_t* usable_size,
4150 size_t* bytes_tl_bulk_allocated) {
4151 const AllocatorType allocator_type = GetCurrentAllocator();
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004152 if (kUsePartialTlabs && alloc_size <= self->TlabRemainingCapacity()) {
4153 DCHECK_GT(alloc_size, self->TlabSize());
4154 // There is enough space if we grow the TLAB. Lets do that. This increases the
4155 // TLAB bytes.
4156 const size_t min_expand_size = alloc_size - self->TlabSize();
4157 const size_t expand_bytes = std::max(
4158 min_expand_size,
4159 std::min(self->TlabRemainingCapacity() - self->TlabSize(), kPartialTlabSize));
4160 if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, expand_bytes, grow))) {
4161 return nullptr;
4162 }
4163 *bytes_tl_bulk_allocated = expand_bytes;
4164 self->ExpandTlab(expand_bytes);
4165 DCHECK_LE(alloc_size, self->TlabSize());
4166 } else if (allocator_type == kAllocatorTypeTLAB) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004167 DCHECK(bump_pointer_space_ != nullptr);
4168 const size_t new_tlab_size = alloc_size + kDefaultTLABSize;
4169 if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, new_tlab_size, grow))) {
4170 return nullptr;
4171 }
4172 // Try allocating a new thread local buffer, if the allocation fails the space must be
4173 // full so return null.
4174 if (!bump_pointer_space_->AllocNewTlab(self, new_tlab_size)) {
4175 return nullptr;
4176 }
4177 *bytes_tl_bulk_allocated = new_tlab_size;
4178 } else {
4179 DCHECK(allocator_type == kAllocatorTypeRegionTLAB);
4180 DCHECK(region_space_ != nullptr);
4181 if (space::RegionSpace::kRegionSize >= alloc_size) {
4182 // Non-large. Check OOME for a tlab.
4183 if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type,
4184 space::RegionSpace::kRegionSize,
4185 grow))) {
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004186 const size_t new_tlab_size = kUsePartialTlabs
4187 ? std::max(alloc_size, kPartialTlabSize)
4188 : gc::space::RegionSpace::kRegionSize;
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004189 // Try to allocate a tlab.
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004190 if (!region_space_->AllocNewTlab(self, new_tlab_size)) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004191 // Failed to allocate a tlab. Try non-tlab.
4192 return region_space_->AllocNonvirtual<false>(alloc_size,
4193 bytes_allocated,
4194 usable_size,
4195 bytes_tl_bulk_allocated);
4196 }
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004197 *bytes_tl_bulk_allocated = new_tlab_size;
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004198 // Fall-through to using the TLAB below.
4199 } else {
4200 // Check OOME for a non-tlab allocation.
4201 if (!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow)) {
4202 return region_space_->AllocNonvirtual<false>(alloc_size,
4203 bytes_allocated,
4204 usable_size,
4205 bytes_tl_bulk_allocated);
4206 }
4207 // Neither tlab or non-tlab works. Give up.
4208 return nullptr;
4209 }
4210 } else {
4211 // Large. Check OOME.
4212 if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow))) {
4213 return region_space_->AllocNonvirtual<false>(alloc_size,
4214 bytes_allocated,
4215 usable_size,
4216 bytes_tl_bulk_allocated);
4217 }
4218 return nullptr;
4219 }
4220 }
4221 // Refilled TLAB, return.
4222 mirror::Object* ret = self->AllocTlab(alloc_size);
4223 DCHECK(ret != nullptr);
4224 *bytes_allocated = alloc_size;
4225 *usable_size = alloc_size;
4226 return ret;
4227}
4228
Mathieu Chartier1ca68902017-04-18 11:26:22 -07004229const Verification* Heap::GetVerification() const {
4230 return verification_.get();
4231}
4232
Andreas Gampe170331f2017-12-07 18:41:03 -08004233void Heap::VlogHeapGrowth(size_t max_allowed_footprint, size_t new_footprint, size_t alloc_size) {
4234 VLOG(heap) << "Growing heap from " << PrettySize(max_allowed_footprint) << " to "
4235 << PrettySize(new_footprint) << " for a " << PrettySize(alloc_size) << " allocation";
4236}
4237
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004238class Heap::TriggerPostForkCCGcTask : public HeapTask {
4239 public:
4240 explicit TriggerPostForkCCGcTask(uint64_t target_time) : HeapTask(target_time) {}
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004241 void Run(Thread* self) override {
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004242 gc::Heap* heap = Runtime::Current()->GetHeap();
Hans Boehmfb8b4e22018-09-05 16:45:42 -07004243 // Trigger a GC, if not already done. The first GC after fork, whenever it
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004244 // takes place, will adjust the thresholds to normal levels.
4245 if (heap->max_allowed_footprint_ == heap->growth_limit_) {
4246 heap->RequestConcurrentGC(self, kGcCauseBackground, false);
4247 }
4248 }
4249};
4250
4251void Heap::PostForkChildAction(Thread* self) {
4252 // Temporarily increase max_allowed_footprint_ and concurrent_start_bytes_ to
4253 // max values to avoid GC during app launch.
4254 if (collector_type_ == kCollectorTypeCC && !IsLowMemoryMode()) {
4255 // Set max_allowed_footprint_ to the largest allowed value.
4256 SetIdealFootprint(growth_limit_);
4257 // Set concurrent_start_bytes_ to half of the heap size.
4258 concurrent_start_bytes_ = std::max(max_allowed_footprint_ / 2, GetBytesAllocated());
4259
4260 GetTaskProcessor()->AddTask(
4261 self, new TriggerPostForkCCGcTask(NanoTime() + MsToNs(kPostForkMaxHeapDurationMS)));
4262 }
4263}
4264
Ian Rogers1d54e732013-05-02 21:10:01 -07004265} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07004266} // namespace art