1*795d594fSAndroid Build Coastguard Worker /*
2*795d594fSAndroid Build Coastguard Worker * Copyright (C) 2011 The Android Open Source Project
3*795d594fSAndroid Build Coastguard Worker *
4*795d594fSAndroid Build Coastguard Worker * Licensed under the Apache License, Version 2.0 (the "License");
5*795d594fSAndroid Build Coastguard Worker * you may not use this file except in compliance with the License.
6*795d594fSAndroid Build Coastguard Worker * You may obtain a copy of the License at
7*795d594fSAndroid Build Coastguard Worker *
8*795d594fSAndroid Build Coastguard Worker * http://www.apache.org/licenses/LICENSE-2.0
9*795d594fSAndroid Build Coastguard Worker *
10*795d594fSAndroid Build Coastguard Worker * Unless required by applicable law or agreed to in writing, software
11*795d594fSAndroid Build Coastguard Worker * distributed under the License is distributed on an "AS IS" BASIS,
12*795d594fSAndroid Build Coastguard Worker * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*795d594fSAndroid Build Coastguard Worker * See the License for the specific language governing permissions and
14*795d594fSAndroid Build Coastguard Worker * limitations under the License.
15*795d594fSAndroid Build Coastguard Worker */
16*795d594fSAndroid Build Coastguard Worker
17*795d594fSAndroid Build Coastguard Worker #include "heap.h"
18*795d594fSAndroid Build Coastguard Worker
19*795d594fSAndroid Build Coastguard Worker #include <sys/types.h>
20*795d594fSAndroid Build Coastguard Worker #include <unistd.h>
21*795d594fSAndroid Build Coastguard Worker
22*795d594fSAndroid Build Coastguard Worker #include <limits>
23*795d594fSAndroid Build Coastguard Worker #include <memory>
24*795d594fSAndroid Build Coastguard Worker #include <random>
25*795d594fSAndroid Build Coastguard Worker #include <sstream>
26*795d594fSAndroid Build Coastguard Worker #include <vector>
27*795d594fSAndroid Build Coastguard Worker
28*795d594fSAndroid Build Coastguard Worker #include "allocation_listener.h"
29*795d594fSAndroid Build Coastguard Worker #include "android-base/stringprintf.h"
30*795d594fSAndroid Build Coastguard Worker #include "android-base/thread_annotations.h"
31*795d594fSAndroid Build Coastguard Worker #include "art_field-inl.h"
32*795d594fSAndroid Build Coastguard Worker #include "backtrace_helper.h"
33*795d594fSAndroid Build Coastguard Worker #include "base/allocator.h"
34*795d594fSAndroid Build Coastguard Worker #include "base/arena_allocator.h"
35*795d594fSAndroid Build Coastguard Worker #include "base/dumpable.h"
36*795d594fSAndroid Build Coastguard Worker #include "base/file_utils.h"
37*795d594fSAndroid Build Coastguard Worker #include "base/histogram-inl.h"
38*795d594fSAndroid Build Coastguard Worker #include "base/logging.h" // For VLOG.
39*795d594fSAndroid Build Coastguard Worker #include "base/memory_tool.h"
40*795d594fSAndroid Build Coastguard Worker #include "base/mutex.h"
41*795d594fSAndroid Build Coastguard Worker #include "base/os.h"
42*795d594fSAndroid Build Coastguard Worker #include "base/stl_util.h"
43*795d594fSAndroid Build Coastguard Worker #include "base/systrace.h"
44*795d594fSAndroid Build Coastguard Worker #include "base/time_utils.h"
45*795d594fSAndroid Build Coastguard Worker #include "base/utils.h"
46*795d594fSAndroid Build Coastguard Worker #include "class_root-inl.h"
47*795d594fSAndroid Build Coastguard Worker #include "common_throws.h"
48*795d594fSAndroid Build Coastguard Worker #include "debugger.h"
49*795d594fSAndroid Build Coastguard Worker #include "dex/dex_file-inl.h"
50*795d594fSAndroid Build Coastguard Worker #include "entrypoints/quick/quick_alloc_entrypoints.h"
51*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/card_table-inl.h"
52*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/heap_bitmap-inl.h"
53*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/mod_union_table-inl.h"
54*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/read_barrier_table.h"
55*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/remembered_set.h"
56*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/space_bitmap-inl.h"
57*795d594fSAndroid Build Coastguard Worker #include "gc/collector/concurrent_copying.h"
58*795d594fSAndroid Build Coastguard Worker #include "gc/collector/mark_compact.h"
59*795d594fSAndroid Build Coastguard Worker #include "gc/collector/mark_sweep.h"
60*795d594fSAndroid Build Coastguard Worker #include "gc/collector/partial_mark_sweep.h"
61*795d594fSAndroid Build Coastguard Worker #include "gc/collector/semi_space.h"
62*795d594fSAndroid Build Coastguard Worker #include "gc/collector/sticky_mark_sweep.h"
63*795d594fSAndroid Build Coastguard Worker #include "gc/racing_check.h"
64*795d594fSAndroid Build Coastguard Worker #include "gc/reference_processor.h"
65*795d594fSAndroid Build Coastguard Worker #include "gc/scoped_gc_critical_section.h"
66*795d594fSAndroid Build Coastguard Worker #include "gc/space/bump_pointer_space.h"
67*795d594fSAndroid Build Coastguard Worker #include "gc/space/dlmalloc_space-inl.h"
68*795d594fSAndroid Build Coastguard Worker #include "gc/space/image_space.h"
69*795d594fSAndroid Build Coastguard Worker #include "gc/space/large_object_space.h"
70*795d594fSAndroid Build Coastguard Worker #include "gc/space/region_space.h"
71*795d594fSAndroid Build Coastguard Worker #include "gc/space/rosalloc_space-inl.h"
72*795d594fSAndroid Build Coastguard Worker #include "gc/space/space-inl.h"
73*795d594fSAndroid Build Coastguard Worker #include "gc/space/zygote_space.h"
74*795d594fSAndroid Build Coastguard Worker #include "gc/task_processor.h"
75*795d594fSAndroid Build Coastguard Worker #include "gc/verification.h"
76*795d594fSAndroid Build Coastguard Worker #include "gc_pause_listener.h"
77*795d594fSAndroid Build Coastguard Worker #include "gc_root.h"
78*795d594fSAndroid Build Coastguard Worker #include "handle_scope-inl.h"
79*795d594fSAndroid Build Coastguard Worker #include "heap-inl.h"
80*795d594fSAndroid Build Coastguard Worker #include "heap-visit-objects-inl.h"
81*795d594fSAndroid Build Coastguard Worker #include "intern_table.h"
82*795d594fSAndroid Build Coastguard Worker #include "jit/jit.h"
83*795d594fSAndroid Build Coastguard Worker #include "jit/jit_code_cache.h"
84*795d594fSAndroid Build Coastguard Worker #include "jni/java_vm_ext.h"
85*795d594fSAndroid Build Coastguard Worker #include "mirror/class-inl.h"
86*795d594fSAndroid Build Coastguard Worker #include "mirror/executable-inl.h"
87*795d594fSAndroid Build Coastguard Worker #include "mirror/field.h"
88*795d594fSAndroid Build Coastguard Worker #include "mirror/method_handle_impl.h"
89*795d594fSAndroid Build Coastguard Worker #include "mirror/object-inl.h"
90*795d594fSAndroid Build Coastguard Worker #include "mirror/object-refvisitor-inl.h"
91*795d594fSAndroid Build Coastguard Worker #include "mirror/object_array-inl.h"
92*795d594fSAndroid Build Coastguard Worker #include "mirror/reference-inl.h"
93*795d594fSAndroid Build Coastguard Worker #include "mirror/var_handle.h"
94*795d594fSAndroid Build Coastguard Worker #include "nativehelper/scoped_local_ref.h"
95*795d594fSAndroid Build Coastguard Worker #include "oat/image.h"
96*795d594fSAndroid Build Coastguard Worker #include "obj_ptr-inl.h"
97*795d594fSAndroid Build Coastguard Worker #ifdef ART_TARGET_ANDROID
98*795d594fSAndroid Build Coastguard Worker #include "perfetto/heap_profile.h"
99*795d594fSAndroid Build Coastguard Worker #endif
100*795d594fSAndroid Build Coastguard Worker #include "reflection.h"
101*795d594fSAndroid Build Coastguard Worker #include "runtime.h"
102*795d594fSAndroid Build Coastguard Worker #include "javaheapprof/javaheapsampler.h"
103*795d594fSAndroid Build Coastguard Worker #include "scoped_thread_state_change-inl.h"
104*795d594fSAndroid Build Coastguard Worker #include "thread-inl.h"
105*795d594fSAndroid Build Coastguard Worker #include "thread_list.h"
106*795d594fSAndroid Build Coastguard Worker #include "verify_object-inl.h"
107*795d594fSAndroid Build Coastguard Worker #include "well_known_classes.h"
108*795d594fSAndroid Build Coastguard Worker
109*795d594fSAndroid Build Coastguard Worker #if defined(__BIONIC__) || defined(__GLIBC__) || defined(ANDROID_HOST_MUSL)
110*795d594fSAndroid Build Coastguard Worker #include <malloc.h> // For mallinfo()
111*795d594fSAndroid Build Coastguard Worker #endif
112*795d594fSAndroid Build Coastguard Worker
113*795d594fSAndroid Build Coastguard Worker namespace art HIDDEN {
114*795d594fSAndroid Build Coastguard Worker
115*795d594fSAndroid Build Coastguard Worker #ifdef ART_TARGET_ANDROID
116*795d594fSAndroid Build Coastguard Worker namespace {
117*795d594fSAndroid Build Coastguard Worker
118*795d594fSAndroid Build Coastguard Worker // Enable the heap sampler Callback function used by Perfetto.
EnableHeapSamplerCallback(void * enable_ptr,const AHeapProfileEnableCallbackInfo * enable_info_ptr)119*795d594fSAndroid Build Coastguard Worker void EnableHeapSamplerCallback(void* enable_ptr,
120*795d594fSAndroid Build Coastguard Worker const AHeapProfileEnableCallbackInfo* enable_info_ptr) {
121*795d594fSAndroid Build Coastguard Worker HeapSampler* sampler_self = reinterpret_cast<HeapSampler*>(enable_ptr);
122*795d594fSAndroid Build Coastguard Worker // Set the ART profiler sampling interval to the value from Perfetto.
123*795d594fSAndroid Build Coastguard Worker uint64_t interval = AHeapProfileEnableCallbackInfo_getSamplingInterval(enable_info_ptr);
124*795d594fSAndroid Build Coastguard Worker if (interval > 0) {
125*795d594fSAndroid Build Coastguard Worker sampler_self->SetSamplingInterval(interval);
126*795d594fSAndroid Build Coastguard Worker }
127*795d594fSAndroid Build Coastguard Worker // Else default is 4K sampling interval. However, default case shouldn't happen for Perfetto API.
128*795d594fSAndroid Build Coastguard Worker // AHeapProfileEnableCallbackInfo_getSamplingInterval should always give the requested
129*795d594fSAndroid Build Coastguard Worker // (non-negative) sampling interval. It is a uint64_t and gets checked for != 0
130*795d594fSAndroid Build Coastguard Worker // Do not call heap as a temp here, it will build but test run will silently fail.
131*795d594fSAndroid Build Coastguard Worker // Heap is not fully constructed yet in some cases.
132*795d594fSAndroid Build Coastguard Worker sampler_self->EnableHeapSampler();
133*795d594fSAndroid Build Coastguard Worker }
134*795d594fSAndroid Build Coastguard Worker
135*795d594fSAndroid Build Coastguard Worker // Disable the heap sampler Callback function used by Perfetto.
DisableHeapSamplerCallback(void * disable_ptr,const AHeapProfileDisableCallbackInfo * info_ptr)136*795d594fSAndroid Build Coastguard Worker void DisableHeapSamplerCallback(void* disable_ptr,
137*795d594fSAndroid Build Coastguard Worker [[maybe_unused]] const AHeapProfileDisableCallbackInfo* info_ptr) {
138*795d594fSAndroid Build Coastguard Worker HeapSampler* sampler_self = reinterpret_cast<HeapSampler*>(disable_ptr);
139*795d594fSAndroid Build Coastguard Worker sampler_self->DisableHeapSampler();
140*795d594fSAndroid Build Coastguard Worker }
141*795d594fSAndroid Build Coastguard Worker
142*795d594fSAndroid Build Coastguard Worker } // namespace
143*795d594fSAndroid Build Coastguard Worker #endif
144*795d594fSAndroid Build Coastguard Worker
145*795d594fSAndroid Build Coastguard Worker namespace gc {
146*795d594fSAndroid Build Coastguard Worker
147*795d594fSAndroid Build Coastguard Worker DEFINE_RUNTIME_DEBUG_FLAG(Heap, kStressCollectorTransition);
148*795d594fSAndroid Build Coastguard Worker
149*795d594fSAndroid Build Coastguard Worker // Minimum amount of remaining bytes before a concurrent GC is triggered.
150*795d594fSAndroid Build Coastguard Worker static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
151*795d594fSAndroid Build Coastguard Worker static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
152*795d594fSAndroid Build Coastguard Worker // Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
153*795d594fSAndroid Build Coastguard Worker // relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
154*795d594fSAndroid Build Coastguard Worker // threads (lower pauses, use less memory bandwidth).
GetStickyGcThroughputAdjustment(bool use_generational_cc)155*795d594fSAndroid Build Coastguard Worker static double GetStickyGcThroughputAdjustment(bool use_generational_cc) {
156*795d594fSAndroid Build Coastguard Worker return use_generational_cc ? 0.5 : 1.0;
157*795d594fSAndroid Build Coastguard Worker }
158*795d594fSAndroid Build Coastguard Worker // Whether or not we compact the zygote in PreZygoteFork.
159*795d594fSAndroid Build Coastguard Worker static constexpr bool kCompactZygote = kMovingCollector;
160*795d594fSAndroid Build Coastguard Worker // How many reserve entries are at the end of the allocation stack, these are only needed if the
161*795d594fSAndroid Build Coastguard Worker // allocation stack overflows.
162*795d594fSAndroid Build Coastguard Worker static constexpr size_t kAllocationStackReserveSize = 1024;
163*795d594fSAndroid Build Coastguard Worker // Default mark stack size in bytes.
164*795d594fSAndroid Build Coastguard Worker static const size_t kDefaultMarkStackSize = 64 * KB;
165*795d594fSAndroid Build Coastguard Worker // Define space name.
166*795d594fSAndroid Build Coastguard Worker static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
167*795d594fSAndroid Build Coastguard Worker static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
168*795d594fSAndroid Build Coastguard Worker static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
169*795d594fSAndroid Build Coastguard Worker static const char* kNonMovingSpaceName = "non moving space";
170*795d594fSAndroid Build Coastguard Worker static const char* kZygoteSpaceName = "zygote space";
171*795d594fSAndroid Build Coastguard Worker static constexpr bool kGCALotMode = false;
172*795d594fSAndroid Build Coastguard Worker // GC alot mode uses a small allocation stack to stress test a lot of GC.
173*795d594fSAndroid Build Coastguard Worker static constexpr size_t kGcAlotAllocationStackSize = 4 * KB /
174*795d594fSAndroid Build Coastguard Worker sizeof(mirror::HeapReference<mirror::Object>);
175*795d594fSAndroid Build Coastguard Worker // Verify objet has a small allocation stack size since searching the allocation stack is slow.
176*795d594fSAndroid Build Coastguard Worker static constexpr size_t kVerifyObjectAllocationStackSize = 16 * KB /
177*795d594fSAndroid Build Coastguard Worker sizeof(mirror::HeapReference<mirror::Object>);
178*795d594fSAndroid Build Coastguard Worker static constexpr size_t kDefaultAllocationStackSize = 8 * MB /
179*795d594fSAndroid Build Coastguard Worker sizeof(mirror::HeapReference<mirror::Object>);
180*795d594fSAndroid Build Coastguard Worker
181*795d594fSAndroid Build Coastguard Worker // If we violate BOTH of the following constraints, we throw OOME.
182*795d594fSAndroid Build Coastguard Worker // They differ due to concurrent allocation.
183*795d594fSAndroid Build Coastguard Worker // After a GC (due to allocation failure) we should retrieve at least this
184*795d594fSAndroid Build Coastguard Worker // fraction of the current max heap size.
185*795d594fSAndroid Build Coastguard Worker static constexpr double kMinFreedHeapAfterGcForAlloc = 0.05;
186*795d594fSAndroid Build Coastguard Worker // After a GC (due to allocation failure), at least this fraction of the
187*795d594fSAndroid Build Coastguard Worker // heap should be available.
188*795d594fSAndroid Build Coastguard Worker static constexpr double kMinFreeHeapAfterGcForAlloc = 0.01;
189*795d594fSAndroid Build Coastguard Worker
190*795d594fSAndroid Build Coastguard Worker // For deterministic compilation, we need the heap to be at a well-known address.
191*795d594fSAndroid Build Coastguard Worker static constexpr uint32_t kAllocSpaceBeginForDeterministicAoT = 0x40000000;
192*795d594fSAndroid Build Coastguard Worker // Dump the rosalloc stats on SIGQUIT.
193*795d594fSAndroid Build Coastguard Worker static constexpr bool kDumpRosAllocStatsOnSigQuit = false;
194*795d594fSAndroid Build Coastguard Worker
195*795d594fSAndroid Build Coastguard Worker static const char* kRegionSpaceName = "main space (region space)";
196*795d594fSAndroid Build Coastguard Worker
197*795d594fSAndroid Build Coastguard Worker // If true, we log all GCs in the both the foreground and background. Used for debugging.
198*795d594fSAndroid Build Coastguard Worker static constexpr bool kLogAllGCs = false;
199*795d594fSAndroid Build Coastguard Worker
200*795d594fSAndroid Build Coastguard Worker // Use Max heap for 2 seconds, this is smaller than the usual 5s window since we don't want to leave
201*795d594fSAndroid Build Coastguard Worker // allocate with relaxed ergonomics for that long.
202*795d594fSAndroid Build Coastguard Worker static constexpr size_t kPostForkMaxHeapDurationMS = 2000;
203*795d594fSAndroid Build Coastguard Worker
204*795d594fSAndroid Build Coastguard Worker #if defined(__LP64__) || !defined(ADDRESS_SANITIZER)
205*795d594fSAndroid Build Coastguard Worker // 32 MB (0x2000000) is picked to ensure it is aligned to the largest supported PMD
206*795d594fSAndroid Build Coastguard Worker // size, which is 32mb with a 16k page size on AArch64.
__anon1647f9090202() 207*795d594fSAndroid Build Coastguard Worker uint8_t* const Heap::kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(([]() constexpr {
208*795d594fSAndroid Build Coastguard Worker constexpr size_t kBegin = 32 * MB;
209*795d594fSAndroid Build Coastguard Worker constexpr int kMaxPMDSize = (kMaxPageSize / sizeof(uint64_t)) * kMaxPageSize;
210*795d594fSAndroid Build Coastguard Worker static_assert(IsAligned<kMaxPMDSize>(kBegin),
211*795d594fSAndroid Build Coastguard Worker "Moving-space's begin should be aligned to the maximum supported PMD size.");
212*795d594fSAndroid Build Coastguard Worker return kBegin;
213*795d594fSAndroid Build Coastguard Worker })());
214*795d594fSAndroid Build Coastguard Worker #else
215*795d594fSAndroid Build Coastguard Worker #ifdef __ANDROID__
216*795d594fSAndroid Build Coastguard Worker // For 32-bit Android, use 0x20000000 because asan reserves 0x04000000 - 0x20000000.
217*795d594fSAndroid Build Coastguard Worker uint8_t* const Heap::kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x20000000);
218*795d594fSAndroid Build Coastguard Worker #else
219*795d594fSAndroid Build Coastguard Worker // For 32-bit host, use 0x40000000 because asan uses most of the space below this.
220*795d594fSAndroid Build Coastguard Worker uint8_t* const Heap::kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x40000000);
221*795d594fSAndroid Build Coastguard Worker #endif
222*795d594fSAndroid Build Coastguard Worker #endif
223*795d594fSAndroid Build Coastguard Worker
224*795d594fSAndroid Build Coastguard Worker // Log GC on regular (but fairly large) intervals during GC stress mode.
225*795d594fSAndroid Build Coastguard Worker // It is expected that the other runtime options will be used to reduce the usual logging.
226*795d594fSAndroid Build Coastguard Worker // This allows us to make the logging much less verbose while still reporting some
227*795d594fSAndroid Build Coastguard Worker // progress (biased towards expensive GCs), and while still reporting pathological cases.
228*795d594fSAndroid Build Coastguard Worker static constexpr int64_t kGcStressModeGcLogSampleFrequencyNs = MsToNs(10000);
229*795d594fSAndroid Build Coastguard Worker
CareAboutPauseTimes()230*795d594fSAndroid Build Coastguard Worker static inline bool CareAboutPauseTimes() {
231*795d594fSAndroid Build Coastguard Worker return Runtime::Current()->InJankPerceptibleProcessState();
232*795d594fSAndroid Build Coastguard Worker }
233*795d594fSAndroid Build Coastguard Worker
VerifyBootImagesContiguity(const std::vector<gc::space::ImageSpace * > & image_spaces)234*795d594fSAndroid Build Coastguard Worker static void VerifyBootImagesContiguity(const std::vector<gc::space::ImageSpace*>& image_spaces) {
235*795d594fSAndroid Build Coastguard Worker uint32_t boot_image_size = 0u;
236*795d594fSAndroid Build Coastguard Worker for (size_t i = 0u, num_spaces = image_spaces.size(); i != num_spaces; ) {
237*795d594fSAndroid Build Coastguard Worker const ImageHeader& image_header = image_spaces[i]->GetImageHeader();
238*795d594fSAndroid Build Coastguard Worker uint32_t reservation_size = image_header.GetImageReservationSize();
239*795d594fSAndroid Build Coastguard Worker uint32_t image_count = image_header.GetImageSpaceCount();
240*795d594fSAndroid Build Coastguard Worker
241*795d594fSAndroid Build Coastguard Worker CHECK_NE(image_count, 0u);
242*795d594fSAndroid Build Coastguard Worker CHECK_LE(image_count, num_spaces - i);
243*795d594fSAndroid Build Coastguard Worker CHECK_NE(reservation_size, 0u);
244*795d594fSAndroid Build Coastguard Worker for (size_t j = 1u; j != image_count; ++j) {
245*795d594fSAndroid Build Coastguard Worker CHECK_EQ(image_spaces[i + j]->GetImageHeader().GetComponentCount(), 0u);
246*795d594fSAndroid Build Coastguard Worker CHECK_EQ(image_spaces[i + j]->GetImageHeader().GetImageReservationSize(), 0u);
247*795d594fSAndroid Build Coastguard Worker }
248*795d594fSAndroid Build Coastguard Worker
249*795d594fSAndroid Build Coastguard Worker // Check the start of the heap.
250*795d594fSAndroid Build Coastguard Worker CHECK_EQ(image_spaces[0]->Begin() + boot_image_size, image_spaces[i]->Begin());
251*795d594fSAndroid Build Coastguard Worker // Check contiguous layout of images and oat files.
252*795d594fSAndroid Build Coastguard Worker const uint8_t* current_heap = image_spaces[i]->Begin();
253*795d594fSAndroid Build Coastguard Worker const uint8_t* current_oat = image_spaces[i]->GetImageHeader().GetOatFileBegin();
254*795d594fSAndroid Build Coastguard Worker for (size_t j = 0u; j != image_count; ++j) {
255*795d594fSAndroid Build Coastguard Worker const ImageHeader& current_header = image_spaces[i + j]->GetImageHeader();
256*795d594fSAndroid Build Coastguard Worker CHECK_EQ(current_heap, image_spaces[i + j]->Begin());
257*795d594fSAndroid Build Coastguard Worker CHECK_EQ(current_oat, current_header.GetOatFileBegin());
258*795d594fSAndroid Build Coastguard Worker current_heap += RoundUp(current_header.GetImageSize(), kElfSegmentAlignment);
259*795d594fSAndroid Build Coastguard Worker CHECK_GT(current_header.GetOatFileEnd(), current_header.GetOatFileBegin());
260*795d594fSAndroid Build Coastguard Worker current_oat = current_header.GetOatFileEnd();
261*795d594fSAndroid Build Coastguard Worker }
262*795d594fSAndroid Build Coastguard Worker // Check that oat files start at the end of images.
263*795d594fSAndroid Build Coastguard Worker CHECK_EQ(current_heap, image_spaces[i]->GetImageHeader().GetOatFileBegin());
264*795d594fSAndroid Build Coastguard Worker // Check that the reservation size equals the size of images and oat files.
265*795d594fSAndroid Build Coastguard Worker CHECK_EQ(reservation_size, static_cast<size_t>(current_oat - image_spaces[i]->Begin()));
266*795d594fSAndroid Build Coastguard Worker
267*795d594fSAndroid Build Coastguard Worker boot_image_size += reservation_size;
268*795d594fSAndroid Build Coastguard Worker i += image_count;
269*795d594fSAndroid Build Coastguard Worker }
270*795d594fSAndroid Build Coastguard Worker }
271*795d594fSAndroid Build Coastguard Worker
Heap(size_t initial_size,size_t growth_limit,size_t min_free,size_t max_free,double target_utilization,double foreground_heap_growth_multiplier,size_t stop_for_native_allocs,size_t capacity,size_t non_moving_space_capacity,const std::vector<std::string> & boot_class_path,const std::vector<std::string> & boot_class_path_locations,ArrayRef<File> boot_class_path_files,ArrayRef<File> boot_class_path_image_files,ArrayRef<File> boot_class_path_vdex_files,ArrayRef<File> boot_class_path_oat_files,const std::vector<std::string> & image_file_names,const InstructionSet image_instruction_set,CollectorType foreground_collector_type,CollectorType background_collector_type,space::LargeObjectSpaceType large_object_space_type,size_t large_object_threshold,size_t parallel_gc_threads,size_t conc_gc_threads,bool low_memory_mode,size_t long_pause_log_threshold,size_t long_gc_log_threshold,bool ignore_target_footprint,bool always_log_explicit_gcs,bool use_tlab,bool verify_pre_gc_heap,bool verify_pre_sweeping_heap,bool verify_post_gc_heap,bool verify_pre_gc_rosalloc,bool verify_pre_sweeping_rosalloc,bool verify_post_gc_rosalloc,bool gc_stress_mode,bool measure_gc_performance,bool use_homogeneous_space_compaction_for_oom,bool use_generational_cc,uint64_t min_interval_homogeneous_space_compaction_by_oom,bool dump_region_info_before_gc,bool dump_region_info_after_gc)272*795d594fSAndroid Build Coastguard Worker Heap::Heap(size_t initial_size,
273*795d594fSAndroid Build Coastguard Worker size_t growth_limit,
274*795d594fSAndroid Build Coastguard Worker size_t min_free,
275*795d594fSAndroid Build Coastguard Worker size_t max_free,
276*795d594fSAndroid Build Coastguard Worker double target_utilization,
277*795d594fSAndroid Build Coastguard Worker double foreground_heap_growth_multiplier,
278*795d594fSAndroid Build Coastguard Worker size_t stop_for_native_allocs,
279*795d594fSAndroid Build Coastguard Worker size_t capacity,
280*795d594fSAndroid Build Coastguard Worker size_t non_moving_space_capacity,
281*795d594fSAndroid Build Coastguard Worker const std::vector<std::string>& boot_class_path,
282*795d594fSAndroid Build Coastguard Worker const std::vector<std::string>& boot_class_path_locations,
283*795d594fSAndroid Build Coastguard Worker ArrayRef<File> boot_class_path_files,
284*795d594fSAndroid Build Coastguard Worker ArrayRef<File> boot_class_path_image_files,
285*795d594fSAndroid Build Coastguard Worker ArrayRef<File> boot_class_path_vdex_files,
286*795d594fSAndroid Build Coastguard Worker ArrayRef<File> boot_class_path_oat_files,
287*795d594fSAndroid Build Coastguard Worker const std::vector<std::string>& image_file_names,
288*795d594fSAndroid Build Coastguard Worker const InstructionSet image_instruction_set,
289*795d594fSAndroid Build Coastguard Worker CollectorType foreground_collector_type,
290*795d594fSAndroid Build Coastguard Worker CollectorType background_collector_type,
291*795d594fSAndroid Build Coastguard Worker space::LargeObjectSpaceType large_object_space_type,
292*795d594fSAndroid Build Coastguard Worker size_t large_object_threshold,
293*795d594fSAndroid Build Coastguard Worker size_t parallel_gc_threads,
294*795d594fSAndroid Build Coastguard Worker size_t conc_gc_threads,
295*795d594fSAndroid Build Coastguard Worker bool low_memory_mode,
296*795d594fSAndroid Build Coastguard Worker size_t long_pause_log_threshold,
297*795d594fSAndroid Build Coastguard Worker size_t long_gc_log_threshold,
298*795d594fSAndroid Build Coastguard Worker bool ignore_target_footprint,
299*795d594fSAndroid Build Coastguard Worker bool always_log_explicit_gcs,
300*795d594fSAndroid Build Coastguard Worker bool use_tlab,
301*795d594fSAndroid Build Coastguard Worker bool verify_pre_gc_heap,
302*795d594fSAndroid Build Coastguard Worker bool verify_pre_sweeping_heap,
303*795d594fSAndroid Build Coastguard Worker bool verify_post_gc_heap,
304*795d594fSAndroid Build Coastguard Worker bool verify_pre_gc_rosalloc,
305*795d594fSAndroid Build Coastguard Worker bool verify_pre_sweeping_rosalloc,
306*795d594fSAndroid Build Coastguard Worker bool verify_post_gc_rosalloc,
307*795d594fSAndroid Build Coastguard Worker bool gc_stress_mode,
308*795d594fSAndroid Build Coastguard Worker bool measure_gc_performance,
309*795d594fSAndroid Build Coastguard Worker bool use_homogeneous_space_compaction_for_oom,
310*795d594fSAndroid Build Coastguard Worker bool use_generational_cc,
311*795d594fSAndroid Build Coastguard Worker uint64_t min_interval_homogeneous_space_compaction_by_oom,
312*795d594fSAndroid Build Coastguard Worker bool dump_region_info_before_gc,
313*795d594fSAndroid Build Coastguard Worker bool dump_region_info_after_gc)
314*795d594fSAndroid Build Coastguard Worker : non_moving_space_(nullptr),
315*795d594fSAndroid Build Coastguard Worker rosalloc_space_(nullptr),
316*795d594fSAndroid Build Coastguard Worker dlmalloc_space_(nullptr),
317*795d594fSAndroid Build Coastguard Worker main_space_(nullptr),
318*795d594fSAndroid Build Coastguard Worker collector_type_(kCollectorTypeNone),
319*795d594fSAndroid Build Coastguard Worker foreground_collector_type_(foreground_collector_type),
320*795d594fSAndroid Build Coastguard Worker background_collector_type_(background_collector_type),
321*795d594fSAndroid Build Coastguard Worker desired_collector_type_(foreground_collector_type_),
322*795d594fSAndroid Build Coastguard Worker pending_task_lock_(nullptr),
323*795d594fSAndroid Build Coastguard Worker parallel_gc_threads_(parallel_gc_threads),
324*795d594fSAndroid Build Coastguard Worker conc_gc_threads_(conc_gc_threads),
325*795d594fSAndroid Build Coastguard Worker low_memory_mode_(low_memory_mode),
326*795d594fSAndroid Build Coastguard Worker long_pause_log_threshold_(long_pause_log_threshold),
327*795d594fSAndroid Build Coastguard Worker long_gc_log_threshold_(long_gc_log_threshold),
328*795d594fSAndroid Build Coastguard Worker process_cpu_start_time_ns_(ProcessCpuNanoTime()),
329*795d594fSAndroid Build Coastguard Worker pre_gc_last_process_cpu_time_ns_(process_cpu_start_time_ns_),
330*795d594fSAndroid Build Coastguard Worker post_gc_last_process_cpu_time_ns_(process_cpu_start_time_ns_),
331*795d594fSAndroid Build Coastguard Worker pre_gc_weighted_allocated_bytes_(0.0),
332*795d594fSAndroid Build Coastguard Worker post_gc_weighted_allocated_bytes_(0.0),
333*795d594fSAndroid Build Coastguard Worker ignore_target_footprint_(ignore_target_footprint),
334*795d594fSAndroid Build Coastguard Worker always_log_explicit_gcs_(always_log_explicit_gcs),
335*795d594fSAndroid Build Coastguard Worker zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
336*795d594fSAndroid Build Coastguard Worker zygote_space_(nullptr),
337*795d594fSAndroid Build Coastguard Worker large_object_threshold_(large_object_threshold),
338*795d594fSAndroid Build Coastguard Worker disable_thread_flip_count_(0),
339*795d594fSAndroid Build Coastguard Worker thread_flip_running_(false),
340*795d594fSAndroid Build Coastguard Worker collector_type_running_(kCollectorTypeNone),
341*795d594fSAndroid Build Coastguard Worker last_gc_cause_(kGcCauseNone),
342*795d594fSAndroid Build Coastguard Worker thread_running_gc_(nullptr),
343*795d594fSAndroid Build Coastguard Worker last_gc_type_(collector::kGcTypeNone),
344*795d594fSAndroid Build Coastguard Worker next_gc_type_(collector::kGcTypePartial),
345*795d594fSAndroid Build Coastguard Worker capacity_(capacity),
346*795d594fSAndroid Build Coastguard Worker growth_limit_(growth_limit),
347*795d594fSAndroid Build Coastguard Worker initial_heap_size_(initial_size),
348*795d594fSAndroid Build Coastguard Worker target_footprint_(initial_size),
349*795d594fSAndroid Build Coastguard Worker // Using kPostMonitorLock as a lock at kDefaultMutexLevel is acquired after
350*795d594fSAndroid Build Coastguard Worker // this one.
351*795d594fSAndroid Build Coastguard Worker process_state_update_lock_("process state update lock", kPostMonitorLock),
352*795d594fSAndroid Build Coastguard Worker min_foreground_target_footprint_(0),
353*795d594fSAndroid Build Coastguard Worker min_foreground_concurrent_start_bytes_(0),
354*795d594fSAndroid Build Coastguard Worker concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
355*795d594fSAndroid Build Coastguard Worker total_bytes_freed_ever_(0),
356*795d594fSAndroid Build Coastguard Worker total_objects_freed_ever_(0),
357*795d594fSAndroid Build Coastguard Worker num_bytes_allocated_(0),
358*795d594fSAndroid Build Coastguard Worker native_bytes_registered_(0),
359*795d594fSAndroid Build Coastguard Worker old_native_bytes_allocated_(0),
360*795d594fSAndroid Build Coastguard Worker native_objects_notified_(0),
361*795d594fSAndroid Build Coastguard Worker num_bytes_freed_revoke_(0),
362*795d594fSAndroid Build Coastguard Worker num_bytes_alive_after_gc_(0),
363*795d594fSAndroid Build Coastguard Worker verify_missing_card_marks_(false),
364*795d594fSAndroid Build Coastguard Worker verify_system_weaks_(false),
365*795d594fSAndroid Build Coastguard Worker verify_pre_gc_heap_(verify_pre_gc_heap),
366*795d594fSAndroid Build Coastguard Worker verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
367*795d594fSAndroid Build Coastguard Worker verify_post_gc_heap_(verify_post_gc_heap),
368*795d594fSAndroid Build Coastguard Worker verify_mod_union_table_(false),
369*795d594fSAndroid Build Coastguard Worker verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
370*795d594fSAndroid Build Coastguard Worker verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
371*795d594fSAndroid Build Coastguard Worker verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
372*795d594fSAndroid Build Coastguard Worker gc_stress_mode_(gc_stress_mode),
373*795d594fSAndroid Build Coastguard Worker /* For GC a lot mode, we limit the allocation stacks to be kGcAlotInterval allocations. This
374*795d594fSAndroid Build Coastguard Worker * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
375*795d594fSAndroid Build Coastguard Worker * verification is enabled, we limit the size of allocation stacks to speed up their
376*795d594fSAndroid Build Coastguard Worker * searching.
377*795d594fSAndroid Build Coastguard Worker */
378*795d594fSAndroid Build Coastguard Worker max_allocation_stack_size_(kGCALotMode
379*795d594fSAndroid Build Coastguard Worker ? kGcAlotAllocationStackSize
380*795d594fSAndroid Build Coastguard Worker : (kVerifyObjectSupport > kVerifyObjectModeFast)
381*795d594fSAndroid Build Coastguard Worker ? kVerifyObjectAllocationStackSize
382*795d594fSAndroid Build Coastguard Worker : kDefaultAllocationStackSize),
383*795d594fSAndroid Build Coastguard Worker current_allocator_(kAllocatorTypeDlMalloc),
384*795d594fSAndroid Build Coastguard Worker current_non_moving_allocator_(kAllocatorTypeNonMoving),
385*795d594fSAndroid Build Coastguard Worker bump_pointer_space_(nullptr),
386*795d594fSAndroid Build Coastguard Worker temp_space_(nullptr),
387*795d594fSAndroid Build Coastguard Worker region_space_(nullptr),
388*795d594fSAndroid Build Coastguard Worker min_free_(min_free),
389*795d594fSAndroid Build Coastguard Worker max_free_(max_free),
390*795d594fSAndroid Build Coastguard Worker target_utilization_(target_utilization),
391*795d594fSAndroid Build Coastguard Worker foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
392*795d594fSAndroid Build Coastguard Worker stop_for_native_allocs_(stop_for_native_allocs),
393*795d594fSAndroid Build Coastguard Worker total_wait_time_(0),
394*795d594fSAndroid Build Coastguard Worker verify_object_mode_(kVerifyObjectModeDisabled),
395*795d594fSAndroid Build Coastguard Worker disable_moving_gc_count_(0),
396*795d594fSAndroid Build Coastguard Worker semi_space_collector_(nullptr),
397*795d594fSAndroid Build Coastguard Worker active_concurrent_copying_collector_(nullptr),
398*795d594fSAndroid Build Coastguard Worker young_concurrent_copying_collector_(nullptr),
399*795d594fSAndroid Build Coastguard Worker concurrent_copying_collector_(nullptr),
400*795d594fSAndroid Build Coastguard Worker is_running_on_memory_tool_(Runtime::Current()->IsRunningOnMemoryTool()),
401*795d594fSAndroid Build Coastguard Worker use_tlab_(use_tlab),
402*795d594fSAndroid Build Coastguard Worker main_space_backup_(nullptr),
403*795d594fSAndroid Build Coastguard Worker min_interval_homogeneous_space_compaction_by_oom_(
404*795d594fSAndroid Build Coastguard Worker min_interval_homogeneous_space_compaction_by_oom),
405*795d594fSAndroid Build Coastguard Worker last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
406*795d594fSAndroid Build Coastguard Worker gcs_completed_(0u),
407*795d594fSAndroid Build Coastguard Worker max_gc_requested_(0u),
408*795d594fSAndroid Build Coastguard Worker pending_collector_transition_(nullptr),
409*795d594fSAndroid Build Coastguard Worker pending_heap_trim_(nullptr),
410*795d594fSAndroid Build Coastguard Worker use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom),
411*795d594fSAndroid Build Coastguard Worker use_generational_cc_(use_generational_cc),
412*795d594fSAndroid Build Coastguard Worker running_collection_is_blocking_(false),
413*795d594fSAndroid Build Coastguard Worker blocking_gc_count_(0U),
414*795d594fSAndroid Build Coastguard Worker blocking_gc_time_(0U),
415*795d594fSAndroid Build Coastguard Worker last_update_time_gc_count_rate_histograms_( // Round down by the window duration.
416*795d594fSAndroid Build Coastguard Worker (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration),
417*795d594fSAndroid Build Coastguard Worker gc_count_last_window_(0U),
418*795d594fSAndroid Build Coastguard Worker blocking_gc_count_last_window_(0U),
419*795d594fSAndroid Build Coastguard Worker gc_count_rate_histogram_("gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
420*795d594fSAndroid Build Coastguard Worker blocking_gc_count_rate_histogram_(
421*795d594fSAndroid Build Coastguard Worker "blocking gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
422*795d594fSAndroid Build Coastguard Worker alloc_tracking_enabled_(false),
423*795d594fSAndroid Build Coastguard Worker alloc_record_depth_(AllocRecordObjectMap::kDefaultAllocStackDepth),
424*795d594fSAndroid Build Coastguard Worker backtrace_lock_(nullptr),
425*795d594fSAndroid Build Coastguard Worker seen_backtrace_count_(0u),
426*795d594fSAndroid Build Coastguard Worker unique_backtrace_count_(0u),
427*795d594fSAndroid Build Coastguard Worker gc_disabled_for_shutdown_(false),
428*795d594fSAndroid Build Coastguard Worker dump_region_info_before_gc_(dump_region_info_before_gc),
429*795d594fSAndroid Build Coastguard Worker dump_region_info_after_gc_(dump_region_info_after_gc),
430*795d594fSAndroid Build Coastguard Worker boot_image_spaces_(),
431*795d594fSAndroid Build Coastguard Worker boot_images_start_address_(0u),
432*795d594fSAndroid Build Coastguard Worker boot_images_size_(0u),
433*795d594fSAndroid Build Coastguard Worker pre_oome_gc_count_(0u) {
434*795d594fSAndroid Build Coastguard Worker if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
435*795d594fSAndroid Build Coastguard Worker LOG(INFO) << "Heap() entering";
436*795d594fSAndroid Build Coastguard Worker }
437*795d594fSAndroid Build Coastguard Worker
438*795d594fSAndroid Build Coastguard Worker LOG(INFO) << "Using " << foreground_collector_type_ << " GC.";
439*795d594fSAndroid Build Coastguard Worker if (gUseUserfaultfd) {
440*795d594fSAndroid Build Coastguard Worker CHECK_EQ(foreground_collector_type_, kCollectorTypeCMC);
441*795d594fSAndroid Build Coastguard Worker CHECK_EQ(background_collector_type_, kCollectorTypeCMCBackground);
442*795d594fSAndroid Build Coastguard Worker } else {
443*795d594fSAndroid Build Coastguard Worker // This ensures that userfaultfd syscall is done before any seccomp filter is installed.
444*795d594fSAndroid Build Coastguard Worker // TODO(b/266731037): Remove this when we no longer need to collect metric on userfaultfd
445*795d594fSAndroid Build Coastguard Worker // support.
446*795d594fSAndroid Build Coastguard Worker auto [uffd_supported, minor_fault_supported] = collector::MarkCompact::GetUffdAndMinorFault();
447*795d594fSAndroid Build Coastguard Worker // The check is just to ensure that compiler doesn't eliminate the function call above.
448*795d594fSAndroid Build Coastguard Worker // Userfaultfd support is certain to be there if its minor-fault feature is supported.
449*795d594fSAndroid Build Coastguard Worker CHECK_IMPLIES(minor_fault_supported, uffd_supported);
450*795d594fSAndroid Build Coastguard Worker }
451*795d594fSAndroid Build Coastguard Worker
452*795d594fSAndroid Build Coastguard Worker if (gUseReadBarrier) {
453*795d594fSAndroid Build Coastguard Worker CHECK_EQ(foreground_collector_type_, kCollectorTypeCC);
454*795d594fSAndroid Build Coastguard Worker CHECK_EQ(background_collector_type_, kCollectorTypeCCBackground);
455*795d594fSAndroid Build Coastguard Worker } else if (background_collector_type_ != gc::kCollectorTypeHomogeneousSpaceCompact) {
456*795d594fSAndroid Build Coastguard Worker CHECK_EQ(IsMovingGc(foreground_collector_type_), IsMovingGc(background_collector_type_))
457*795d594fSAndroid Build Coastguard Worker << "Changing from " << foreground_collector_type_ << " to "
458*795d594fSAndroid Build Coastguard Worker << background_collector_type_ << " (or visa versa) is not supported.";
459*795d594fSAndroid Build Coastguard Worker }
460*795d594fSAndroid Build Coastguard Worker verification_.reset(new Verification(this));
461*795d594fSAndroid Build Coastguard Worker CHECK_GE(large_object_threshold, kMinLargeObjectThreshold);
462*795d594fSAndroid Build Coastguard Worker ScopedTrace trace(__FUNCTION__);
463*795d594fSAndroid Build Coastguard Worker Runtime* const runtime = Runtime::Current();
464*795d594fSAndroid Build Coastguard Worker // If we aren't the zygote, switch to the default non zygote allocator. This may update the
465*795d594fSAndroid Build Coastguard Worker // entrypoints.
466*795d594fSAndroid Build Coastguard Worker const bool is_zygote = runtime->IsZygote();
467*795d594fSAndroid Build Coastguard Worker if (!is_zygote) {
468*795d594fSAndroid Build Coastguard Worker // Background compaction is currently not supported for command line runs.
469*795d594fSAndroid Build Coastguard Worker if (background_collector_type_ != foreground_collector_type_) {
470*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Disabling background compaction for non zygote";
471*795d594fSAndroid Build Coastguard Worker background_collector_type_ = foreground_collector_type_;
472*795d594fSAndroid Build Coastguard Worker }
473*795d594fSAndroid Build Coastguard Worker }
474*795d594fSAndroid Build Coastguard Worker ChangeCollector(desired_collector_type_);
475*795d594fSAndroid Build Coastguard Worker live_bitmap_.reset(new accounting::HeapBitmap(this));
476*795d594fSAndroid Build Coastguard Worker mark_bitmap_.reset(new accounting::HeapBitmap(this));
477*795d594fSAndroid Build Coastguard Worker
478*795d594fSAndroid Build Coastguard Worker // We don't have hspace compaction enabled with CC.
479*795d594fSAndroid Build Coastguard Worker if (foreground_collector_type_ == kCollectorTypeCC
480*795d594fSAndroid Build Coastguard Worker || foreground_collector_type_ == kCollectorTypeCMC) {
481*795d594fSAndroid Build Coastguard Worker use_homogeneous_space_compaction_for_oom_ = false;
482*795d594fSAndroid Build Coastguard Worker }
483*795d594fSAndroid Build Coastguard Worker bool support_homogeneous_space_compaction =
484*795d594fSAndroid Build Coastguard Worker background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
485*795d594fSAndroid Build Coastguard Worker use_homogeneous_space_compaction_for_oom_;
486*795d594fSAndroid Build Coastguard Worker // We may use the same space the main space for the non moving space if we don't need to compact
487*795d594fSAndroid Build Coastguard Worker // from the main space.
488*795d594fSAndroid Build Coastguard Worker // This is not the case if we support homogeneous compaction or have a moving background
489*795d594fSAndroid Build Coastguard Worker // collector type.
490*795d594fSAndroid Build Coastguard Worker bool separate_non_moving_space = is_zygote ||
491*795d594fSAndroid Build Coastguard Worker support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
492*795d594fSAndroid Build Coastguard Worker IsMovingGc(background_collector_type_);
493*795d594fSAndroid Build Coastguard Worker
494*795d594fSAndroid Build Coastguard Worker // Requested begin for the alloc space, to follow the mapped image and oat files
495*795d594fSAndroid Build Coastguard Worker uint8_t* request_begin = nullptr;
496*795d594fSAndroid Build Coastguard Worker // Calculate the extra space required after the boot image, see allocations below.
497*795d594fSAndroid Build Coastguard Worker size_t heap_reservation_size = 0u;
498*795d594fSAndroid Build Coastguard Worker if (separate_non_moving_space) {
499*795d594fSAndroid Build Coastguard Worker heap_reservation_size = non_moving_space_capacity;
500*795d594fSAndroid Build Coastguard Worker } else if (foreground_collector_type_ != kCollectorTypeCC && is_zygote) {
501*795d594fSAndroid Build Coastguard Worker heap_reservation_size = capacity_;
502*795d594fSAndroid Build Coastguard Worker }
503*795d594fSAndroid Build Coastguard Worker heap_reservation_size = RoundUp(heap_reservation_size, gPageSize);
504*795d594fSAndroid Build Coastguard Worker // Load image space(s).
505*795d594fSAndroid Build Coastguard Worker std::vector<std::unique_ptr<space::ImageSpace>> boot_image_spaces;
506*795d594fSAndroid Build Coastguard Worker MemMap heap_reservation;
507*795d594fSAndroid Build Coastguard Worker if (space::ImageSpace::LoadBootImage(boot_class_path,
508*795d594fSAndroid Build Coastguard Worker boot_class_path_locations,
509*795d594fSAndroid Build Coastguard Worker boot_class_path_files,
510*795d594fSAndroid Build Coastguard Worker boot_class_path_image_files,
511*795d594fSAndroid Build Coastguard Worker boot_class_path_vdex_files,
512*795d594fSAndroid Build Coastguard Worker boot_class_path_oat_files,
513*795d594fSAndroid Build Coastguard Worker image_file_names,
514*795d594fSAndroid Build Coastguard Worker image_instruction_set,
515*795d594fSAndroid Build Coastguard Worker runtime->ShouldRelocate(),
516*795d594fSAndroid Build Coastguard Worker /*executable=*/!runtime->IsAotCompiler(),
517*795d594fSAndroid Build Coastguard Worker heap_reservation_size,
518*795d594fSAndroid Build Coastguard Worker runtime->AllowInMemoryCompilation(),
519*795d594fSAndroid Build Coastguard Worker runtime->GetApexVersions(),
520*795d594fSAndroid Build Coastguard Worker &boot_image_spaces,
521*795d594fSAndroid Build Coastguard Worker &heap_reservation)) {
522*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(heap_reservation_size, heap_reservation.IsValid() ? heap_reservation.Size() : 0u);
523*795d594fSAndroid Build Coastguard Worker DCHECK(!boot_image_spaces.empty());
524*795d594fSAndroid Build Coastguard Worker request_begin = boot_image_spaces.back()->GetImageHeader().GetOatFileEnd();
525*795d594fSAndroid Build Coastguard Worker DCHECK_IMPLIES(heap_reservation.IsValid(), request_begin == heap_reservation.Begin())
526*795d594fSAndroid Build Coastguard Worker << "request_begin=" << static_cast<const void*>(request_begin)
527*795d594fSAndroid Build Coastguard Worker << " heap_reservation.Begin()=" << static_cast<const void*>(heap_reservation.Begin());
528*795d594fSAndroid Build Coastguard Worker for (std::unique_ptr<space::ImageSpace>& space : boot_image_spaces) {
529*795d594fSAndroid Build Coastguard Worker boot_image_spaces_.push_back(space.get());
530*795d594fSAndroid Build Coastguard Worker AddSpace(space.release());
531*795d594fSAndroid Build Coastguard Worker }
532*795d594fSAndroid Build Coastguard Worker boot_images_start_address_ = PointerToLowMemUInt32(boot_image_spaces_.front()->Begin());
533*795d594fSAndroid Build Coastguard Worker uint32_t boot_images_end =
534*795d594fSAndroid Build Coastguard Worker PointerToLowMemUInt32(boot_image_spaces_.back()->GetImageHeader().GetOatFileEnd());
535*795d594fSAndroid Build Coastguard Worker boot_images_size_ = boot_images_end - boot_images_start_address_;
536*795d594fSAndroid Build Coastguard Worker if (kIsDebugBuild) {
537*795d594fSAndroid Build Coastguard Worker VerifyBootImagesContiguity(boot_image_spaces_);
538*795d594fSAndroid Build Coastguard Worker }
539*795d594fSAndroid Build Coastguard Worker } else {
540*795d594fSAndroid Build Coastguard Worker if (foreground_collector_type_ == kCollectorTypeCC) {
541*795d594fSAndroid Build Coastguard Worker // Need to use a low address so that we can allocate a contiguous 2 * Xmx space
542*795d594fSAndroid Build Coastguard Worker // when there's no image (dex2oat for target).
543*795d594fSAndroid Build Coastguard Worker request_begin = kPreferredAllocSpaceBegin;
544*795d594fSAndroid Build Coastguard Worker }
545*795d594fSAndroid Build Coastguard Worker // Gross hack to make dex2oat deterministic.
546*795d594fSAndroid Build Coastguard Worker if (foreground_collector_type_ == kCollectorTypeMS && Runtime::Current()->IsAotCompiler()) {
547*795d594fSAndroid Build Coastguard Worker // Currently only enabled for MS collector since that is what the deterministic dex2oat uses.
548*795d594fSAndroid Build Coastguard Worker // b/26849108
549*795d594fSAndroid Build Coastguard Worker request_begin = reinterpret_cast<uint8_t*>(kAllocSpaceBeginForDeterministicAoT);
550*795d594fSAndroid Build Coastguard Worker }
551*795d594fSAndroid Build Coastguard Worker }
552*795d594fSAndroid Build Coastguard Worker
553*795d594fSAndroid Build Coastguard Worker /*
554*795d594fSAndroid Build Coastguard Worker requested_alloc_space_begin -> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
555*795d594fSAndroid Build Coastguard Worker +- nonmoving space (non_moving_space_capacity)+-
556*795d594fSAndroid Build Coastguard Worker +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
557*795d594fSAndroid Build Coastguard Worker +-????????????????????????????????????????????+-
558*795d594fSAndroid Build Coastguard Worker +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
559*795d594fSAndroid Build Coastguard Worker +-main alloc space / bump space 1 (capacity_) +-
560*795d594fSAndroid Build Coastguard Worker +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
561*795d594fSAndroid Build Coastguard Worker +-????????????????????????????????????????????+-
562*795d594fSAndroid Build Coastguard Worker +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
563*795d594fSAndroid Build Coastguard Worker +-main alloc space2 / bump space 2 (capacity_)+-
564*795d594fSAndroid Build Coastguard Worker +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
565*795d594fSAndroid Build Coastguard Worker */
566*795d594fSAndroid Build Coastguard Worker
567*795d594fSAndroid Build Coastguard Worker MemMap main_mem_map_1;
568*795d594fSAndroid Build Coastguard Worker MemMap main_mem_map_2;
569*795d594fSAndroid Build Coastguard Worker
570*795d594fSAndroid Build Coastguard Worker std::string error_str;
571*795d594fSAndroid Build Coastguard Worker MemMap non_moving_space_mem_map;
572*795d594fSAndroid Build Coastguard Worker if (separate_non_moving_space) {
573*795d594fSAndroid Build Coastguard Worker ScopedTrace trace2("Create separate non moving space");
574*795d594fSAndroid Build Coastguard Worker // If we are the zygote, the non moving space becomes the zygote space when we run
575*795d594fSAndroid Build Coastguard Worker // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
576*795d594fSAndroid Build Coastguard Worker // rename the mem map later.
577*795d594fSAndroid Build Coastguard Worker const char* space_name = is_zygote ? kZygoteSpaceName : kNonMovingSpaceName;
578*795d594fSAndroid Build Coastguard Worker // Reserve the non moving mem map before the other two since it needs to be at a specific
579*795d594fSAndroid Build Coastguard Worker // address.
580*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(heap_reservation.IsValid(), !boot_image_spaces_.empty());
581*795d594fSAndroid Build Coastguard Worker if (heap_reservation.IsValid()) {
582*795d594fSAndroid Build Coastguard Worker non_moving_space_mem_map = heap_reservation.RemapAtEnd(
583*795d594fSAndroid Build Coastguard Worker heap_reservation.Begin(), space_name, PROT_READ | PROT_WRITE, &error_str);
584*795d594fSAndroid Build Coastguard Worker } else {
585*795d594fSAndroid Build Coastguard Worker non_moving_space_mem_map = MapAnonymousPreferredAddress(
586*795d594fSAndroid Build Coastguard Worker space_name, request_begin, non_moving_space_capacity, &error_str);
587*795d594fSAndroid Build Coastguard Worker }
588*795d594fSAndroid Build Coastguard Worker CHECK(non_moving_space_mem_map.IsValid()) << error_str;
589*795d594fSAndroid Build Coastguard Worker DCHECK(!heap_reservation.IsValid());
590*795d594fSAndroid Build Coastguard Worker // Try to reserve virtual memory at a lower address if we have a separate non moving space.
591*795d594fSAndroid Build Coastguard Worker request_begin = non_moving_space_mem_map.Begin() == kPreferredAllocSpaceBegin
592*795d594fSAndroid Build Coastguard Worker ? non_moving_space_mem_map.End()
593*795d594fSAndroid Build Coastguard Worker : kPreferredAllocSpaceBegin;
594*795d594fSAndroid Build Coastguard Worker }
595*795d594fSAndroid Build Coastguard Worker // Attempt to create 2 mem maps at or after the requested begin.
596*795d594fSAndroid Build Coastguard Worker if (foreground_collector_type_ != kCollectorTypeCC) {
597*795d594fSAndroid Build Coastguard Worker ScopedTrace trace2("Create main mem map");
598*795d594fSAndroid Build Coastguard Worker if (separate_non_moving_space || !is_zygote) {
599*795d594fSAndroid Build Coastguard Worker main_mem_map_1 = MapAnonymousPreferredAddress(
600*795d594fSAndroid Build Coastguard Worker kMemMapSpaceName[0], request_begin, capacity_, &error_str);
601*795d594fSAndroid Build Coastguard Worker } else {
602*795d594fSAndroid Build Coastguard Worker // If no separate non-moving space and we are the zygote, the main space must come right after
603*795d594fSAndroid Build Coastguard Worker // the image space to avoid a gap. This is required since we want the zygote space to be
604*795d594fSAndroid Build Coastguard Worker // adjacent to the image space.
605*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(heap_reservation.IsValid(), !boot_image_spaces_.empty());
606*795d594fSAndroid Build Coastguard Worker main_mem_map_1 = MemMap::MapAnonymous(
607*795d594fSAndroid Build Coastguard Worker kMemMapSpaceName[0],
608*795d594fSAndroid Build Coastguard Worker request_begin,
609*795d594fSAndroid Build Coastguard Worker capacity_,
610*795d594fSAndroid Build Coastguard Worker PROT_READ | PROT_WRITE,
611*795d594fSAndroid Build Coastguard Worker /* low_4gb= */ true,
612*795d594fSAndroid Build Coastguard Worker /* reuse= */ false,
613*795d594fSAndroid Build Coastguard Worker heap_reservation.IsValid() ? &heap_reservation : nullptr,
614*795d594fSAndroid Build Coastguard Worker &error_str);
615*795d594fSAndroid Build Coastguard Worker }
616*795d594fSAndroid Build Coastguard Worker CHECK(main_mem_map_1.IsValid()) << error_str;
617*795d594fSAndroid Build Coastguard Worker DCHECK(!heap_reservation.IsValid());
618*795d594fSAndroid Build Coastguard Worker }
619*795d594fSAndroid Build Coastguard Worker if (support_homogeneous_space_compaction ||
620*795d594fSAndroid Build Coastguard Worker background_collector_type_ == kCollectorTypeSS ||
621*795d594fSAndroid Build Coastguard Worker foreground_collector_type_ == kCollectorTypeSS) {
622*795d594fSAndroid Build Coastguard Worker ScopedTrace trace2("Create main mem map 2");
623*795d594fSAndroid Build Coastguard Worker main_mem_map_2 = MapAnonymousPreferredAddress(
624*795d594fSAndroid Build Coastguard Worker kMemMapSpaceName[1], main_mem_map_1.End(), capacity_, &error_str);
625*795d594fSAndroid Build Coastguard Worker CHECK(main_mem_map_2.IsValid()) << error_str;
626*795d594fSAndroid Build Coastguard Worker }
627*795d594fSAndroid Build Coastguard Worker
628*795d594fSAndroid Build Coastguard Worker // Create the non moving space first so that bitmaps don't take up the address range.
629*795d594fSAndroid Build Coastguard Worker if (separate_non_moving_space) {
630*795d594fSAndroid Build Coastguard Worker ScopedTrace trace2("Add non moving space");
631*795d594fSAndroid Build Coastguard Worker // Non moving space is always dlmalloc since we currently don't have support for multiple
632*795d594fSAndroid Build Coastguard Worker // active rosalloc spaces.
633*795d594fSAndroid Build Coastguard Worker const size_t size = non_moving_space_mem_map.Size();
634*795d594fSAndroid Build Coastguard Worker const void* non_moving_space_mem_map_begin = non_moving_space_mem_map.Begin();
635*795d594fSAndroid Build Coastguard Worker non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(std::move(non_moving_space_mem_map),
636*795d594fSAndroid Build Coastguard Worker "zygote / non moving space",
637*795d594fSAndroid Build Coastguard Worker GetDefaultStartingSize(),
638*795d594fSAndroid Build Coastguard Worker initial_size,
639*795d594fSAndroid Build Coastguard Worker size,
640*795d594fSAndroid Build Coastguard Worker size,
641*795d594fSAndroid Build Coastguard Worker /* can_move_objects= */ false);
642*795d594fSAndroid Build Coastguard Worker CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
643*795d594fSAndroid Build Coastguard Worker << non_moving_space_mem_map_begin;
644*795d594fSAndroid Build Coastguard Worker non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
645*795d594fSAndroid Build Coastguard Worker AddSpace(non_moving_space_);
646*795d594fSAndroid Build Coastguard Worker }
647*795d594fSAndroid Build Coastguard Worker // Create other spaces based on whether or not we have a moving GC.
648*795d594fSAndroid Build Coastguard Worker if (foreground_collector_type_ == kCollectorTypeCC) {
649*795d594fSAndroid Build Coastguard Worker CHECK(separate_non_moving_space);
650*795d594fSAndroid Build Coastguard Worker // Reserve twice the capacity, to allow evacuating every region for explicit GCs.
651*795d594fSAndroid Build Coastguard Worker MemMap region_space_mem_map =
652*795d594fSAndroid Build Coastguard Worker space::RegionSpace::CreateMemMap(kRegionSpaceName, capacity_ * 2, request_begin);
653*795d594fSAndroid Build Coastguard Worker CHECK(region_space_mem_map.IsValid()) << "No region space mem map";
654*795d594fSAndroid Build Coastguard Worker region_space_ = space::RegionSpace::Create(
655*795d594fSAndroid Build Coastguard Worker kRegionSpaceName, std::move(region_space_mem_map), use_generational_cc_);
656*795d594fSAndroid Build Coastguard Worker AddSpace(region_space_);
657*795d594fSAndroid Build Coastguard Worker } else if (IsMovingGc(foreground_collector_type_)) {
658*795d594fSAndroid Build Coastguard Worker // Create bump pointer spaces.
659*795d594fSAndroid Build Coastguard Worker // We only to create the bump pointer if the foreground collector is a compacting GC.
660*795d594fSAndroid Build Coastguard Worker // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
661*795d594fSAndroid Build Coastguard Worker bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
662*795d594fSAndroid Build Coastguard Worker std::move(main_mem_map_1));
663*795d594fSAndroid Build Coastguard Worker CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
664*795d594fSAndroid Build Coastguard Worker AddSpace(bump_pointer_space_);
665*795d594fSAndroid Build Coastguard Worker // For Concurrent Mark-compact GC we don't need the temp space to be in
666*795d594fSAndroid Build Coastguard Worker // lower 4GB. So its temp space will be created by the GC itself.
667*795d594fSAndroid Build Coastguard Worker if (foreground_collector_type_ != kCollectorTypeCMC) {
668*795d594fSAndroid Build Coastguard Worker temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
669*795d594fSAndroid Build Coastguard Worker std::move(main_mem_map_2));
670*795d594fSAndroid Build Coastguard Worker CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
671*795d594fSAndroid Build Coastguard Worker AddSpace(temp_space_);
672*795d594fSAndroid Build Coastguard Worker }
673*795d594fSAndroid Build Coastguard Worker CHECK(separate_non_moving_space);
674*795d594fSAndroid Build Coastguard Worker } else {
675*795d594fSAndroid Build Coastguard Worker CreateMainMallocSpace(std::move(main_mem_map_1), initial_size, growth_limit_, capacity_);
676*795d594fSAndroid Build Coastguard Worker CHECK(main_space_ != nullptr);
677*795d594fSAndroid Build Coastguard Worker AddSpace(main_space_);
678*795d594fSAndroid Build Coastguard Worker if (!separate_non_moving_space) {
679*795d594fSAndroid Build Coastguard Worker non_moving_space_ = main_space_;
680*795d594fSAndroid Build Coastguard Worker CHECK(!non_moving_space_->CanMoveObjects());
681*795d594fSAndroid Build Coastguard Worker }
682*795d594fSAndroid Build Coastguard Worker if (main_mem_map_2.IsValid()) {
683*795d594fSAndroid Build Coastguard Worker const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
684*795d594fSAndroid Build Coastguard Worker main_space_backup_.reset(CreateMallocSpaceFromMemMap(std::move(main_mem_map_2),
685*795d594fSAndroid Build Coastguard Worker initial_size,
686*795d594fSAndroid Build Coastguard Worker growth_limit_,
687*795d594fSAndroid Build Coastguard Worker capacity_,
688*795d594fSAndroid Build Coastguard Worker name,
689*795d594fSAndroid Build Coastguard Worker /* can_move_objects= */ true));
690*795d594fSAndroid Build Coastguard Worker CHECK(main_space_backup_.get() != nullptr);
691*795d594fSAndroid Build Coastguard Worker // Add the space so its accounted for in the heap_begin and heap_end.
692*795d594fSAndroid Build Coastguard Worker AddSpace(main_space_backup_.get());
693*795d594fSAndroid Build Coastguard Worker }
694*795d594fSAndroid Build Coastguard Worker }
695*795d594fSAndroid Build Coastguard Worker CHECK(non_moving_space_ != nullptr);
696*795d594fSAndroid Build Coastguard Worker CHECK(!non_moving_space_->CanMoveObjects());
697*795d594fSAndroid Build Coastguard Worker // Allocate the large object space.
698*795d594fSAndroid Build Coastguard Worker if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
699*795d594fSAndroid Build Coastguard Worker large_object_space_ = space::FreeListSpace::Create("free list large object space", capacity_);
700*795d594fSAndroid Build Coastguard Worker CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
701*795d594fSAndroid Build Coastguard Worker } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
702*795d594fSAndroid Build Coastguard Worker large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
703*795d594fSAndroid Build Coastguard Worker CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
704*795d594fSAndroid Build Coastguard Worker } else {
705*795d594fSAndroid Build Coastguard Worker // Disable the large object space by making the cutoff excessively large.
706*795d594fSAndroid Build Coastguard Worker large_object_threshold_ = std::numeric_limits<size_t>::max();
707*795d594fSAndroid Build Coastguard Worker large_object_space_ = nullptr;
708*795d594fSAndroid Build Coastguard Worker }
709*795d594fSAndroid Build Coastguard Worker if (large_object_space_ != nullptr) {
710*795d594fSAndroid Build Coastguard Worker AddSpace(large_object_space_);
711*795d594fSAndroid Build Coastguard Worker }
712*795d594fSAndroid Build Coastguard Worker // Compute heap capacity. Continuous spaces are sorted in order of Begin().
713*795d594fSAndroid Build Coastguard Worker CHECK(!continuous_spaces_.empty());
714*795d594fSAndroid Build Coastguard Worker // Relies on the spaces being sorted.
715*795d594fSAndroid Build Coastguard Worker uint8_t* heap_begin = continuous_spaces_.front()->Begin();
716*795d594fSAndroid Build Coastguard Worker uint8_t* heap_end = continuous_spaces_.back()->Limit();
717*795d594fSAndroid Build Coastguard Worker size_t heap_capacity = heap_end - heap_begin;
718*795d594fSAndroid Build Coastguard Worker // Remove the main backup space since it slows down the GC to have unused extra spaces.
719*795d594fSAndroid Build Coastguard Worker // TODO: Avoid needing to do this.
720*795d594fSAndroid Build Coastguard Worker if (main_space_backup_.get() != nullptr) {
721*795d594fSAndroid Build Coastguard Worker RemoveSpace(main_space_backup_.get());
722*795d594fSAndroid Build Coastguard Worker }
723*795d594fSAndroid Build Coastguard Worker // Allocate the card table.
724*795d594fSAndroid Build Coastguard Worker // We currently don't support dynamically resizing the card table.
725*795d594fSAndroid Build Coastguard Worker // Since we don't know where in the low_4gb the app image will be located, make the card table
726*795d594fSAndroid Build Coastguard Worker // cover the whole low_4gb. TODO: Extend the card table in AddSpace.
727*795d594fSAndroid Build Coastguard Worker UNUSED(heap_capacity);
728*795d594fSAndroid Build Coastguard Worker // Start at 4 KB, we can be sure there are no spaces mapped this low since the address range is
729*795d594fSAndroid Build Coastguard Worker // reserved by the kernel.
730*795d594fSAndroid Build Coastguard Worker static constexpr size_t kMinHeapAddress = 4 * KB;
731*795d594fSAndroid Build Coastguard Worker card_table_.reset(accounting::CardTable::Create(reinterpret_cast<uint8_t*>(kMinHeapAddress),
732*795d594fSAndroid Build Coastguard Worker 4 * GB - kMinHeapAddress));
733*795d594fSAndroid Build Coastguard Worker CHECK(card_table_.get() != nullptr) << "Failed to create card table";
734*795d594fSAndroid Build Coastguard Worker if (foreground_collector_type_ == kCollectorTypeCC && kUseTableLookupReadBarrier) {
735*795d594fSAndroid Build Coastguard Worker rb_table_.reset(new accounting::ReadBarrierTable());
736*795d594fSAndroid Build Coastguard Worker DCHECK(rb_table_->IsAllCleared());
737*795d594fSAndroid Build Coastguard Worker }
738*795d594fSAndroid Build Coastguard Worker if (HasBootImageSpace()) {
739*795d594fSAndroid Build Coastguard Worker // Don't add the image mod union table if we are running without an image, this can crash if
740*795d594fSAndroid Build Coastguard Worker // we use the CardCache implementation.
741*795d594fSAndroid Build Coastguard Worker for (space::ImageSpace* image_space : GetBootImageSpaces()) {
742*795d594fSAndroid Build Coastguard Worker accounting::ModUnionTable* mod_union_table = new accounting::ModUnionTableToZygoteAllocspace(
743*795d594fSAndroid Build Coastguard Worker "Image mod-union table", this, image_space);
744*795d594fSAndroid Build Coastguard Worker CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
745*795d594fSAndroid Build Coastguard Worker AddModUnionTable(mod_union_table);
746*795d594fSAndroid Build Coastguard Worker }
747*795d594fSAndroid Build Coastguard Worker }
748*795d594fSAndroid Build Coastguard Worker if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
749*795d594fSAndroid Build Coastguard Worker accounting::RememberedSet* non_moving_space_rem_set =
750*795d594fSAndroid Build Coastguard Worker new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
751*795d594fSAndroid Build Coastguard Worker CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
752*795d594fSAndroid Build Coastguard Worker AddRememberedSet(non_moving_space_rem_set);
753*795d594fSAndroid Build Coastguard Worker }
754*795d594fSAndroid Build Coastguard Worker // TODO: Count objects in the image space here?
755*795d594fSAndroid Build Coastguard Worker num_bytes_allocated_.store(0, std::memory_order_relaxed);
756*795d594fSAndroid Build Coastguard Worker mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
757*795d594fSAndroid Build Coastguard Worker kDefaultMarkStackSize));
758*795d594fSAndroid Build Coastguard Worker const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
759*795d594fSAndroid Build Coastguard Worker allocation_stack_.reset(accounting::ObjectStack::Create(
760*795d594fSAndroid Build Coastguard Worker "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
761*795d594fSAndroid Build Coastguard Worker live_stack_.reset(accounting::ObjectStack::Create(
762*795d594fSAndroid Build Coastguard Worker "live stack", max_allocation_stack_size_, alloc_stack_capacity));
763*795d594fSAndroid Build Coastguard Worker // It's still too early to take a lock because there are no threads yet, but we can create locks
764*795d594fSAndroid Build Coastguard Worker // now. We don't create it earlier to make it clear that you can't use locks during heap
765*795d594fSAndroid Build Coastguard Worker // initialization.
766*795d594fSAndroid Build Coastguard Worker gc_complete_lock_ = new Mutex("GC complete lock");
767*795d594fSAndroid Build Coastguard Worker gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
768*795d594fSAndroid Build Coastguard Worker *gc_complete_lock_));
769*795d594fSAndroid Build Coastguard Worker
770*795d594fSAndroid Build Coastguard Worker thread_flip_lock_ = new Mutex("GC thread flip lock");
771*795d594fSAndroid Build Coastguard Worker thread_flip_cond_.reset(new ConditionVariable("GC thread flip condition variable",
772*795d594fSAndroid Build Coastguard Worker *thread_flip_lock_));
773*795d594fSAndroid Build Coastguard Worker task_processor_.reset(new TaskProcessor());
774*795d594fSAndroid Build Coastguard Worker reference_processor_.reset(new ReferenceProcessor());
775*795d594fSAndroid Build Coastguard Worker pending_task_lock_ = new Mutex("Pending task lock");
776*795d594fSAndroid Build Coastguard Worker if (ignore_target_footprint_) {
777*795d594fSAndroid Build Coastguard Worker SetIdealFootprint(std::numeric_limits<size_t>::max());
778*795d594fSAndroid Build Coastguard Worker concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
779*795d594fSAndroid Build Coastguard Worker }
780*795d594fSAndroid Build Coastguard Worker CHECK_NE(target_footprint_.load(std::memory_order_relaxed), 0U);
781*795d594fSAndroid Build Coastguard Worker // Create our garbage collectors.
782*795d594fSAndroid Build Coastguard Worker for (size_t i = 0; i < 2; ++i) {
783*795d594fSAndroid Build Coastguard Worker const bool concurrent = i != 0;
784*795d594fSAndroid Build Coastguard Worker if ((MayUseCollector(kCollectorTypeCMS) && concurrent) ||
785*795d594fSAndroid Build Coastguard Worker (MayUseCollector(kCollectorTypeMS) && !concurrent)) {
786*795d594fSAndroid Build Coastguard Worker garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
787*795d594fSAndroid Build Coastguard Worker garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
788*795d594fSAndroid Build Coastguard Worker garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
789*795d594fSAndroid Build Coastguard Worker }
790*795d594fSAndroid Build Coastguard Worker }
791*795d594fSAndroid Build Coastguard Worker if (kMovingCollector) {
792*795d594fSAndroid Build Coastguard Worker if (MayUseCollector(kCollectorTypeSS) ||
793*795d594fSAndroid Build Coastguard Worker MayUseCollector(kCollectorTypeHomogeneousSpaceCompact) ||
794*795d594fSAndroid Build Coastguard Worker use_homogeneous_space_compaction_for_oom_) {
795*795d594fSAndroid Build Coastguard Worker semi_space_collector_ = new collector::SemiSpace(this);
796*795d594fSAndroid Build Coastguard Worker garbage_collectors_.push_back(semi_space_collector_);
797*795d594fSAndroid Build Coastguard Worker }
798*795d594fSAndroid Build Coastguard Worker if (MayUseCollector(kCollectorTypeCMC)) {
799*795d594fSAndroid Build Coastguard Worker mark_compact_ = new collector::MarkCompact(this);
800*795d594fSAndroid Build Coastguard Worker garbage_collectors_.push_back(mark_compact_);
801*795d594fSAndroid Build Coastguard Worker }
802*795d594fSAndroid Build Coastguard Worker if (MayUseCollector(kCollectorTypeCC)) {
803*795d594fSAndroid Build Coastguard Worker concurrent_copying_collector_ = new collector::ConcurrentCopying(this,
804*795d594fSAndroid Build Coastguard Worker /*young_gen=*/false,
805*795d594fSAndroid Build Coastguard Worker use_generational_cc_,
806*795d594fSAndroid Build Coastguard Worker "",
807*795d594fSAndroid Build Coastguard Worker measure_gc_performance);
808*795d594fSAndroid Build Coastguard Worker if (use_generational_cc_) {
809*795d594fSAndroid Build Coastguard Worker young_concurrent_copying_collector_ = new collector::ConcurrentCopying(
810*795d594fSAndroid Build Coastguard Worker this,
811*795d594fSAndroid Build Coastguard Worker /*young_gen=*/true,
812*795d594fSAndroid Build Coastguard Worker use_generational_cc_,
813*795d594fSAndroid Build Coastguard Worker "young",
814*795d594fSAndroid Build Coastguard Worker measure_gc_performance);
815*795d594fSAndroid Build Coastguard Worker }
816*795d594fSAndroid Build Coastguard Worker active_concurrent_copying_collector_.store(concurrent_copying_collector_,
817*795d594fSAndroid Build Coastguard Worker std::memory_order_relaxed);
818*795d594fSAndroid Build Coastguard Worker DCHECK(region_space_ != nullptr);
819*795d594fSAndroid Build Coastguard Worker concurrent_copying_collector_->SetRegionSpace(region_space_);
820*795d594fSAndroid Build Coastguard Worker if (use_generational_cc_) {
821*795d594fSAndroid Build Coastguard Worker young_concurrent_copying_collector_->SetRegionSpace(region_space_);
822*795d594fSAndroid Build Coastguard Worker // At this point, non-moving space should be created.
823*795d594fSAndroid Build Coastguard Worker DCHECK(non_moving_space_ != nullptr);
824*795d594fSAndroid Build Coastguard Worker concurrent_copying_collector_->CreateInterRegionRefBitmaps();
825*795d594fSAndroid Build Coastguard Worker }
826*795d594fSAndroid Build Coastguard Worker garbage_collectors_.push_back(concurrent_copying_collector_);
827*795d594fSAndroid Build Coastguard Worker if (use_generational_cc_) {
828*795d594fSAndroid Build Coastguard Worker garbage_collectors_.push_back(young_concurrent_copying_collector_);
829*795d594fSAndroid Build Coastguard Worker }
830*795d594fSAndroid Build Coastguard Worker }
831*795d594fSAndroid Build Coastguard Worker }
832*795d594fSAndroid Build Coastguard Worker if (!GetBootImageSpaces().empty() && non_moving_space_ != nullptr &&
833*795d594fSAndroid Build Coastguard Worker (is_zygote || separate_non_moving_space)) {
834*795d594fSAndroid Build Coastguard Worker // Check that there's no gap between the image space and the non moving space so that the
835*795d594fSAndroid Build Coastguard Worker // immune region won't break (eg. due to a large object allocated in the gap). This is only
836*795d594fSAndroid Build Coastguard Worker // required when we're the zygote.
837*795d594fSAndroid Build Coastguard Worker // Space with smallest Begin().
838*795d594fSAndroid Build Coastguard Worker space::ImageSpace* first_space = nullptr;
839*795d594fSAndroid Build Coastguard Worker for (space::ImageSpace* space : boot_image_spaces_) {
840*795d594fSAndroid Build Coastguard Worker if (first_space == nullptr || space->Begin() < first_space->Begin()) {
841*795d594fSAndroid Build Coastguard Worker first_space = space;
842*795d594fSAndroid Build Coastguard Worker }
843*795d594fSAndroid Build Coastguard Worker }
844*795d594fSAndroid Build Coastguard Worker bool no_gap = MemMap::CheckNoGaps(*first_space->GetMemMap(), *non_moving_space_->GetMemMap());
845*795d594fSAndroid Build Coastguard Worker if (!no_gap) {
846*795d594fSAndroid Build Coastguard Worker PrintFileToLog("/proc/self/maps", LogSeverity::ERROR);
847*795d594fSAndroid Build Coastguard Worker MemMap::DumpMaps(LOG_STREAM(ERROR), /* terse= */ true);
848*795d594fSAndroid Build Coastguard Worker LOG(FATAL) << "There's a gap between the image space and the non-moving space";
849*795d594fSAndroid Build Coastguard Worker }
850*795d594fSAndroid Build Coastguard Worker }
851*795d594fSAndroid Build Coastguard Worker // Perfetto Java Heap Profiler Support.
852*795d594fSAndroid Build Coastguard Worker if (runtime->IsPerfettoJavaHeapStackProfEnabled()) {
853*795d594fSAndroid Build Coastguard Worker // Perfetto Plugin is loaded and enabled, initialize the Java Heap Profiler.
854*795d594fSAndroid Build Coastguard Worker InitPerfettoJavaHeapProf();
855*795d594fSAndroid Build Coastguard Worker } else {
856*795d594fSAndroid Build Coastguard Worker // Disable the Java Heap Profiler.
857*795d594fSAndroid Build Coastguard Worker GetHeapSampler().DisableHeapSampler();
858*795d594fSAndroid Build Coastguard Worker }
859*795d594fSAndroid Build Coastguard Worker
860*795d594fSAndroid Build Coastguard Worker instrumentation::Instrumentation* const instrumentation = runtime->GetInstrumentation();
861*795d594fSAndroid Build Coastguard Worker if (gc_stress_mode_) {
862*795d594fSAndroid Build Coastguard Worker backtrace_lock_ = new Mutex("GC complete lock");
863*795d594fSAndroid Build Coastguard Worker }
864*795d594fSAndroid Build Coastguard Worker if (is_running_on_memory_tool_ || gc_stress_mode_) {
865*795d594fSAndroid Build Coastguard Worker instrumentation->InstrumentQuickAllocEntryPoints();
866*795d594fSAndroid Build Coastguard Worker }
867*795d594fSAndroid Build Coastguard Worker if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
868*795d594fSAndroid Build Coastguard Worker LOG(INFO) << "Heap() exiting";
869*795d594fSAndroid Build Coastguard Worker }
870*795d594fSAndroid Build Coastguard Worker }
871*795d594fSAndroid Build Coastguard Worker
MapAnonymousPreferredAddress(const char * name,uint8_t * request_begin,size_t capacity,std::string * out_error_str)872*795d594fSAndroid Build Coastguard Worker MemMap Heap::MapAnonymousPreferredAddress(const char* name,
873*795d594fSAndroid Build Coastguard Worker uint8_t* request_begin,
874*795d594fSAndroid Build Coastguard Worker size_t capacity,
875*795d594fSAndroid Build Coastguard Worker std::string* out_error_str) {
876*795d594fSAndroid Build Coastguard Worker while (true) {
877*795d594fSAndroid Build Coastguard Worker MemMap map = MemMap::MapAnonymous(name,
878*795d594fSAndroid Build Coastguard Worker request_begin,
879*795d594fSAndroid Build Coastguard Worker capacity,
880*795d594fSAndroid Build Coastguard Worker PROT_READ | PROT_WRITE,
881*795d594fSAndroid Build Coastguard Worker /*low_4gb=*/ true,
882*795d594fSAndroid Build Coastguard Worker /*reuse=*/ false,
883*795d594fSAndroid Build Coastguard Worker /*reservation=*/ nullptr,
884*795d594fSAndroid Build Coastguard Worker out_error_str);
885*795d594fSAndroid Build Coastguard Worker if (map.IsValid() || request_begin == nullptr) {
886*795d594fSAndroid Build Coastguard Worker return map;
887*795d594fSAndroid Build Coastguard Worker }
888*795d594fSAndroid Build Coastguard Worker // Retry a second time with no specified request begin.
889*795d594fSAndroid Build Coastguard Worker request_begin = nullptr;
890*795d594fSAndroid Build Coastguard Worker }
891*795d594fSAndroid Build Coastguard Worker }
892*795d594fSAndroid Build Coastguard Worker
MayUseCollector(CollectorType type) const893*795d594fSAndroid Build Coastguard Worker bool Heap::MayUseCollector(CollectorType type) const {
894*795d594fSAndroid Build Coastguard Worker return foreground_collector_type_ == type || background_collector_type_ == type;
895*795d594fSAndroid Build Coastguard Worker }
896*795d594fSAndroid Build Coastguard Worker
CreateMallocSpaceFromMemMap(MemMap && mem_map,size_t initial_size,size_t growth_limit,size_t capacity,const char * name,bool can_move_objects)897*795d594fSAndroid Build Coastguard Worker space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap&& mem_map,
898*795d594fSAndroid Build Coastguard Worker size_t initial_size,
899*795d594fSAndroid Build Coastguard Worker size_t growth_limit,
900*795d594fSAndroid Build Coastguard Worker size_t capacity,
901*795d594fSAndroid Build Coastguard Worker const char* name,
902*795d594fSAndroid Build Coastguard Worker bool can_move_objects) {
903*795d594fSAndroid Build Coastguard Worker space::MallocSpace* malloc_space = nullptr;
904*795d594fSAndroid Build Coastguard Worker if (kUseRosAlloc) {
905*795d594fSAndroid Build Coastguard Worker // Create rosalloc space.
906*795d594fSAndroid Build Coastguard Worker malloc_space = space::RosAllocSpace::CreateFromMemMap(std::move(mem_map),
907*795d594fSAndroid Build Coastguard Worker name,
908*795d594fSAndroid Build Coastguard Worker GetDefaultStartingSize(),
909*795d594fSAndroid Build Coastguard Worker initial_size,
910*795d594fSAndroid Build Coastguard Worker growth_limit,
911*795d594fSAndroid Build Coastguard Worker capacity,
912*795d594fSAndroid Build Coastguard Worker low_memory_mode_,
913*795d594fSAndroid Build Coastguard Worker can_move_objects);
914*795d594fSAndroid Build Coastguard Worker } else {
915*795d594fSAndroid Build Coastguard Worker malloc_space = space::DlMallocSpace::CreateFromMemMap(std::move(mem_map),
916*795d594fSAndroid Build Coastguard Worker name,
917*795d594fSAndroid Build Coastguard Worker GetDefaultStartingSize(),
918*795d594fSAndroid Build Coastguard Worker initial_size,
919*795d594fSAndroid Build Coastguard Worker growth_limit,
920*795d594fSAndroid Build Coastguard Worker capacity,
921*795d594fSAndroid Build Coastguard Worker can_move_objects);
922*795d594fSAndroid Build Coastguard Worker }
923*795d594fSAndroid Build Coastguard Worker if (collector::SemiSpace::kUseRememberedSet) {
924*795d594fSAndroid Build Coastguard Worker accounting::RememberedSet* rem_set =
925*795d594fSAndroid Build Coastguard Worker new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
926*795d594fSAndroid Build Coastguard Worker CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
927*795d594fSAndroid Build Coastguard Worker AddRememberedSet(rem_set);
928*795d594fSAndroid Build Coastguard Worker }
929*795d594fSAndroid Build Coastguard Worker CHECK(malloc_space != nullptr) << "Failed to create " << name;
930*795d594fSAndroid Build Coastguard Worker malloc_space->SetFootprintLimit(malloc_space->Capacity());
931*795d594fSAndroid Build Coastguard Worker return malloc_space;
932*795d594fSAndroid Build Coastguard Worker }
933*795d594fSAndroid Build Coastguard Worker
CreateMainMallocSpace(MemMap && mem_map,size_t initial_size,size_t growth_limit,size_t capacity)934*795d594fSAndroid Build Coastguard Worker void Heap::CreateMainMallocSpace(MemMap&& mem_map,
935*795d594fSAndroid Build Coastguard Worker size_t initial_size,
936*795d594fSAndroid Build Coastguard Worker size_t growth_limit,
937*795d594fSAndroid Build Coastguard Worker size_t capacity) {
938*795d594fSAndroid Build Coastguard Worker // Is background compaction is enabled?
939*795d594fSAndroid Build Coastguard Worker bool can_move_objects = IsMovingGc(background_collector_type_) !=
940*795d594fSAndroid Build Coastguard Worker IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
941*795d594fSAndroid Build Coastguard Worker // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
942*795d594fSAndroid Build Coastguard Worker // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
943*795d594fSAndroid Build Coastguard Worker // from the main space to the zygote space. If background compaction is enabled, always pass in
944*795d594fSAndroid Build Coastguard Worker // that we can move objets.
945*795d594fSAndroid Build Coastguard Worker if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
946*795d594fSAndroid Build Coastguard Worker // After the zygote we want this to be false if we don't have background compaction enabled so
947*795d594fSAndroid Build Coastguard Worker // that getting primitive array elements is faster.
948*795d594fSAndroid Build Coastguard Worker can_move_objects = !HasZygoteSpace();
949*795d594fSAndroid Build Coastguard Worker }
950*795d594fSAndroid Build Coastguard Worker if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
951*795d594fSAndroid Build Coastguard Worker RemoveRememberedSet(main_space_);
952*795d594fSAndroid Build Coastguard Worker }
953*795d594fSAndroid Build Coastguard Worker const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
954*795d594fSAndroid Build Coastguard Worker main_space_ = CreateMallocSpaceFromMemMap(std::move(mem_map),
955*795d594fSAndroid Build Coastguard Worker initial_size,
956*795d594fSAndroid Build Coastguard Worker growth_limit,
957*795d594fSAndroid Build Coastguard Worker capacity, name,
958*795d594fSAndroid Build Coastguard Worker can_move_objects);
959*795d594fSAndroid Build Coastguard Worker SetSpaceAsDefault(main_space_);
960*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Created main space " << main_space_;
961*795d594fSAndroid Build Coastguard Worker }
962*795d594fSAndroid Build Coastguard Worker
ChangeAllocator(AllocatorType allocator)963*795d594fSAndroid Build Coastguard Worker void Heap::ChangeAllocator(AllocatorType allocator) {
964*795d594fSAndroid Build Coastguard Worker if (current_allocator_ != allocator) {
965*795d594fSAndroid Build Coastguard Worker // These two allocators are only used internally and don't have any entrypoints.
966*795d594fSAndroid Build Coastguard Worker CHECK_NE(allocator, kAllocatorTypeLOS);
967*795d594fSAndroid Build Coastguard Worker CHECK_NE(allocator, kAllocatorTypeNonMoving);
968*795d594fSAndroid Build Coastguard Worker current_allocator_ = allocator;
969*795d594fSAndroid Build Coastguard Worker MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
970*795d594fSAndroid Build Coastguard Worker SetQuickAllocEntryPointsAllocator(current_allocator_);
971*795d594fSAndroid Build Coastguard Worker Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
972*795d594fSAndroid Build Coastguard Worker }
973*795d594fSAndroid Build Coastguard Worker }
974*795d594fSAndroid Build Coastguard Worker
IsCompilingBoot() const975*795d594fSAndroid Build Coastguard Worker bool Heap::IsCompilingBoot() const {
976*795d594fSAndroid Build Coastguard Worker if (!Runtime::Current()->IsAotCompiler()) {
977*795d594fSAndroid Build Coastguard Worker return false;
978*795d594fSAndroid Build Coastguard Worker }
979*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(Thread::Current());
980*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
981*795d594fSAndroid Build Coastguard Worker if (space->IsImageSpace() || space->IsZygoteSpace()) {
982*795d594fSAndroid Build Coastguard Worker return false;
983*795d594fSAndroid Build Coastguard Worker }
984*795d594fSAndroid Build Coastguard Worker }
985*795d594fSAndroid Build Coastguard Worker return true;
986*795d594fSAndroid Build Coastguard Worker }
987*795d594fSAndroid Build Coastguard Worker
IncrementDisableMovingGC(Thread * self)988*795d594fSAndroid Build Coastguard Worker void Heap::IncrementDisableMovingGC(Thread* self) {
989*795d594fSAndroid Build Coastguard Worker // Need to do this holding the lock to prevent races where the GC is about to run / running when
990*795d594fSAndroid Build Coastguard Worker // we attempt to disable it.
991*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc(self, ThreadState::kWaitingForGcToComplete);
992*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *gc_complete_lock_);
993*795d594fSAndroid Build Coastguard Worker ++disable_moving_gc_count_;
994*795d594fSAndroid Build Coastguard Worker if (IsMovingGc(collector_type_running_)) {
995*795d594fSAndroid Build Coastguard Worker WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
996*795d594fSAndroid Build Coastguard Worker }
997*795d594fSAndroid Build Coastguard Worker }
998*795d594fSAndroid Build Coastguard Worker
DecrementDisableMovingGC(Thread * self)999*795d594fSAndroid Build Coastguard Worker void Heap::DecrementDisableMovingGC(Thread* self) {
1000*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *gc_complete_lock_);
1001*795d594fSAndroid Build Coastguard Worker CHECK_GT(disable_moving_gc_count_, 0U);
1002*795d594fSAndroid Build Coastguard Worker --disable_moving_gc_count_;
1003*795d594fSAndroid Build Coastguard Worker }
1004*795d594fSAndroid Build Coastguard Worker
IncrementDisableThreadFlip(Thread * self)1005*795d594fSAndroid Build Coastguard Worker void Heap::IncrementDisableThreadFlip(Thread* self) {
1006*795d594fSAndroid Build Coastguard Worker // Supposed to be called by mutators. If thread_flip_running_ is true, block. Otherwise, go ahead.
1007*795d594fSAndroid Build Coastguard Worker bool is_nested = self->GetDisableThreadFlipCount() > 0;
1008*795d594fSAndroid Build Coastguard Worker self->IncrementDisableThreadFlipCount();
1009*795d594fSAndroid Build Coastguard Worker if (is_nested) {
1010*795d594fSAndroid Build Coastguard Worker // If this is a nested JNI critical section enter, we don't need to wait or increment the global
1011*795d594fSAndroid Build Coastguard Worker // counter. The global counter is incremented only once for a thread for the outermost enter.
1012*795d594fSAndroid Build Coastguard Worker return;
1013*795d594fSAndroid Build Coastguard Worker }
1014*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc(self, ThreadState::kWaitingForGcThreadFlip);
1015*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *thread_flip_lock_);
1016*795d594fSAndroid Build Coastguard Worker thread_flip_cond_->CheckSafeToWait(self);
1017*795d594fSAndroid Build Coastguard Worker bool has_waited = false;
1018*795d594fSAndroid Build Coastguard Worker uint64_t wait_start = 0;
1019*795d594fSAndroid Build Coastguard Worker if (thread_flip_running_) {
1020*795d594fSAndroid Build Coastguard Worker wait_start = NanoTime();
1021*795d594fSAndroid Build Coastguard Worker ScopedTrace trace("IncrementDisableThreadFlip");
1022*795d594fSAndroid Build Coastguard Worker while (thread_flip_running_) {
1023*795d594fSAndroid Build Coastguard Worker has_waited = true;
1024*795d594fSAndroid Build Coastguard Worker thread_flip_cond_->Wait(self);
1025*795d594fSAndroid Build Coastguard Worker }
1026*795d594fSAndroid Build Coastguard Worker }
1027*795d594fSAndroid Build Coastguard Worker ++disable_thread_flip_count_;
1028*795d594fSAndroid Build Coastguard Worker if (has_waited) {
1029*795d594fSAndroid Build Coastguard Worker uint64_t wait_time = NanoTime() - wait_start;
1030*795d594fSAndroid Build Coastguard Worker total_wait_time_ += wait_time;
1031*795d594fSAndroid Build Coastguard Worker if (wait_time > long_pause_log_threshold_) {
1032*795d594fSAndroid Build Coastguard Worker LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
1033*795d594fSAndroid Build Coastguard Worker }
1034*795d594fSAndroid Build Coastguard Worker }
1035*795d594fSAndroid Build Coastguard Worker }
1036*795d594fSAndroid Build Coastguard Worker
EnsureObjectUserfaulted(ObjPtr<mirror::Object> obj)1037*795d594fSAndroid Build Coastguard Worker void Heap::EnsureObjectUserfaulted(ObjPtr<mirror::Object> obj) {
1038*795d594fSAndroid Build Coastguard Worker if (gUseUserfaultfd) {
1039*795d594fSAndroid Build Coastguard Worker // Use volatile to ensure that compiler loads from memory to trigger userfaults, if required.
1040*795d594fSAndroid Build Coastguard Worker const uint8_t* start = reinterpret_cast<uint8_t*>(obj.Ptr());
1041*795d594fSAndroid Build Coastguard Worker const uint8_t* end = AlignUp(start + obj->SizeOf(), gPageSize);
1042*795d594fSAndroid Build Coastguard Worker // The first page is already touched by SizeOf().
1043*795d594fSAndroid Build Coastguard Worker start += gPageSize;
1044*795d594fSAndroid Build Coastguard Worker while (start < end) {
1045*795d594fSAndroid Build Coastguard Worker ForceRead(start);
1046*795d594fSAndroid Build Coastguard Worker start += gPageSize;
1047*795d594fSAndroid Build Coastguard Worker }
1048*795d594fSAndroid Build Coastguard Worker }
1049*795d594fSAndroid Build Coastguard Worker }
1050*795d594fSAndroid Build Coastguard Worker
DecrementDisableThreadFlip(Thread * self)1051*795d594fSAndroid Build Coastguard Worker void Heap::DecrementDisableThreadFlip(Thread* self) {
1052*795d594fSAndroid Build Coastguard Worker // Supposed to be called by mutators. Decrement disable_thread_flip_count_ and potentially wake up
1053*795d594fSAndroid Build Coastguard Worker // the GC waiting before doing a thread flip.
1054*795d594fSAndroid Build Coastguard Worker self->DecrementDisableThreadFlipCount();
1055*795d594fSAndroid Build Coastguard Worker bool is_outermost = self->GetDisableThreadFlipCount() == 0;
1056*795d594fSAndroid Build Coastguard Worker if (!is_outermost) {
1057*795d594fSAndroid Build Coastguard Worker // If this is not an outermost JNI critical exit, we don't need to decrement the global counter.
1058*795d594fSAndroid Build Coastguard Worker // The global counter is decremented only once for a thread for the outermost exit.
1059*795d594fSAndroid Build Coastguard Worker return;
1060*795d594fSAndroid Build Coastguard Worker }
1061*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *thread_flip_lock_);
1062*795d594fSAndroid Build Coastguard Worker CHECK_GT(disable_thread_flip_count_, 0U);
1063*795d594fSAndroid Build Coastguard Worker --disable_thread_flip_count_;
1064*795d594fSAndroid Build Coastguard Worker if (disable_thread_flip_count_ == 0) {
1065*795d594fSAndroid Build Coastguard Worker // Potentially notify the GC thread blocking to begin a thread flip.
1066*795d594fSAndroid Build Coastguard Worker thread_flip_cond_->Broadcast(self);
1067*795d594fSAndroid Build Coastguard Worker }
1068*795d594fSAndroid Build Coastguard Worker }
1069*795d594fSAndroid Build Coastguard Worker
ThreadFlipBegin(Thread * self)1070*795d594fSAndroid Build Coastguard Worker void Heap::ThreadFlipBegin(Thread* self) {
1071*795d594fSAndroid Build Coastguard Worker // Supposed to be called by GC. Set thread_flip_running_ to be true. If disable_thread_flip_count_
1072*795d594fSAndroid Build Coastguard Worker // > 0, block. Otherwise, go ahead.
1073*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc(self, ThreadState::kWaitingForGcThreadFlip);
1074*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *thread_flip_lock_);
1075*795d594fSAndroid Build Coastguard Worker thread_flip_cond_->CheckSafeToWait(self);
1076*795d594fSAndroid Build Coastguard Worker bool has_waited = false;
1077*795d594fSAndroid Build Coastguard Worker uint64_t wait_start = NanoTime();
1078*795d594fSAndroid Build Coastguard Worker CHECK(!thread_flip_running_);
1079*795d594fSAndroid Build Coastguard Worker // Set this to true before waiting so that frequent JNI critical enter/exits won't starve
1080*795d594fSAndroid Build Coastguard Worker // GC. This like a writer preference of a reader-writer lock.
1081*795d594fSAndroid Build Coastguard Worker thread_flip_running_ = true;
1082*795d594fSAndroid Build Coastguard Worker while (disable_thread_flip_count_ > 0) {
1083*795d594fSAndroid Build Coastguard Worker has_waited = true;
1084*795d594fSAndroid Build Coastguard Worker thread_flip_cond_->Wait(self);
1085*795d594fSAndroid Build Coastguard Worker }
1086*795d594fSAndroid Build Coastguard Worker if (has_waited) {
1087*795d594fSAndroid Build Coastguard Worker uint64_t wait_time = NanoTime() - wait_start;
1088*795d594fSAndroid Build Coastguard Worker total_wait_time_ += wait_time;
1089*795d594fSAndroid Build Coastguard Worker if (wait_time > long_pause_log_threshold_) {
1090*795d594fSAndroid Build Coastguard Worker LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
1091*795d594fSAndroid Build Coastguard Worker }
1092*795d594fSAndroid Build Coastguard Worker }
1093*795d594fSAndroid Build Coastguard Worker }
1094*795d594fSAndroid Build Coastguard Worker
ThreadFlipEnd(Thread * self)1095*795d594fSAndroid Build Coastguard Worker void Heap::ThreadFlipEnd(Thread* self) {
1096*795d594fSAndroid Build Coastguard Worker // Supposed to be called by GC. Set thread_flip_running_ to false and potentially wake up mutators
1097*795d594fSAndroid Build Coastguard Worker // waiting before doing a JNI critical.
1098*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *thread_flip_lock_);
1099*795d594fSAndroid Build Coastguard Worker CHECK(thread_flip_running_);
1100*795d594fSAndroid Build Coastguard Worker thread_flip_running_ = false;
1101*795d594fSAndroid Build Coastguard Worker // Potentially notify mutator threads blocking to enter a JNI critical section.
1102*795d594fSAndroid Build Coastguard Worker thread_flip_cond_->Broadcast(self);
1103*795d594fSAndroid Build Coastguard Worker }
1104*795d594fSAndroid Build Coastguard Worker
GrowHeapOnJankPerceptibleSwitch()1105*795d594fSAndroid Build Coastguard Worker void Heap::GrowHeapOnJankPerceptibleSwitch() {
1106*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), process_state_update_lock_);
1107*795d594fSAndroid Build Coastguard Worker size_t orig_target_footprint = target_footprint_.load(std::memory_order_relaxed);
1108*795d594fSAndroid Build Coastguard Worker if (orig_target_footprint < min_foreground_target_footprint_) {
1109*795d594fSAndroid Build Coastguard Worker target_footprint_.compare_exchange_strong(orig_target_footprint,
1110*795d594fSAndroid Build Coastguard Worker min_foreground_target_footprint_,
1111*795d594fSAndroid Build Coastguard Worker std::memory_order_relaxed);
1112*795d594fSAndroid Build Coastguard Worker }
1113*795d594fSAndroid Build Coastguard Worker if (IsGcConcurrent() && concurrent_start_bytes_ < min_foreground_concurrent_start_bytes_) {
1114*795d594fSAndroid Build Coastguard Worker concurrent_start_bytes_ = min_foreground_concurrent_start_bytes_;
1115*795d594fSAndroid Build Coastguard Worker }
1116*795d594fSAndroid Build Coastguard Worker }
1117*795d594fSAndroid Build Coastguard Worker
UpdateProcessState(ProcessState old_process_state,ProcessState new_process_state)1118*795d594fSAndroid Build Coastguard Worker void Heap::UpdateProcessState(ProcessState old_process_state, ProcessState new_process_state) {
1119*795d594fSAndroid Build Coastguard Worker if (old_process_state != new_process_state) {
1120*795d594fSAndroid Build Coastguard Worker const bool jank_perceptible = new_process_state == kProcessStateJankPerceptible;
1121*795d594fSAndroid Build Coastguard Worker if (jank_perceptible) {
1122*795d594fSAndroid Build Coastguard Worker // Transition back to foreground right away to prevent jank.
1123*795d594fSAndroid Build Coastguard Worker RequestCollectorTransition(foreground_collector_type_, 0);
1124*795d594fSAndroid Build Coastguard Worker GrowHeapOnJankPerceptibleSwitch();
1125*795d594fSAndroid Build Coastguard Worker } else {
1126*795d594fSAndroid Build Coastguard Worker // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
1127*795d594fSAndroid Build Coastguard Worker // special handling which does a homogenous space compaction once but then doesn't transition
1128*795d594fSAndroid Build Coastguard Worker // the collector. Similarly, we invoke a full compaction for kCollectorTypeCC but don't
1129*795d594fSAndroid Build Coastguard Worker // transition the collector.
1130*795d594fSAndroid Build Coastguard Worker RequestCollectorTransition(background_collector_type_, 0);
1131*795d594fSAndroid Build Coastguard Worker }
1132*795d594fSAndroid Build Coastguard Worker }
1133*795d594fSAndroid Build Coastguard Worker }
1134*795d594fSAndroid Build Coastguard Worker
CreateThreadPool(size_t num_threads)1135*795d594fSAndroid Build Coastguard Worker void Heap::CreateThreadPool(size_t num_threads) {
1136*795d594fSAndroid Build Coastguard Worker if (num_threads == 0) {
1137*795d594fSAndroid Build Coastguard Worker num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
1138*795d594fSAndroid Build Coastguard Worker }
1139*795d594fSAndroid Build Coastguard Worker if (num_threads != 0) {
1140*795d594fSAndroid Build Coastguard Worker thread_pool_.reset(ThreadPool::Create("Heap thread pool", num_threads));
1141*795d594fSAndroid Build Coastguard Worker }
1142*795d594fSAndroid Build Coastguard Worker }
1143*795d594fSAndroid Build Coastguard Worker
WaitForWorkersToBeCreated()1144*795d594fSAndroid Build Coastguard Worker void Heap::WaitForWorkersToBeCreated() {
1145*795d594fSAndroid Build Coastguard Worker DCHECK(!Runtime::Current()->IsShuttingDown(Thread::Current()))
1146*795d594fSAndroid Build Coastguard Worker << "Cannot create new threads during runtime shutdown";
1147*795d594fSAndroid Build Coastguard Worker if (thread_pool_ != nullptr) {
1148*795d594fSAndroid Build Coastguard Worker thread_pool_->WaitForWorkersToBeCreated();
1149*795d594fSAndroid Build Coastguard Worker }
1150*795d594fSAndroid Build Coastguard Worker }
1151*795d594fSAndroid Build Coastguard Worker
MarkAllocStackAsLive(accounting::ObjectStack * stack)1152*795d594fSAndroid Build Coastguard Worker void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
1153*795d594fSAndroid Build Coastguard Worker space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
1154*795d594fSAndroid Build Coastguard Worker space::ContinuousSpace* space2 = non_moving_space_;
1155*795d594fSAndroid Build Coastguard Worker // TODO: Generalize this to n bitmaps?
1156*795d594fSAndroid Build Coastguard Worker CHECK(space1 != nullptr);
1157*795d594fSAndroid Build Coastguard Worker CHECK(space2 != nullptr);
1158*795d594fSAndroid Build Coastguard Worker MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
1159*795d594fSAndroid Build Coastguard Worker (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
1160*795d594fSAndroid Build Coastguard Worker stack);
1161*795d594fSAndroid Build Coastguard Worker }
1162*795d594fSAndroid Build Coastguard Worker
DeleteThreadPool()1163*795d594fSAndroid Build Coastguard Worker void Heap::DeleteThreadPool() {
1164*795d594fSAndroid Build Coastguard Worker thread_pool_.reset(nullptr);
1165*795d594fSAndroid Build Coastguard Worker }
1166*795d594fSAndroid Build Coastguard Worker
AddSpace(space::Space * space)1167*795d594fSAndroid Build Coastguard Worker void Heap::AddSpace(space::Space* space) {
1168*795d594fSAndroid Build Coastguard Worker CHECK(space != nullptr);
1169*795d594fSAndroid Build Coastguard Worker WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1170*795d594fSAndroid Build Coastguard Worker if (space->IsContinuousSpace()) {
1171*795d594fSAndroid Build Coastguard Worker DCHECK(!space->IsDiscontinuousSpace());
1172*795d594fSAndroid Build Coastguard Worker space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1173*795d594fSAndroid Build Coastguard Worker // Continuous spaces don't necessarily have bitmaps.
1174*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1175*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
1176*795d594fSAndroid Build Coastguard Worker // The region space bitmap is not added since VisitObjects visits the region space objects with
1177*795d594fSAndroid Build Coastguard Worker // special handling.
1178*795d594fSAndroid Build Coastguard Worker if (live_bitmap != nullptr && !space->IsRegionSpace()) {
1179*795d594fSAndroid Build Coastguard Worker CHECK(mark_bitmap != nullptr);
1180*795d594fSAndroid Build Coastguard Worker live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
1181*795d594fSAndroid Build Coastguard Worker mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
1182*795d594fSAndroid Build Coastguard Worker }
1183*795d594fSAndroid Build Coastguard Worker continuous_spaces_.push_back(continuous_space);
1184*795d594fSAndroid Build Coastguard Worker // Ensure that spaces remain sorted in increasing order of start address.
1185*795d594fSAndroid Build Coastguard Worker std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
1186*795d594fSAndroid Build Coastguard Worker [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
1187*795d594fSAndroid Build Coastguard Worker return a->Begin() < b->Begin();
1188*795d594fSAndroid Build Coastguard Worker });
1189*795d594fSAndroid Build Coastguard Worker } else {
1190*795d594fSAndroid Build Coastguard Worker CHECK(space->IsDiscontinuousSpace());
1191*795d594fSAndroid Build Coastguard Worker space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
1192*795d594fSAndroid Build Coastguard Worker live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1193*795d594fSAndroid Build Coastguard Worker mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
1194*795d594fSAndroid Build Coastguard Worker discontinuous_spaces_.push_back(discontinuous_space);
1195*795d594fSAndroid Build Coastguard Worker }
1196*795d594fSAndroid Build Coastguard Worker if (space->IsAllocSpace()) {
1197*795d594fSAndroid Build Coastguard Worker alloc_spaces_.push_back(space->AsAllocSpace());
1198*795d594fSAndroid Build Coastguard Worker }
1199*795d594fSAndroid Build Coastguard Worker }
1200*795d594fSAndroid Build Coastguard Worker
SetSpaceAsDefault(space::ContinuousSpace * continuous_space)1201*795d594fSAndroid Build Coastguard Worker void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
1202*795d594fSAndroid Build Coastguard Worker WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1203*795d594fSAndroid Build Coastguard Worker if (continuous_space->IsDlMallocSpace()) {
1204*795d594fSAndroid Build Coastguard Worker dlmalloc_space_ = continuous_space->AsDlMallocSpace();
1205*795d594fSAndroid Build Coastguard Worker } else if (continuous_space->IsRosAllocSpace()) {
1206*795d594fSAndroid Build Coastguard Worker rosalloc_space_ = continuous_space->AsRosAllocSpace();
1207*795d594fSAndroid Build Coastguard Worker }
1208*795d594fSAndroid Build Coastguard Worker }
1209*795d594fSAndroid Build Coastguard Worker
RemoveSpace(space::Space * space)1210*795d594fSAndroid Build Coastguard Worker void Heap::RemoveSpace(space::Space* space) {
1211*795d594fSAndroid Build Coastguard Worker DCHECK(space != nullptr);
1212*795d594fSAndroid Build Coastguard Worker WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1213*795d594fSAndroid Build Coastguard Worker if (space->IsContinuousSpace()) {
1214*795d594fSAndroid Build Coastguard Worker DCHECK(!space->IsDiscontinuousSpace());
1215*795d594fSAndroid Build Coastguard Worker space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1216*795d594fSAndroid Build Coastguard Worker // Continuous spaces don't necessarily have bitmaps.
1217*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1218*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
1219*795d594fSAndroid Build Coastguard Worker if (live_bitmap != nullptr && !space->IsRegionSpace()) {
1220*795d594fSAndroid Build Coastguard Worker DCHECK(mark_bitmap != nullptr);
1221*795d594fSAndroid Build Coastguard Worker live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
1222*795d594fSAndroid Build Coastguard Worker mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
1223*795d594fSAndroid Build Coastguard Worker }
1224*795d594fSAndroid Build Coastguard Worker auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
1225*795d594fSAndroid Build Coastguard Worker DCHECK(it != continuous_spaces_.end());
1226*795d594fSAndroid Build Coastguard Worker continuous_spaces_.erase(it);
1227*795d594fSAndroid Build Coastguard Worker } else {
1228*795d594fSAndroid Build Coastguard Worker DCHECK(space->IsDiscontinuousSpace());
1229*795d594fSAndroid Build Coastguard Worker space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
1230*795d594fSAndroid Build Coastguard Worker live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1231*795d594fSAndroid Build Coastguard Worker mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
1232*795d594fSAndroid Build Coastguard Worker auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
1233*795d594fSAndroid Build Coastguard Worker discontinuous_space);
1234*795d594fSAndroid Build Coastguard Worker DCHECK(it != discontinuous_spaces_.end());
1235*795d594fSAndroid Build Coastguard Worker discontinuous_spaces_.erase(it);
1236*795d594fSAndroid Build Coastguard Worker }
1237*795d594fSAndroid Build Coastguard Worker if (space->IsAllocSpace()) {
1238*795d594fSAndroid Build Coastguard Worker auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
1239*795d594fSAndroid Build Coastguard Worker DCHECK(it != alloc_spaces_.end());
1240*795d594fSAndroid Build Coastguard Worker alloc_spaces_.erase(it);
1241*795d594fSAndroid Build Coastguard Worker }
1242*795d594fSAndroid Build Coastguard Worker }
1243*795d594fSAndroid Build Coastguard Worker
CalculateGcWeightedAllocatedBytes(uint64_t gc_last_process_cpu_time_ns,uint64_t current_process_cpu_time) const1244*795d594fSAndroid Build Coastguard Worker double Heap::CalculateGcWeightedAllocatedBytes(uint64_t gc_last_process_cpu_time_ns,
1245*795d594fSAndroid Build Coastguard Worker uint64_t current_process_cpu_time) const {
1246*795d594fSAndroid Build Coastguard Worker uint64_t bytes_allocated = GetBytesAllocated();
1247*795d594fSAndroid Build Coastguard Worker double weight = current_process_cpu_time - gc_last_process_cpu_time_ns;
1248*795d594fSAndroid Build Coastguard Worker return weight * bytes_allocated;
1249*795d594fSAndroid Build Coastguard Worker }
1250*795d594fSAndroid Build Coastguard Worker
CalculatePreGcWeightedAllocatedBytes()1251*795d594fSAndroid Build Coastguard Worker void Heap::CalculatePreGcWeightedAllocatedBytes() {
1252*795d594fSAndroid Build Coastguard Worker uint64_t current_process_cpu_time = ProcessCpuNanoTime();
1253*795d594fSAndroid Build Coastguard Worker pre_gc_weighted_allocated_bytes_ +=
1254*795d594fSAndroid Build Coastguard Worker CalculateGcWeightedAllocatedBytes(pre_gc_last_process_cpu_time_ns_, current_process_cpu_time);
1255*795d594fSAndroid Build Coastguard Worker pre_gc_last_process_cpu_time_ns_ = current_process_cpu_time;
1256*795d594fSAndroid Build Coastguard Worker }
1257*795d594fSAndroid Build Coastguard Worker
CalculatePostGcWeightedAllocatedBytes()1258*795d594fSAndroid Build Coastguard Worker void Heap::CalculatePostGcWeightedAllocatedBytes() {
1259*795d594fSAndroid Build Coastguard Worker uint64_t current_process_cpu_time = ProcessCpuNanoTime();
1260*795d594fSAndroid Build Coastguard Worker post_gc_weighted_allocated_bytes_ +=
1261*795d594fSAndroid Build Coastguard Worker CalculateGcWeightedAllocatedBytes(post_gc_last_process_cpu_time_ns_, current_process_cpu_time);
1262*795d594fSAndroid Build Coastguard Worker post_gc_last_process_cpu_time_ns_ = current_process_cpu_time;
1263*795d594fSAndroid Build Coastguard Worker }
1264*795d594fSAndroid Build Coastguard Worker
GetTotalGcCpuTime()1265*795d594fSAndroid Build Coastguard Worker uint64_t Heap::GetTotalGcCpuTime() {
1266*795d594fSAndroid Build Coastguard Worker uint64_t sum = 0;
1267*795d594fSAndroid Build Coastguard Worker for (auto* collector : garbage_collectors_) {
1268*795d594fSAndroid Build Coastguard Worker sum += collector->GetTotalCpuTime();
1269*795d594fSAndroid Build Coastguard Worker }
1270*795d594fSAndroid Build Coastguard Worker return sum;
1271*795d594fSAndroid Build Coastguard Worker }
1272*795d594fSAndroid Build Coastguard Worker
DumpGcPerformanceInfo(std::ostream & os)1273*795d594fSAndroid Build Coastguard Worker void Heap::DumpGcPerformanceInfo(std::ostream& os) {
1274*795d594fSAndroid Build Coastguard Worker // Dump cumulative timings.
1275*795d594fSAndroid Build Coastguard Worker os << "Dumping cumulative Gc timings\n";
1276*795d594fSAndroid Build Coastguard Worker uint64_t total_duration = 0;
1277*795d594fSAndroid Build Coastguard Worker // Dump cumulative loggers for each GC type.
1278*795d594fSAndroid Build Coastguard Worker uint64_t total_paused_time = 0;
1279*795d594fSAndroid Build Coastguard Worker for (auto* collector : garbage_collectors_) {
1280*795d594fSAndroid Build Coastguard Worker total_duration += collector->GetCumulativeTimings().GetTotalNs();
1281*795d594fSAndroid Build Coastguard Worker total_paused_time += collector->GetTotalPausedTimeNs();
1282*795d594fSAndroid Build Coastguard Worker collector->DumpPerformanceInfo(os);
1283*795d594fSAndroid Build Coastguard Worker }
1284*795d594fSAndroid Build Coastguard Worker if (total_duration != 0) {
1285*795d594fSAndroid Build Coastguard Worker const double total_seconds = total_duration / 1.0e9;
1286*795d594fSAndroid Build Coastguard Worker const double total_cpu_seconds = GetTotalGcCpuTime() / 1.0e9;
1287*795d594fSAndroid Build Coastguard Worker os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
1288*795d594fSAndroid Build Coastguard Worker os << "Mean GC size throughput: "
1289*795d594fSAndroid Build Coastguard Worker << PrettySize(GetBytesFreedEver() / total_seconds) << "/s"
1290*795d594fSAndroid Build Coastguard Worker << " per cpu-time: "
1291*795d594fSAndroid Build Coastguard Worker << PrettySize(GetBytesFreedEver() / total_cpu_seconds) << "/s\n";
1292*795d594fSAndroid Build Coastguard Worker }
1293*795d594fSAndroid Build Coastguard Worker os << "Total bytes allocated " << PrettySize(GetBytesAllocatedEver()) << "\n";
1294*795d594fSAndroid Build Coastguard Worker os << "Total bytes freed " << PrettySize(GetBytesFreedEver()) << "\n";
1295*795d594fSAndroid Build Coastguard Worker os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
1296*795d594fSAndroid Build Coastguard Worker os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
1297*795d594fSAndroid Build Coastguard Worker os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
1298*795d594fSAndroid Build Coastguard Worker os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
1299*795d594fSAndroid Build Coastguard Worker os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
1300*795d594fSAndroid Build Coastguard Worker if (HasZygoteSpace()) {
1301*795d594fSAndroid Build Coastguard Worker os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
1302*795d594fSAndroid Build Coastguard Worker }
1303*795d594fSAndroid Build Coastguard Worker os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
1304*795d594fSAndroid Build Coastguard Worker os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
1305*795d594fSAndroid Build Coastguard Worker os << "Total GC count: " << GetGcCount() << "\n";
1306*795d594fSAndroid Build Coastguard Worker os << "Total GC time: " << PrettyDuration(GetGcTime()) << "\n";
1307*795d594fSAndroid Build Coastguard Worker os << "Total blocking GC count: " << GetBlockingGcCount() << "\n";
1308*795d594fSAndroid Build Coastguard Worker os << "Total blocking GC time: " << PrettyDuration(GetBlockingGcTime()) << "\n";
1309*795d594fSAndroid Build Coastguard Worker os << "Total pre-OOME GC count: " << GetPreOomeGcCount() << "\n";
1310*795d594fSAndroid Build Coastguard Worker {
1311*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *gc_complete_lock_);
1312*795d594fSAndroid Build Coastguard Worker if (gc_count_rate_histogram_.SampleSize() > 0U) {
1313*795d594fSAndroid Build Coastguard Worker os << "Histogram of GC count per " << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1314*795d594fSAndroid Build Coastguard Worker gc_count_rate_histogram_.DumpBins(os);
1315*795d594fSAndroid Build Coastguard Worker os << "\n";
1316*795d594fSAndroid Build Coastguard Worker }
1317*795d594fSAndroid Build Coastguard Worker if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1318*795d594fSAndroid Build Coastguard Worker os << "Histogram of blocking GC count per "
1319*795d594fSAndroid Build Coastguard Worker << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1320*795d594fSAndroid Build Coastguard Worker blocking_gc_count_rate_histogram_.DumpBins(os);
1321*795d594fSAndroid Build Coastguard Worker os << "\n";
1322*795d594fSAndroid Build Coastguard Worker }
1323*795d594fSAndroid Build Coastguard Worker }
1324*795d594fSAndroid Build Coastguard Worker
1325*795d594fSAndroid Build Coastguard Worker if (kDumpRosAllocStatsOnSigQuit && rosalloc_space_ != nullptr) {
1326*795d594fSAndroid Build Coastguard Worker rosalloc_space_->DumpStats(os);
1327*795d594fSAndroid Build Coastguard Worker }
1328*795d594fSAndroid Build Coastguard Worker
1329*795d594fSAndroid Build Coastguard Worker os << "Native bytes total: " << GetNativeBytes()
1330*795d594fSAndroid Build Coastguard Worker << " registered: " << native_bytes_registered_.load(std::memory_order_relaxed) << "\n";
1331*795d594fSAndroid Build Coastguard Worker
1332*795d594fSAndroid Build Coastguard Worker os << "Total native bytes at last GC: "
1333*795d594fSAndroid Build Coastguard Worker << old_native_bytes_allocated_.load(std::memory_order_relaxed) << "\n";
1334*795d594fSAndroid Build Coastguard Worker
1335*795d594fSAndroid Build Coastguard Worker BaseMutex::DumpAll(os);
1336*795d594fSAndroid Build Coastguard Worker }
1337*795d594fSAndroid Build Coastguard Worker
ResetGcPerformanceInfo()1338*795d594fSAndroid Build Coastguard Worker void Heap::ResetGcPerformanceInfo() {
1339*795d594fSAndroid Build Coastguard Worker for (auto* collector : garbage_collectors_) {
1340*795d594fSAndroid Build Coastguard Worker collector->ResetMeasurements();
1341*795d594fSAndroid Build Coastguard Worker }
1342*795d594fSAndroid Build Coastguard Worker
1343*795d594fSAndroid Build Coastguard Worker process_cpu_start_time_ns_ = ProcessCpuNanoTime();
1344*795d594fSAndroid Build Coastguard Worker
1345*795d594fSAndroid Build Coastguard Worker pre_gc_last_process_cpu_time_ns_ = process_cpu_start_time_ns_;
1346*795d594fSAndroid Build Coastguard Worker pre_gc_weighted_allocated_bytes_ = 0u;
1347*795d594fSAndroid Build Coastguard Worker
1348*795d594fSAndroid Build Coastguard Worker post_gc_last_process_cpu_time_ns_ = process_cpu_start_time_ns_;
1349*795d594fSAndroid Build Coastguard Worker post_gc_weighted_allocated_bytes_ = 0u;
1350*795d594fSAndroid Build Coastguard Worker
1351*795d594fSAndroid Build Coastguard Worker total_bytes_freed_ever_.store(0);
1352*795d594fSAndroid Build Coastguard Worker total_objects_freed_ever_.store(0);
1353*795d594fSAndroid Build Coastguard Worker total_wait_time_ = 0;
1354*795d594fSAndroid Build Coastguard Worker blocking_gc_count_ = 0;
1355*795d594fSAndroid Build Coastguard Worker blocking_gc_time_ = 0;
1356*795d594fSAndroid Build Coastguard Worker pre_oome_gc_count_.store(0, std::memory_order_relaxed);
1357*795d594fSAndroid Build Coastguard Worker gc_count_last_window_ = 0;
1358*795d594fSAndroid Build Coastguard Worker blocking_gc_count_last_window_ = 0;
1359*795d594fSAndroid Build Coastguard Worker last_update_time_gc_count_rate_histograms_ = // Round down by the window duration.
1360*795d594fSAndroid Build Coastguard Worker (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
1361*795d594fSAndroid Build Coastguard Worker {
1362*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *gc_complete_lock_);
1363*795d594fSAndroid Build Coastguard Worker gc_count_rate_histogram_.Reset();
1364*795d594fSAndroid Build Coastguard Worker blocking_gc_count_rate_histogram_.Reset();
1365*795d594fSAndroid Build Coastguard Worker }
1366*795d594fSAndroid Build Coastguard Worker }
1367*795d594fSAndroid Build Coastguard Worker
GetGcCount() const1368*795d594fSAndroid Build Coastguard Worker uint64_t Heap::GetGcCount() const {
1369*795d594fSAndroid Build Coastguard Worker uint64_t gc_count = 0U;
1370*795d594fSAndroid Build Coastguard Worker for (auto* collector : garbage_collectors_) {
1371*795d594fSAndroid Build Coastguard Worker gc_count += collector->GetCumulativeTimings().GetIterations();
1372*795d594fSAndroid Build Coastguard Worker }
1373*795d594fSAndroid Build Coastguard Worker return gc_count;
1374*795d594fSAndroid Build Coastguard Worker }
1375*795d594fSAndroid Build Coastguard Worker
GetGcTime() const1376*795d594fSAndroid Build Coastguard Worker uint64_t Heap::GetGcTime() const {
1377*795d594fSAndroid Build Coastguard Worker uint64_t gc_time = 0U;
1378*795d594fSAndroid Build Coastguard Worker for (auto* collector : garbage_collectors_) {
1379*795d594fSAndroid Build Coastguard Worker gc_time += collector->GetCumulativeTimings().GetTotalNs();
1380*795d594fSAndroid Build Coastguard Worker }
1381*795d594fSAndroid Build Coastguard Worker return gc_time;
1382*795d594fSAndroid Build Coastguard Worker }
1383*795d594fSAndroid Build Coastguard Worker
GetBlockingGcCount() const1384*795d594fSAndroid Build Coastguard Worker uint64_t Heap::GetBlockingGcCount() const {
1385*795d594fSAndroid Build Coastguard Worker return blocking_gc_count_;
1386*795d594fSAndroid Build Coastguard Worker }
1387*795d594fSAndroid Build Coastguard Worker
GetBlockingGcTime() const1388*795d594fSAndroid Build Coastguard Worker uint64_t Heap::GetBlockingGcTime() const {
1389*795d594fSAndroid Build Coastguard Worker return blocking_gc_time_;
1390*795d594fSAndroid Build Coastguard Worker }
1391*795d594fSAndroid Build Coastguard Worker
DumpGcCountRateHistogram(std::ostream & os) const1392*795d594fSAndroid Build Coastguard Worker void Heap::DumpGcCountRateHistogram(std::ostream& os) const {
1393*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *gc_complete_lock_);
1394*795d594fSAndroid Build Coastguard Worker if (gc_count_rate_histogram_.SampleSize() > 0U) {
1395*795d594fSAndroid Build Coastguard Worker gc_count_rate_histogram_.DumpBins(os);
1396*795d594fSAndroid Build Coastguard Worker }
1397*795d594fSAndroid Build Coastguard Worker }
1398*795d594fSAndroid Build Coastguard Worker
DumpBlockingGcCountRateHistogram(std::ostream & os) const1399*795d594fSAndroid Build Coastguard Worker void Heap::DumpBlockingGcCountRateHistogram(std::ostream& os) const {
1400*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *gc_complete_lock_);
1401*795d594fSAndroid Build Coastguard Worker if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1402*795d594fSAndroid Build Coastguard Worker blocking_gc_count_rate_histogram_.DumpBins(os);
1403*795d594fSAndroid Build Coastguard Worker }
1404*795d594fSAndroid Build Coastguard Worker }
1405*795d594fSAndroid Build Coastguard Worker
GetPreOomeGcCount() const1406*795d594fSAndroid Build Coastguard Worker uint64_t Heap::GetPreOomeGcCount() const {
1407*795d594fSAndroid Build Coastguard Worker return pre_oome_gc_count_.load(std::memory_order_relaxed);
1408*795d594fSAndroid Build Coastguard Worker }
1409*795d594fSAndroid Build Coastguard Worker
1410*795d594fSAndroid Build Coastguard Worker ALWAYS_INLINE
GetAndOverwriteAllocationListener(Atomic<AllocationListener * > * storage,AllocationListener * new_value)1411*795d594fSAndroid Build Coastguard Worker static inline AllocationListener* GetAndOverwriteAllocationListener(
1412*795d594fSAndroid Build Coastguard Worker Atomic<AllocationListener*>* storage, AllocationListener* new_value) {
1413*795d594fSAndroid Build Coastguard Worker return storage->exchange(new_value);
1414*795d594fSAndroid Build Coastguard Worker }
1415*795d594fSAndroid Build Coastguard Worker
~Heap()1416*795d594fSAndroid Build Coastguard Worker Heap::~Heap() {
1417*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Starting ~Heap()";
1418*795d594fSAndroid Build Coastguard Worker STLDeleteElements(&garbage_collectors_);
1419*795d594fSAndroid Build Coastguard Worker // If we don't reset then the mark stack complains in its destructor.
1420*795d594fSAndroid Build Coastguard Worker allocation_stack_->Reset();
1421*795d594fSAndroid Build Coastguard Worker allocation_records_.reset();
1422*795d594fSAndroid Build Coastguard Worker live_stack_->Reset();
1423*795d594fSAndroid Build Coastguard Worker STLDeleteValues(&mod_union_tables_);
1424*795d594fSAndroid Build Coastguard Worker STLDeleteValues(&remembered_sets_);
1425*795d594fSAndroid Build Coastguard Worker STLDeleteElements(&continuous_spaces_);
1426*795d594fSAndroid Build Coastguard Worker STLDeleteElements(&discontinuous_spaces_);
1427*795d594fSAndroid Build Coastguard Worker delete gc_complete_lock_;
1428*795d594fSAndroid Build Coastguard Worker delete thread_flip_lock_;
1429*795d594fSAndroid Build Coastguard Worker delete pending_task_lock_;
1430*795d594fSAndroid Build Coastguard Worker delete backtrace_lock_;
1431*795d594fSAndroid Build Coastguard Worker uint64_t unique_count = unique_backtrace_count_.load();
1432*795d594fSAndroid Build Coastguard Worker uint64_t seen_count = seen_backtrace_count_.load();
1433*795d594fSAndroid Build Coastguard Worker if (unique_count != 0 || seen_count != 0) {
1434*795d594fSAndroid Build Coastguard Worker LOG(INFO) << "gc stress unique=" << unique_count << " total=" << (unique_count + seen_count);
1435*795d594fSAndroid Build Coastguard Worker }
1436*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Finished ~Heap()";
1437*795d594fSAndroid Build Coastguard Worker }
1438*795d594fSAndroid Build Coastguard Worker
1439*795d594fSAndroid Build Coastguard Worker
FindContinuousSpaceFromAddress(const mirror::Object * addr) const1440*795d594fSAndroid Build Coastguard Worker space::ContinuousSpace* Heap::FindContinuousSpaceFromAddress(const mirror::Object* addr) const {
1441*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
1442*795d594fSAndroid Build Coastguard Worker if (space->Contains(addr)) {
1443*795d594fSAndroid Build Coastguard Worker return space;
1444*795d594fSAndroid Build Coastguard Worker }
1445*795d594fSAndroid Build Coastguard Worker }
1446*795d594fSAndroid Build Coastguard Worker return nullptr;
1447*795d594fSAndroid Build Coastguard Worker }
1448*795d594fSAndroid Build Coastguard Worker
FindContinuousSpaceFromObject(ObjPtr<mirror::Object> obj,bool fail_ok) const1449*795d594fSAndroid Build Coastguard Worker space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
1450*795d594fSAndroid Build Coastguard Worker bool fail_ok) const {
1451*795d594fSAndroid Build Coastguard Worker space::ContinuousSpace* space = FindContinuousSpaceFromAddress(obj.Ptr());
1452*795d594fSAndroid Build Coastguard Worker if (space != nullptr) {
1453*795d594fSAndroid Build Coastguard Worker return space;
1454*795d594fSAndroid Build Coastguard Worker }
1455*795d594fSAndroid Build Coastguard Worker if (!fail_ok) {
1456*795d594fSAndroid Build Coastguard Worker LOG(FATAL) << "object " << obj << " not inside any spaces!";
1457*795d594fSAndroid Build Coastguard Worker }
1458*795d594fSAndroid Build Coastguard Worker return nullptr;
1459*795d594fSAndroid Build Coastguard Worker }
1460*795d594fSAndroid Build Coastguard Worker
FindDiscontinuousSpaceFromObject(ObjPtr<mirror::Object> obj,bool fail_ok) const1461*795d594fSAndroid Build Coastguard Worker space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
1462*795d594fSAndroid Build Coastguard Worker bool fail_ok) const {
1463*795d594fSAndroid Build Coastguard Worker for (const auto& space : discontinuous_spaces_) {
1464*795d594fSAndroid Build Coastguard Worker if (space->Contains(obj.Ptr())) {
1465*795d594fSAndroid Build Coastguard Worker return space;
1466*795d594fSAndroid Build Coastguard Worker }
1467*795d594fSAndroid Build Coastguard Worker }
1468*795d594fSAndroid Build Coastguard Worker if (!fail_ok) {
1469*795d594fSAndroid Build Coastguard Worker LOG(FATAL) << "object " << obj << " not inside any spaces!";
1470*795d594fSAndroid Build Coastguard Worker }
1471*795d594fSAndroid Build Coastguard Worker return nullptr;
1472*795d594fSAndroid Build Coastguard Worker }
1473*795d594fSAndroid Build Coastguard Worker
FindSpaceFromObject(ObjPtr<mirror::Object> obj,bool fail_ok) const1474*795d594fSAndroid Build Coastguard Worker space::Space* Heap::FindSpaceFromObject(ObjPtr<mirror::Object> obj, bool fail_ok) const {
1475*795d594fSAndroid Build Coastguard Worker space::Space* result = FindContinuousSpaceFromObject(obj, true);
1476*795d594fSAndroid Build Coastguard Worker if (result != nullptr) {
1477*795d594fSAndroid Build Coastguard Worker return result;
1478*795d594fSAndroid Build Coastguard Worker }
1479*795d594fSAndroid Build Coastguard Worker return FindDiscontinuousSpaceFromObject(obj, fail_ok);
1480*795d594fSAndroid Build Coastguard Worker }
1481*795d594fSAndroid Build Coastguard Worker
FindSpaceFromAddress(const void * addr) const1482*795d594fSAndroid Build Coastguard Worker space::Space* Heap::FindSpaceFromAddress(const void* addr) const {
1483*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
1484*795d594fSAndroid Build Coastguard Worker if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1485*795d594fSAndroid Build Coastguard Worker return space;
1486*795d594fSAndroid Build Coastguard Worker }
1487*795d594fSAndroid Build Coastguard Worker }
1488*795d594fSAndroid Build Coastguard Worker for (const auto& space : discontinuous_spaces_) {
1489*795d594fSAndroid Build Coastguard Worker if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1490*795d594fSAndroid Build Coastguard Worker return space;
1491*795d594fSAndroid Build Coastguard Worker }
1492*795d594fSAndroid Build Coastguard Worker }
1493*795d594fSAndroid Build Coastguard Worker return nullptr;
1494*795d594fSAndroid Build Coastguard Worker }
1495*795d594fSAndroid Build Coastguard Worker
DumpSpaceNameFromAddress(const void * addr) const1496*795d594fSAndroid Build Coastguard Worker std::string Heap::DumpSpaceNameFromAddress(const void* addr) const {
1497*795d594fSAndroid Build Coastguard Worker space::Space* space = FindSpaceFromAddress(addr);
1498*795d594fSAndroid Build Coastguard Worker return (space != nullptr) ? space->GetName() : "no space";
1499*795d594fSAndroid Build Coastguard Worker }
1500*795d594fSAndroid Build Coastguard Worker
ThrowOutOfMemoryError(Thread * self,size_t byte_count,AllocatorType allocator_type)1501*795d594fSAndroid Build Coastguard Worker void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
1502*795d594fSAndroid Build Coastguard Worker // If we're in a stack overflow, do not create a new exception. It would require running the
1503*795d594fSAndroid Build Coastguard Worker // constructor, which will of course still be in a stack overflow. Note: we only care if the
1504*795d594fSAndroid Build Coastguard Worker // native stack has overflowed. If the simulated stack overflows, it is still possible that the
1505*795d594fSAndroid Build Coastguard Worker // native stack has room to create a new exception.
1506*795d594fSAndroid Build Coastguard Worker if (self->IsHandlingStackOverflow<kNativeStackType>()) {
1507*795d594fSAndroid Build Coastguard Worker self->SetException(
1508*795d594fSAndroid Build Coastguard Worker Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow());
1509*795d594fSAndroid Build Coastguard Worker return;
1510*795d594fSAndroid Build Coastguard Worker }
1511*795d594fSAndroid Build Coastguard Worker // Allow plugins to intercept out of memory errors.
1512*795d594fSAndroid Build Coastguard Worker Runtime::Current()->OutOfMemoryErrorHook();
1513*795d594fSAndroid Build Coastguard Worker
1514*795d594fSAndroid Build Coastguard Worker std::ostringstream oss;
1515*795d594fSAndroid Build Coastguard Worker size_t total_bytes_free = GetFreeMemory();
1516*795d594fSAndroid Build Coastguard Worker oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
1517*795d594fSAndroid Build Coastguard Worker << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM,"
1518*795d594fSAndroid Build Coastguard Worker << " target footprint " << target_footprint_.load(std::memory_order_relaxed)
1519*795d594fSAndroid Build Coastguard Worker << ", growth limit "
1520*795d594fSAndroid Build Coastguard Worker << growth_limit_;
1521*795d594fSAndroid Build Coastguard Worker // If the allocation failed due to fragmentation, print out the largest continuous allocation.
1522*795d594fSAndroid Build Coastguard Worker if (total_bytes_free >= byte_count) {
1523*795d594fSAndroid Build Coastguard Worker space::AllocSpace* space = nullptr;
1524*795d594fSAndroid Build Coastguard Worker if (allocator_type == kAllocatorTypeNonMoving) {
1525*795d594fSAndroid Build Coastguard Worker space = non_moving_space_;
1526*795d594fSAndroid Build Coastguard Worker } else if (allocator_type == kAllocatorTypeRosAlloc ||
1527*795d594fSAndroid Build Coastguard Worker allocator_type == kAllocatorTypeDlMalloc) {
1528*795d594fSAndroid Build Coastguard Worker space = main_space_;
1529*795d594fSAndroid Build Coastguard Worker } else if (allocator_type == kAllocatorTypeBumpPointer ||
1530*795d594fSAndroid Build Coastguard Worker allocator_type == kAllocatorTypeTLAB) {
1531*795d594fSAndroid Build Coastguard Worker space = bump_pointer_space_;
1532*795d594fSAndroid Build Coastguard Worker } else if (allocator_type == kAllocatorTypeRegion ||
1533*795d594fSAndroid Build Coastguard Worker allocator_type == kAllocatorTypeRegionTLAB) {
1534*795d594fSAndroid Build Coastguard Worker space = region_space_;
1535*795d594fSAndroid Build Coastguard Worker }
1536*795d594fSAndroid Build Coastguard Worker
1537*795d594fSAndroid Build Coastguard Worker // There is no fragmentation info to log for large-object space.
1538*795d594fSAndroid Build Coastguard Worker if (allocator_type != kAllocatorTypeLOS) {
1539*795d594fSAndroid Build Coastguard Worker CHECK(space != nullptr) << "allocator_type:" << allocator_type
1540*795d594fSAndroid Build Coastguard Worker << " byte_count:" << byte_count
1541*795d594fSAndroid Build Coastguard Worker << " total_bytes_free:" << total_bytes_free;
1542*795d594fSAndroid Build Coastguard Worker // LogFragmentationAllocFailure returns true if byte_count is greater than
1543*795d594fSAndroid Build Coastguard Worker // the largest free contiguous chunk in the space. Return value false
1544*795d594fSAndroid Build Coastguard Worker // means that we are throwing OOME because the amount of free heap after
1545*795d594fSAndroid Build Coastguard Worker // GC is less than kMinFreeHeapAfterGcForAlloc in proportion of the heap-size.
1546*795d594fSAndroid Build Coastguard Worker // Log an appropriate message in that case.
1547*795d594fSAndroid Build Coastguard Worker if (!space->LogFragmentationAllocFailure(oss, byte_count)) {
1548*795d594fSAndroid Build Coastguard Worker oss << "; giving up on allocation because <"
1549*795d594fSAndroid Build Coastguard Worker << kMinFreeHeapAfterGcForAlloc * 100
1550*795d594fSAndroid Build Coastguard Worker << "% of heap free after GC.";
1551*795d594fSAndroid Build Coastguard Worker }
1552*795d594fSAndroid Build Coastguard Worker }
1553*795d594fSAndroid Build Coastguard Worker }
1554*795d594fSAndroid Build Coastguard Worker self->ThrowOutOfMemoryError(oss.str().c_str());
1555*795d594fSAndroid Build Coastguard Worker }
1556*795d594fSAndroid Build Coastguard Worker
DoPendingCollectorTransition()1557*795d594fSAndroid Build Coastguard Worker void Heap::DoPendingCollectorTransition() {
1558*795d594fSAndroid Build Coastguard Worker CollectorType desired_collector_type = desired_collector_type_;
1559*795d594fSAndroid Build Coastguard Worker
1560*795d594fSAndroid Build Coastguard Worker if (collector_type_ == kCollectorTypeCC || collector_type_ == kCollectorTypeCMC) {
1561*795d594fSAndroid Build Coastguard Worker // App's allocations (since last GC) more than the threshold then do TransitionGC
1562*795d594fSAndroid Build Coastguard Worker // when the app was in background. If not then don't do TransitionGC.
1563*795d594fSAndroid Build Coastguard Worker // num_bytes_allocated_since_gc should always be positive even if initially
1564*795d594fSAndroid Build Coastguard Worker // num_bytes_alive_after_gc_ is coming from Zygote. This gives positive or zero value.
1565*795d594fSAndroid Build Coastguard Worker size_t num_bytes_allocated_since_gc =
1566*795d594fSAndroid Build Coastguard Worker UnsignedDifference(GetBytesAllocated(), num_bytes_alive_after_gc_);
1567*795d594fSAndroid Build Coastguard Worker if (num_bytes_allocated_since_gc <
1568*795d594fSAndroid Build Coastguard Worker (UnsignedDifference(target_footprint_.load(std::memory_order_relaxed),
1569*795d594fSAndroid Build Coastguard Worker num_bytes_alive_after_gc_)/4)
1570*795d594fSAndroid Build Coastguard Worker && !kStressCollectorTransition
1571*795d594fSAndroid Build Coastguard Worker && !IsLowMemoryMode()) {
1572*795d594fSAndroid Build Coastguard Worker return;
1573*795d594fSAndroid Build Coastguard Worker }
1574*795d594fSAndroid Build Coastguard Worker }
1575*795d594fSAndroid Build Coastguard Worker
1576*795d594fSAndroid Build Coastguard Worker // Launch homogeneous space compaction if it is desired.
1577*795d594fSAndroid Build Coastguard Worker if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
1578*795d594fSAndroid Build Coastguard Worker if (!CareAboutPauseTimes()) {
1579*795d594fSAndroid Build Coastguard Worker PerformHomogeneousSpaceCompact();
1580*795d594fSAndroid Build Coastguard Worker } else {
1581*795d594fSAndroid Build Coastguard Worker VLOG(gc) << "Homogeneous compaction ignored due to jank perceptible process state";
1582*795d594fSAndroid Build Coastguard Worker }
1583*795d594fSAndroid Build Coastguard Worker } else if (desired_collector_type == kCollectorTypeCCBackground ||
1584*795d594fSAndroid Build Coastguard Worker desired_collector_type == kCollectorTypeCMCBackground) {
1585*795d594fSAndroid Build Coastguard Worker if (!CareAboutPauseTimes()) {
1586*795d594fSAndroid Build Coastguard Worker // Invoke full compaction.
1587*795d594fSAndroid Build Coastguard Worker CollectGarbageInternal(collector::kGcTypeFull,
1588*795d594fSAndroid Build Coastguard Worker kGcCauseCollectorTransition,
1589*795d594fSAndroid Build Coastguard Worker /*clear_soft_references=*/false, GetCurrentGcNum() + 1);
1590*795d594fSAndroid Build Coastguard Worker } else {
1591*795d594fSAndroid Build Coastguard Worker VLOG(gc) << "background compaction ignored due to jank perceptible process state";
1592*795d594fSAndroid Build Coastguard Worker }
1593*795d594fSAndroid Build Coastguard Worker } else {
1594*795d594fSAndroid Build Coastguard Worker CHECK_EQ(desired_collector_type, collector_type_) << "Unsupported collector transition";
1595*795d594fSAndroid Build Coastguard Worker }
1596*795d594fSAndroid Build Coastguard Worker }
1597*795d594fSAndroid Build Coastguard Worker
Trim(Thread * self)1598*795d594fSAndroid Build Coastguard Worker void Heap::Trim(Thread* self) {
1599*795d594fSAndroid Build Coastguard Worker Runtime* const runtime = Runtime::Current();
1600*795d594fSAndroid Build Coastguard Worker if (!CareAboutPauseTimes()) {
1601*795d594fSAndroid Build Coastguard Worker // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
1602*795d594fSAndroid Build Coastguard Worker // about pauses.
1603*795d594fSAndroid Build Coastguard Worker ScopedTrace trace("Deflating monitors");
1604*795d594fSAndroid Build Coastguard Worker // Avoid race conditions on the lock word for CC.
1605*795d594fSAndroid Build Coastguard Worker ScopedGCCriticalSection gcs(self, kGcCauseTrim, kCollectorTypeHeapTrim);
1606*795d594fSAndroid Build Coastguard Worker ScopedSuspendAll ssa(__FUNCTION__);
1607*795d594fSAndroid Build Coastguard Worker uint64_t start_time = NanoTime();
1608*795d594fSAndroid Build Coastguard Worker size_t count = runtime->GetMonitorList()->DeflateMonitors();
1609*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Deflating " << count << " monitors took "
1610*795d594fSAndroid Build Coastguard Worker << PrettyDuration(NanoTime() - start_time);
1611*795d594fSAndroid Build Coastguard Worker }
1612*795d594fSAndroid Build Coastguard Worker TrimIndirectReferenceTables(self);
1613*795d594fSAndroid Build Coastguard Worker TrimSpaces(self);
1614*795d594fSAndroid Build Coastguard Worker // Trim arenas that may have been used by JIT or verifier.
1615*795d594fSAndroid Build Coastguard Worker runtime->GetArenaPool()->TrimMaps();
1616*795d594fSAndroid Build Coastguard Worker }
1617*795d594fSAndroid Build Coastguard Worker
1618*795d594fSAndroid Build Coastguard Worker class TrimIndirectReferenceTableClosure : public Closure {
1619*795d594fSAndroid Build Coastguard Worker public:
TrimIndirectReferenceTableClosure(Barrier * barrier)1620*795d594fSAndroid Build Coastguard Worker explicit TrimIndirectReferenceTableClosure(Barrier* barrier) : barrier_(barrier) {
1621*795d594fSAndroid Build Coastguard Worker }
Run(Thread * thread)1622*795d594fSAndroid Build Coastguard Worker void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
1623*795d594fSAndroid Build Coastguard Worker thread->GetJniEnv()->TrimLocals();
1624*795d594fSAndroid Build Coastguard Worker // If thread is a running mutator, then act on behalf of the trim thread.
1625*795d594fSAndroid Build Coastguard Worker // See the code in ThreadList::RunCheckpoint.
1626*795d594fSAndroid Build Coastguard Worker barrier_->Pass(Thread::Current());
1627*795d594fSAndroid Build Coastguard Worker }
1628*795d594fSAndroid Build Coastguard Worker
1629*795d594fSAndroid Build Coastguard Worker private:
1630*795d594fSAndroid Build Coastguard Worker Barrier* const barrier_;
1631*795d594fSAndroid Build Coastguard Worker };
1632*795d594fSAndroid Build Coastguard Worker
TrimIndirectReferenceTables(Thread * self)1633*795d594fSAndroid Build Coastguard Worker void Heap::TrimIndirectReferenceTables(Thread* self) {
1634*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(self);
1635*795d594fSAndroid Build Coastguard Worker ScopedTrace trace(__PRETTY_FUNCTION__);
1636*795d594fSAndroid Build Coastguard Worker JavaVMExt* vm = soa.Vm();
1637*795d594fSAndroid Build Coastguard Worker // Trim globals indirect reference table.
1638*795d594fSAndroid Build Coastguard Worker vm->TrimGlobals();
1639*795d594fSAndroid Build Coastguard Worker // Trim locals indirect reference tables.
1640*795d594fSAndroid Build Coastguard Worker // TODO: May also want to look for entirely empty pages maintained by SmallIrtAllocator.
1641*795d594fSAndroid Build Coastguard Worker Barrier barrier(0);
1642*795d594fSAndroid Build Coastguard Worker TrimIndirectReferenceTableClosure closure(&barrier);
1643*795d594fSAndroid Build Coastguard Worker size_t barrier_count = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1644*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc(self, ThreadState::kWaitingForCheckPointsToRun);
1645*795d594fSAndroid Build Coastguard Worker if (barrier_count != 0) {
1646*795d594fSAndroid Build Coastguard Worker barrier.Increment(self, barrier_count);
1647*795d594fSAndroid Build Coastguard Worker }
1648*795d594fSAndroid Build Coastguard Worker }
1649*795d594fSAndroid Build Coastguard Worker
StartGC(Thread * self,GcCause cause,CollectorType collector_type)1650*795d594fSAndroid Build Coastguard Worker void Heap::StartGC(Thread* self, GcCause cause, CollectorType collector_type) {
1651*795d594fSAndroid Build Coastguard Worker // This can be called in either kRunnable or suspended states.
1652*795d594fSAndroid Build Coastguard Worker // TODO: Consider fixing that?
1653*795d594fSAndroid Build Coastguard Worker ThreadState old_thread_state = self->GetState();
1654*795d594fSAndroid Build Coastguard Worker if (old_thread_state == ThreadState::kRunnable) {
1655*795d594fSAndroid Build Coastguard Worker Locks::mutator_lock_->AssertSharedHeld(self);
1656*795d594fSAndroid Build Coastguard Worker // Manually inlining the following call breaks thread-safety analysis.
1657*795d594fSAndroid Build Coastguard Worker StartGCRunnable(self, cause, collector_type);
1658*795d594fSAndroid Build Coastguard Worker return;
1659*795d594fSAndroid Build Coastguard Worker }
1660*795d594fSAndroid Build Coastguard Worker Locks::mutator_lock_->AssertNotHeld(self);
1661*795d594fSAndroid Build Coastguard Worker self->SetState(ThreadState::kWaitingForGcToComplete);
1662*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *gc_complete_lock_);
1663*795d594fSAndroid Build Coastguard Worker WaitForGcToCompleteLocked(cause, self);
1664*795d594fSAndroid Build Coastguard Worker collector_type_running_ = collector_type;
1665*795d594fSAndroid Build Coastguard Worker last_gc_cause_ = cause;
1666*795d594fSAndroid Build Coastguard Worker thread_running_gc_ = self;
1667*795d594fSAndroid Build Coastguard Worker self->SetState(old_thread_state);
1668*795d594fSAndroid Build Coastguard Worker }
1669*795d594fSAndroid Build Coastguard Worker
StartGCRunnable(Thread * self,GcCause cause,CollectorType collector_type)1670*795d594fSAndroid Build Coastguard Worker void Heap::StartGCRunnable(Thread* self, GcCause cause, CollectorType collector_type) {
1671*795d594fSAndroid Build Coastguard Worker Locks::mutator_lock_->AssertSharedHeld(self);
1672*795d594fSAndroid Build Coastguard Worker while (true) {
1673*795d594fSAndroid Build Coastguard Worker self->TransitionFromRunnableToSuspended(ThreadState::kWaitingForGcToComplete);
1674*795d594fSAndroid Build Coastguard Worker {
1675*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *gc_complete_lock_);
1676*795d594fSAndroid Build Coastguard Worker // Ensure there is only one GC at a time.
1677*795d594fSAndroid Build Coastguard Worker WaitForGcToCompleteLocked(cause, self);
1678*795d594fSAndroid Build Coastguard Worker collector_type_running_ = collector_type;
1679*795d594fSAndroid Build Coastguard Worker last_gc_cause_ = cause;
1680*795d594fSAndroid Build Coastguard Worker thread_running_gc_ = self;
1681*795d594fSAndroid Build Coastguard Worker }
1682*795d594fSAndroid Build Coastguard Worker // We have to be careful returning to runnable state, since that could cause us to block.
1683*795d594fSAndroid Build Coastguard Worker // That would be bad, since collector_type_running_ is set, and hence no GC is possible in this
1684*795d594fSAndroid Build Coastguard Worker // state, allowing deadlock.
1685*795d594fSAndroid Build Coastguard Worker if (LIKELY(self->TryTransitionFromSuspendedToRunnable())) {
1686*795d594fSAndroid Build Coastguard Worker return;
1687*795d594fSAndroid Build Coastguard Worker }
1688*795d594fSAndroid Build Coastguard Worker {
1689*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *gc_complete_lock_);
1690*795d594fSAndroid Build Coastguard Worker collector_type_running_ = kCollectorTypeNone;
1691*795d594fSAndroid Build Coastguard Worker thread_running_gc_ = nullptr;
1692*795d594fSAndroid Build Coastguard Worker }
1693*795d594fSAndroid Build Coastguard Worker self->TransitionFromSuspendedToRunnable(); // Will handle suspension request and block.
1694*795d594fSAndroid Build Coastguard Worker }
1695*795d594fSAndroid Build Coastguard Worker }
1696*795d594fSAndroid Build Coastguard Worker
TrimSpaces(Thread * self)1697*795d594fSAndroid Build Coastguard Worker void Heap::TrimSpaces(Thread* self) {
1698*795d594fSAndroid Build Coastguard Worker // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1699*795d594fSAndroid Build Coastguard Worker // trimming.
1700*795d594fSAndroid Build Coastguard Worker StartGC(self, kGcCauseTrim, kCollectorTypeHeapTrim);
1701*795d594fSAndroid Build Coastguard Worker ScopedTrace trace(__PRETTY_FUNCTION__);
1702*795d594fSAndroid Build Coastguard Worker const uint64_t start_ns = NanoTime();
1703*795d594fSAndroid Build Coastguard Worker // Trim the managed spaces.
1704*795d594fSAndroid Build Coastguard Worker uint64_t total_alloc_space_allocated = 0;
1705*795d594fSAndroid Build Coastguard Worker uint64_t total_alloc_space_size = 0;
1706*795d594fSAndroid Build Coastguard Worker uint64_t managed_reclaimed = 0;
1707*795d594fSAndroid Build Coastguard Worker {
1708*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(self);
1709*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
1710*795d594fSAndroid Build Coastguard Worker if (space->IsMallocSpace()) {
1711*795d594fSAndroid Build Coastguard Worker gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1712*795d594fSAndroid Build Coastguard Worker if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1713*795d594fSAndroid Build Coastguard Worker // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1714*795d594fSAndroid Build Coastguard Worker // for a long period of time.
1715*795d594fSAndroid Build Coastguard Worker managed_reclaimed += malloc_space->Trim();
1716*795d594fSAndroid Build Coastguard Worker }
1717*795d594fSAndroid Build Coastguard Worker total_alloc_space_size += malloc_space->Size();
1718*795d594fSAndroid Build Coastguard Worker }
1719*795d594fSAndroid Build Coastguard Worker }
1720*795d594fSAndroid Build Coastguard Worker }
1721*795d594fSAndroid Build Coastguard Worker total_alloc_space_allocated = GetBytesAllocated();
1722*795d594fSAndroid Build Coastguard Worker if (large_object_space_ != nullptr) {
1723*795d594fSAndroid Build Coastguard Worker total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1724*795d594fSAndroid Build Coastguard Worker }
1725*795d594fSAndroid Build Coastguard Worker if (bump_pointer_space_ != nullptr) {
1726*795d594fSAndroid Build Coastguard Worker total_alloc_space_allocated -= bump_pointer_space_->Size();
1727*795d594fSAndroid Build Coastguard Worker }
1728*795d594fSAndroid Build Coastguard Worker if (region_space_ != nullptr) {
1729*795d594fSAndroid Build Coastguard Worker total_alloc_space_allocated -= region_space_->GetBytesAllocated();
1730*795d594fSAndroid Build Coastguard Worker }
1731*795d594fSAndroid Build Coastguard Worker const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1732*795d594fSAndroid Build Coastguard Worker static_cast<float>(total_alloc_space_size);
1733*795d594fSAndroid Build Coastguard Worker uint64_t gc_heap_end_ns = NanoTime();
1734*795d594fSAndroid Build Coastguard Worker // We never move things in the native heap, so we can finish the GC at this point.
1735*795d594fSAndroid Build Coastguard Worker FinishGC(self, collector::kGcTypeNone);
1736*795d594fSAndroid Build Coastguard Worker
1737*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
1738*795d594fSAndroid Build Coastguard Worker << ", advised=" << PrettySize(managed_reclaimed) << ") heap. Managed heap utilization of "
1739*795d594fSAndroid Build Coastguard Worker << static_cast<int>(100 * managed_utilization) << "%.";
1740*795d594fSAndroid Build Coastguard Worker }
1741*795d594fSAndroid Build Coastguard Worker
IsValidObjectAddress(const void * addr) const1742*795d594fSAndroid Build Coastguard Worker bool Heap::IsValidObjectAddress(const void* addr) const {
1743*795d594fSAndroid Build Coastguard Worker if (addr == nullptr) {
1744*795d594fSAndroid Build Coastguard Worker return true;
1745*795d594fSAndroid Build Coastguard Worker }
1746*795d594fSAndroid Build Coastguard Worker return IsAligned<kObjectAlignment>(addr) && FindSpaceFromAddress(addr) != nullptr;
1747*795d594fSAndroid Build Coastguard Worker }
1748*795d594fSAndroid Build Coastguard Worker
IsNonDiscontinuousSpaceHeapAddress(const void * addr) const1749*795d594fSAndroid Build Coastguard Worker bool Heap::IsNonDiscontinuousSpaceHeapAddress(const void* addr) const {
1750*795d594fSAndroid Build Coastguard Worker return FindContinuousSpaceFromAddress(reinterpret_cast<const mirror::Object*>(addr)) != nullptr;
1751*795d594fSAndroid Build Coastguard Worker }
1752*795d594fSAndroid Build Coastguard Worker
IsLiveObjectLocked(ObjPtr<mirror::Object> obj,bool search_allocation_stack,bool search_live_stack,bool sorted)1753*795d594fSAndroid Build Coastguard Worker bool Heap::IsLiveObjectLocked(ObjPtr<mirror::Object> obj,
1754*795d594fSAndroid Build Coastguard Worker bool search_allocation_stack,
1755*795d594fSAndroid Build Coastguard Worker bool search_live_stack,
1756*795d594fSAndroid Build Coastguard Worker bool sorted) {
1757*795d594fSAndroid Build Coastguard Worker if (UNLIKELY(!IsAligned<kObjectAlignment>(obj.Ptr()))) {
1758*795d594fSAndroid Build Coastguard Worker return false;
1759*795d594fSAndroid Build Coastguard Worker }
1760*795d594fSAndroid Build Coastguard Worker if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj.Ptr())) {
1761*795d594fSAndroid Build Coastguard Worker mirror::Class* klass = obj->GetClass<kVerifyNone>();
1762*795d594fSAndroid Build Coastguard Worker if (obj == klass) {
1763*795d594fSAndroid Build Coastguard Worker // This case happens for java.lang.Class.
1764*795d594fSAndroid Build Coastguard Worker return true;
1765*795d594fSAndroid Build Coastguard Worker }
1766*795d594fSAndroid Build Coastguard Worker return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1767*795d594fSAndroid Build Coastguard Worker } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj.Ptr())) {
1768*795d594fSAndroid Build Coastguard Worker // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1769*795d594fSAndroid Build Coastguard Worker // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1770*795d594fSAndroid Build Coastguard Worker return temp_space_->Contains(obj.Ptr());
1771*795d594fSAndroid Build Coastguard Worker }
1772*795d594fSAndroid Build Coastguard Worker if (region_space_ != nullptr && region_space_->HasAddress(obj.Ptr())) {
1773*795d594fSAndroid Build Coastguard Worker return true;
1774*795d594fSAndroid Build Coastguard Worker }
1775*795d594fSAndroid Build Coastguard Worker space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
1776*795d594fSAndroid Build Coastguard Worker space::DiscontinuousSpace* d_space = nullptr;
1777*795d594fSAndroid Build Coastguard Worker if (c_space != nullptr) {
1778*795d594fSAndroid Build Coastguard Worker if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
1779*795d594fSAndroid Build Coastguard Worker return true;
1780*795d594fSAndroid Build Coastguard Worker }
1781*795d594fSAndroid Build Coastguard Worker } else {
1782*795d594fSAndroid Build Coastguard Worker d_space = FindDiscontinuousSpaceFromObject(obj, true);
1783*795d594fSAndroid Build Coastguard Worker if (d_space != nullptr) {
1784*795d594fSAndroid Build Coastguard Worker if (d_space->GetLiveBitmap()->Test(obj.Ptr())) {
1785*795d594fSAndroid Build Coastguard Worker return true;
1786*795d594fSAndroid Build Coastguard Worker }
1787*795d594fSAndroid Build Coastguard Worker }
1788*795d594fSAndroid Build Coastguard Worker }
1789*795d594fSAndroid Build Coastguard Worker // This is covering the allocation/live stack swapping that is done without mutators suspended.
1790*795d594fSAndroid Build Coastguard Worker for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1791*795d594fSAndroid Build Coastguard Worker if (i > 0) {
1792*795d594fSAndroid Build Coastguard Worker NanoSleep(MsToNs(10));
1793*795d594fSAndroid Build Coastguard Worker }
1794*795d594fSAndroid Build Coastguard Worker if (search_allocation_stack) {
1795*795d594fSAndroid Build Coastguard Worker if (sorted) {
1796*795d594fSAndroid Build Coastguard Worker if (allocation_stack_->ContainsSorted(obj.Ptr())) {
1797*795d594fSAndroid Build Coastguard Worker return true;
1798*795d594fSAndroid Build Coastguard Worker }
1799*795d594fSAndroid Build Coastguard Worker } else if (allocation_stack_->Contains(obj.Ptr())) {
1800*795d594fSAndroid Build Coastguard Worker return true;
1801*795d594fSAndroid Build Coastguard Worker }
1802*795d594fSAndroid Build Coastguard Worker }
1803*795d594fSAndroid Build Coastguard Worker
1804*795d594fSAndroid Build Coastguard Worker if (search_live_stack) {
1805*795d594fSAndroid Build Coastguard Worker if (sorted) {
1806*795d594fSAndroid Build Coastguard Worker if (live_stack_->ContainsSorted(obj.Ptr())) {
1807*795d594fSAndroid Build Coastguard Worker return true;
1808*795d594fSAndroid Build Coastguard Worker }
1809*795d594fSAndroid Build Coastguard Worker } else if (live_stack_->Contains(obj.Ptr())) {
1810*795d594fSAndroid Build Coastguard Worker return true;
1811*795d594fSAndroid Build Coastguard Worker }
1812*795d594fSAndroid Build Coastguard Worker }
1813*795d594fSAndroid Build Coastguard Worker }
1814*795d594fSAndroid Build Coastguard Worker // We need to check the bitmaps again since there is a race where we mark something as live and
1815*795d594fSAndroid Build Coastguard Worker // then clear the stack containing it.
1816*795d594fSAndroid Build Coastguard Worker if (c_space != nullptr) {
1817*795d594fSAndroid Build Coastguard Worker if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
1818*795d594fSAndroid Build Coastguard Worker return true;
1819*795d594fSAndroid Build Coastguard Worker }
1820*795d594fSAndroid Build Coastguard Worker } else {
1821*795d594fSAndroid Build Coastguard Worker d_space = FindDiscontinuousSpaceFromObject(obj, true);
1822*795d594fSAndroid Build Coastguard Worker if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj.Ptr())) {
1823*795d594fSAndroid Build Coastguard Worker return true;
1824*795d594fSAndroid Build Coastguard Worker }
1825*795d594fSAndroid Build Coastguard Worker }
1826*795d594fSAndroid Build Coastguard Worker return false;
1827*795d594fSAndroid Build Coastguard Worker }
1828*795d594fSAndroid Build Coastguard Worker
DumpSpaces() const1829*795d594fSAndroid Build Coastguard Worker std::string Heap::DumpSpaces() const {
1830*795d594fSAndroid Build Coastguard Worker std::ostringstream oss;
1831*795d594fSAndroid Build Coastguard Worker DumpSpaces(oss);
1832*795d594fSAndroid Build Coastguard Worker return oss.str();
1833*795d594fSAndroid Build Coastguard Worker }
1834*795d594fSAndroid Build Coastguard Worker
DumpSpaces(std::ostream & stream) const1835*795d594fSAndroid Build Coastguard Worker void Heap::DumpSpaces(std::ostream& stream) const {
1836*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
1837*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1838*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1839*795d594fSAndroid Build Coastguard Worker stream << space << " " << *space << "\n";
1840*795d594fSAndroid Build Coastguard Worker if (live_bitmap != nullptr) {
1841*795d594fSAndroid Build Coastguard Worker stream << live_bitmap << " " << *live_bitmap << "\n";
1842*795d594fSAndroid Build Coastguard Worker }
1843*795d594fSAndroid Build Coastguard Worker if (mark_bitmap != nullptr) {
1844*795d594fSAndroid Build Coastguard Worker stream << mark_bitmap << " " << *mark_bitmap << "\n";
1845*795d594fSAndroid Build Coastguard Worker }
1846*795d594fSAndroid Build Coastguard Worker }
1847*795d594fSAndroid Build Coastguard Worker for (const auto& space : discontinuous_spaces_) {
1848*795d594fSAndroid Build Coastguard Worker stream << space << " " << *space << "\n";
1849*795d594fSAndroid Build Coastguard Worker }
1850*795d594fSAndroid Build Coastguard Worker }
1851*795d594fSAndroid Build Coastguard Worker
VerifyObjectBody(ObjPtr<mirror::Object> obj)1852*795d594fSAndroid Build Coastguard Worker void Heap::VerifyObjectBody(ObjPtr<mirror::Object> obj) {
1853*795d594fSAndroid Build Coastguard Worker if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1854*795d594fSAndroid Build Coastguard Worker return;
1855*795d594fSAndroid Build Coastguard Worker }
1856*795d594fSAndroid Build Coastguard Worker
1857*795d594fSAndroid Build Coastguard Worker // Ignore early dawn of the universe verifications.
1858*795d594fSAndroid Build Coastguard Worker if (UNLIKELY(num_bytes_allocated_.load(std::memory_order_relaxed) < 10 * KB)) {
1859*795d594fSAndroid Build Coastguard Worker return;
1860*795d594fSAndroid Build Coastguard Worker }
1861*795d594fSAndroid Build Coastguard Worker CHECK_ALIGNED(obj.Ptr(), kObjectAlignment) << "Object isn't aligned";
1862*795d594fSAndroid Build Coastguard Worker mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
1863*795d594fSAndroid Build Coastguard Worker CHECK(c != nullptr) << "Null class in object " << obj;
1864*795d594fSAndroid Build Coastguard Worker CHECK_ALIGNED(c, kObjectAlignment) << "Class " << c << " not aligned in object " << obj;
1865*795d594fSAndroid Build Coastguard Worker CHECK(VerifyClassClass(c));
1866*795d594fSAndroid Build Coastguard Worker
1867*795d594fSAndroid Build Coastguard Worker if (verify_object_mode_ > kVerifyObjectModeFast) {
1868*795d594fSAndroid Build Coastguard Worker // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
1869*795d594fSAndroid Build Coastguard Worker CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
1870*795d594fSAndroid Build Coastguard Worker }
1871*795d594fSAndroid Build Coastguard Worker }
1872*795d594fSAndroid Build Coastguard Worker
VerifyHeap()1873*795d594fSAndroid Build Coastguard Worker void Heap::VerifyHeap() {
1874*795d594fSAndroid Build Coastguard Worker ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1875*795d594fSAndroid Build Coastguard Worker auto visitor = [&](mirror::Object* obj) NO_THREAD_SAFETY_ANALYSIS {
1876*795d594fSAndroid Build Coastguard Worker VerifyObjectBody(obj);
1877*795d594fSAndroid Build Coastguard Worker };
1878*795d594fSAndroid Build Coastguard Worker // Technically we need the mutator lock here to call Visit. However, VerifyObjectBody is already
1879*795d594fSAndroid Build Coastguard Worker // NO_THREAD_SAFETY_ANALYSIS.
1880*795d594fSAndroid Build Coastguard Worker auto no_thread_safety_analysis = [&]() NO_THREAD_SAFETY_ANALYSIS {
1881*795d594fSAndroid Build Coastguard Worker GetLiveBitmap()->Visit(visitor);
1882*795d594fSAndroid Build Coastguard Worker };
1883*795d594fSAndroid Build Coastguard Worker no_thread_safety_analysis();
1884*795d594fSAndroid Build Coastguard Worker }
1885*795d594fSAndroid Build Coastguard Worker
RecordFree(uint64_t freed_objects,int64_t freed_bytes)1886*795d594fSAndroid Build Coastguard Worker void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
1887*795d594fSAndroid Build Coastguard Worker // Use signed comparison since freed bytes can be negative when background compaction foreground
1888*795d594fSAndroid Build Coastguard Worker // transitions occurs. This is typically due to objects moving from a bump pointer space to a
1889*795d594fSAndroid Build Coastguard Worker // free list backed space, which may increase memory footprint due to padding and binning.
1890*795d594fSAndroid Build Coastguard Worker RACING_DCHECK_LE(freed_bytes,
1891*795d594fSAndroid Build Coastguard Worker static_cast<int64_t>(num_bytes_allocated_.load(std::memory_order_relaxed)));
1892*795d594fSAndroid Build Coastguard Worker // Note: This relies on 2s complement for handling negative freed_bytes.
1893*795d594fSAndroid Build Coastguard Worker num_bytes_allocated_.fetch_sub(static_cast<ssize_t>(freed_bytes), std::memory_order_relaxed);
1894*795d594fSAndroid Build Coastguard Worker if (Runtime::Current()->HasStatsEnabled()) {
1895*795d594fSAndroid Build Coastguard Worker RuntimeStats* thread_stats = Thread::Current()->GetStats();
1896*795d594fSAndroid Build Coastguard Worker thread_stats->freed_objects += freed_objects;
1897*795d594fSAndroid Build Coastguard Worker thread_stats->freed_bytes += freed_bytes;
1898*795d594fSAndroid Build Coastguard Worker // TODO: Do this concurrently.
1899*795d594fSAndroid Build Coastguard Worker RuntimeStats* global_stats = Runtime::Current()->GetStats();
1900*795d594fSAndroid Build Coastguard Worker global_stats->freed_objects += freed_objects;
1901*795d594fSAndroid Build Coastguard Worker global_stats->freed_bytes += freed_bytes;
1902*795d594fSAndroid Build Coastguard Worker }
1903*795d594fSAndroid Build Coastguard Worker }
1904*795d594fSAndroid Build Coastguard Worker
RecordFreeRevoke()1905*795d594fSAndroid Build Coastguard Worker void Heap::RecordFreeRevoke() {
1906*795d594fSAndroid Build Coastguard Worker // Subtract num_bytes_freed_revoke_ from num_bytes_allocated_ to cancel out the
1907*795d594fSAndroid Build Coastguard Worker // ahead-of-time, bulk counting of bytes allocated in rosalloc thread-local buffers.
1908*795d594fSAndroid Build Coastguard Worker // If there's a concurrent revoke, ok to not necessarily reset num_bytes_freed_revoke_
1909*795d594fSAndroid Build Coastguard Worker // all the way to zero exactly as the remainder will be subtracted at the next GC.
1910*795d594fSAndroid Build Coastguard Worker size_t bytes_freed = num_bytes_freed_revoke_.load(std::memory_order_relaxed);
1911*795d594fSAndroid Build Coastguard Worker CHECK_GE(num_bytes_freed_revoke_.fetch_sub(bytes_freed, std::memory_order_relaxed),
1912*795d594fSAndroid Build Coastguard Worker bytes_freed) << "num_bytes_freed_revoke_ underflow";
1913*795d594fSAndroid Build Coastguard Worker CHECK_GE(num_bytes_allocated_.fetch_sub(bytes_freed, std::memory_order_relaxed),
1914*795d594fSAndroid Build Coastguard Worker bytes_freed) << "num_bytes_allocated_ underflow";
1915*795d594fSAndroid Build Coastguard Worker GetCurrentGcIteration()->SetFreedRevoke(bytes_freed);
1916*795d594fSAndroid Build Coastguard Worker }
1917*795d594fSAndroid Build Coastguard Worker
GetRosAllocSpace(gc::allocator::RosAlloc * rosalloc) const1918*795d594fSAndroid Build Coastguard Worker space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
1919*795d594fSAndroid Build Coastguard Worker if (rosalloc_space_ != nullptr && rosalloc_space_->GetRosAlloc() == rosalloc) {
1920*795d594fSAndroid Build Coastguard Worker return rosalloc_space_;
1921*795d594fSAndroid Build Coastguard Worker }
1922*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
1923*795d594fSAndroid Build Coastguard Worker if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1924*795d594fSAndroid Build Coastguard Worker if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1925*795d594fSAndroid Build Coastguard Worker return space->AsContinuousSpace()->AsRosAllocSpace();
1926*795d594fSAndroid Build Coastguard Worker }
1927*795d594fSAndroid Build Coastguard Worker }
1928*795d594fSAndroid Build Coastguard Worker }
1929*795d594fSAndroid Build Coastguard Worker return nullptr;
1930*795d594fSAndroid Build Coastguard Worker }
1931*795d594fSAndroid Build Coastguard Worker
EntrypointsInstrumented()1932*795d594fSAndroid Build Coastguard Worker static inline bool EntrypointsInstrumented() REQUIRES_SHARED(Locks::mutator_lock_) {
1933*795d594fSAndroid Build Coastguard Worker instrumentation::Instrumentation* const instrumentation =
1934*795d594fSAndroid Build Coastguard Worker Runtime::Current()->GetInstrumentation();
1935*795d594fSAndroid Build Coastguard Worker return instrumentation != nullptr && instrumentation->AllocEntrypointsInstrumented();
1936*795d594fSAndroid Build Coastguard Worker }
1937*795d594fSAndroid Build Coastguard Worker
AllocateInternalWithGc(Thread * self,AllocatorType allocator,bool instrumented,size_t alloc_size,size_t * bytes_allocated,size_t * usable_size,size_t * bytes_tl_bulk_allocated,ObjPtr<mirror::Class> * klass)1938*795d594fSAndroid Build Coastguard Worker mirror::Object* Heap::AllocateInternalWithGc(Thread* self,
1939*795d594fSAndroid Build Coastguard Worker AllocatorType allocator,
1940*795d594fSAndroid Build Coastguard Worker bool instrumented,
1941*795d594fSAndroid Build Coastguard Worker size_t alloc_size,
1942*795d594fSAndroid Build Coastguard Worker size_t* bytes_allocated,
1943*795d594fSAndroid Build Coastguard Worker size_t* usable_size,
1944*795d594fSAndroid Build Coastguard Worker size_t* bytes_tl_bulk_allocated,
1945*795d594fSAndroid Build Coastguard Worker ObjPtr<mirror::Class>* klass) {
1946*795d594fSAndroid Build Coastguard Worker bool was_default_allocator = allocator == GetCurrentAllocator();
1947*795d594fSAndroid Build Coastguard Worker // Make sure there is no pending exception since we may need to throw an OOME.
1948*795d594fSAndroid Build Coastguard Worker self->AssertNoPendingException();
1949*795d594fSAndroid Build Coastguard Worker DCHECK(klass != nullptr);
1950*795d594fSAndroid Build Coastguard Worker
1951*795d594fSAndroid Build Coastguard Worker StackHandleScope<1> hs(self);
1952*795d594fSAndroid Build Coastguard Worker HandleWrapperObjPtr<mirror::Class> h_klass(hs.NewHandleWrapper(klass));
1953*795d594fSAndroid Build Coastguard Worker
1954*795d594fSAndroid Build Coastguard Worker auto send_object_pre_alloc =
1955*795d594fSAndroid Build Coastguard Worker [&]() REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_) {
1956*795d594fSAndroid Build Coastguard Worker if (UNLIKELY(instrumented)) {
1957*795d594fSAndroid Build Coastguard Worker AllocationListener* l = alloc_listener_.load(std::memory_order_seq_cst);
1958*795d594fSAndroid Build Coastguard Worker if (UNLIKELY(l != nullptr) && UNLIKELY(l->HasPreAlloc())) {
1959*795d594fSAndroid Build Coastguard Worker l->PreObjectAllocated(self, h_klass, &alloc_size);
1960*795d594fSAndroid Build Coastguard Worker }
1961*795d594fSAndroid Build Coastguard Worker }
1962*795d594fSAndroid Build Coastguard Worker };
1963*795d594fSAndroid Build Coastguard Worker #define PERFORM_SUSPENDING_OPERATION(op) \
1964*795d594fSAndroid Build Coastguard Worker [&]() REQUIRES(Roles::uninterruptible_) REQUIRES_SHARED(Locks::mutator_lock_) { \
1965*795d594fSAndroid Build Coastguard Worker ScopedAllowThreadSuspension ats; \
1966*795d594fSAndroid Build Coastguard Worker auto res = (op); \
1967*795d594fSAndroid Build Coastguard Worker send_object_pre_alloc(); \
1968*795d594fSAndroid Build Coastguard Worker return res; \
1969*795d594fSAndroid Build Coastguard Worker }()
1970*795d594fSAndroid Build Coastguard Worker
1971*795d594fSAndroid Build Coastguard Worker // The allocation failed. If the GC is running, block until it completes, and then retry the
1972*795d594fSAndroid Build Coastguard Worker // allocation.
1973*795d594fSAndroid Build Coastguard Worker collector::GcType last_gc =
1974*795d594fSAndroid Build Coastguard Worker PERFORM_SUSPENDING_OPERATION(WaitForGcToComplete(kGcCauseForAlloc, self));
1975*795d594fSAndroid Build Coastguard Worker // If we were the default allocator but the allocator changed while we were suspended,
1976*795d594fSAndroid Build Coastguard Worker // abort the allocation.
1977*795d594fSAndroid Build Coastguard Worker if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1978*795d594fSAndroid Build Coastguard Worker (!instrumented && EntrypointsInstrumented())) {
1979*795d594fSAndroid Build Coastguard Worker return nullptr;
1980*795d594fSAndroid Build Coastguard Worker }
1981*795d594fSAndroid Build Coastguard Worker uint32_t starting_gc_num = GetCurrentGcNum();
1982*795d594fSAndroid Build Coastguard Worker if (last_gc != collector::kGcTypeNone) {
1983*795d594fSAndroid Build Coastguard Worker // A GC was in progress and we blocked, retry allocation now that memory has been freed.
1984*795d594fSAndroid Build Coastguard Worker mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1985*795d594fSAndroid Build Coastguard Worker usable_size, bytes_tl_bulk_allocated);
1986*795d594fSAndroid Build Coastguard Worker if (ptr != nullptr) {
1987*795d594fSAndroid Build Coastguard Worker return ptr;
1988*795d594fSAndroid Build Coastguard Worker }
1989*795d594fSAndroid Build Coastguard Worker }
1990*795d594fSAndroid Build Coastguard Worker if (IsGCDisabledForShutdown()) {
1991*795d594fSAndroid Build Coastguard Worker // We're just shutting down and GCs don't work anymore. Try a different allocator.
1992*795d594fSAndroid Build Coastguard Worker mirror::Object* ptr = TryToAllocate<true, false>(self,
1993*795d594fSAndroid Build Coastguard Worker kAllocatorTypeNonMoving,
1994*795d594fSAndroid Build Coastguard Worker alloc_size,
1995*795d594fSAndroid Build Coastguard Worker bytes_allocated,
1996*795d594fSAndroid Build Coastguard Worker usable_size,
1997*795d594fSAndroid Build Coastguard Worker bytes_tl_bulk_allocated);
1998*795d594fSAndroid Build Coastguard Worker if (ptr != nullptr) {
1999*795d594fSAndroid Build Coastguard Worker return ptr;
2000*795d594fSAndroid Build Coastguard Worker }
2001*795d594fSAndroid Build Coastguard Worker }
2002*795d594fSAndroid Build Coastguard Worker
2003*795d594fSAndroid Build Coastguard Worker int64_t bytes_freed_before = GetBytesFreedEver();
2004*795d594fSAndroid Build Coastguard Worker auto have_reclaimed_enough = [&]() {
2005*795d594fSAndroid Build Coastguard Worker size_t curr_bytes_allocated = GetBytesAllocated();
2006*795d594fSAndroid Build Coastguard Worker size_t free_heap = UnsignedDifference(growth_limit_, curr_bytes_allocated);
2007*795d594fSAndroid Build Coastguard Worker int64_t newly_freed = GetBytesFreedEver() - bytes_freed_before;
2008*795d594fSAndroid Build Coastguard Worker double free_heap_ratio = static_cast<double>(free_heap) / growth_limit_;
2009*795d594fSAndroid Build Coastguard Worker double newly_freed_ratio = static_cast<double>(newly_freed) / growth_limit_;
2010*795d594fSAndroid Build Coastguard Worker return free_heap_ratio >= kMinFreeHeapAfterGcForAlloc ||
2011*795d594fSAndroid Build Coastguard Worker newly_freed_ratio >= kMinFreedHeapAfterGcForAlloc;
2012*795d594fSAndroid Build Coastguard Worker };
2013*795d594fSAndroid Build Coastguard Worker // We perform one GC as per the next_gc_type_ (chosen in GrowForUtilization),
2014*795d594fSAndroid Build Coastguard Worker // if it's not already tried. If that doesn't succeed then go for the most
2015*795d594fSAndroid Build Coastguard Worker // exhaustive option. Perform a full-heap collection including clearing
2016*795d594fSAndroid Build Coastguard Worker // SoftReferences. In case of ConcurrentCopying, it will also ensure that
2017*795d594fSAndroid Build Coastguard Worker // all regions are evacuated. If allocation doesn't succeed even after that
2018*795d594fSAndroid Build Coastguard Worker // then there is no hope, so we throw OOME.
2019*795d594fSAndroid Build Coastguard Worker collector::GcType tried_type = next_gc_type_;
2020*795d594fSAndroid Build Coastguard Worker if (last_gc < tried_type) {
2021*795d594fSAndroid Build Coastguard Worker VLOG(gc) << "Starting a blocking GC " << kGcCauseForAlloc;
2022*795d594fSAndroid Build Coastguard Worker PERFORM_SUSPENDING_OPERATION(
2023*795d594fSAndroid Build Coastguard Worker CollectGarbageInternal(tried_type, kGcCauseForAlloc, false, starting_gc_num + 1));
2024*795d594fSAndroid Build Coastguard Worker
2025*795d594fSAndroid Build Coastguard Worker if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
2026*795d594fSAndroid Build Coastguard Worker (!instrumented && EntrypointsInstrumented())) {
2027*795d594fSAndroid Build Coastguard Worker return nullptr;
2028*795d594fSAndroid Build Coastguard Worker }
2029*795d594fSAndroid Build Coastguard Worker // Check this even if we didn't actually run a GC; if we didn't someone else probably did.
2030*795d594fSAndroid Build Coastguard Worker if (have_reclaimed_enough()) {
2031*795d594fSAndroid Build Coastguard Worker mirror::Object* ptr = TryToAllocate<true, false>(self, allocator,
2032*795d594fSAndroid Build Coastguard Worker alloc_size, bytes_allocated,
2033*795d594fSAndroid Build Coastguard Worker usable_size, bytes_tl_bulk_allocated);
2034*795d594fSAndroid Build Coastguard Worker if (ptr != nullptr) {
2035*795d594fSAndroid Build Coastguard Worker return ptr;
2036*795d594fSAndroid Build Coastguard Worker }
2037*795d594fSAndroid Build Coastguard Worker }
2038*795d594fSAndroid Build Coastguard Worker }
2039*795d594fSAndroid Build Coastguard Worker // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
2040*795d594fSAndroid Build Coastguard Worker // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
2041*795d594fSAndroid Build Coastguard Worker // VM spec requires that all SoftReferences have been collected and cleared before throwing
2042*795d594fSAndroid Build Coastguard Worker // OOME.
2043*795d594fSAndroid Build Coastguard Worker VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
2044*795d594fSAndroid Build Coastguard Worker << " allocation";
2045*795d594fSAndroid Build Coastguard Worker // TODO: Run finalization, but this may cause more allocations to occur.
2046*795d594fSAndroid Build Coastguard Worker // We don't need a WaitForGcToComplete here either.
2047*795d594fSAndroid Build Coastguard Worker // TODO: Should check whether another thread already just ran a GC with soft
2048*795d594fSAndroid Build Coastguard Worker // references.
2049*795d594fSAndroid Build Coastguard Worker
2050*795d594fSAndroid Build Coastguard Worker DCHECK(!gc_plan_.empty());
2051*795d594fSAndroid Build Coastguard Worker
2052*795d594fSAndroid Build Coastguard Worker int64_t min_freed_to_continue =
2053*795d594fSAndroid Build Coastguard Worker static_cast<int64_t>(kMinFreedHeapAfterGcForAlloc * growth_limit_ + alloc_size);
2054*795d594fSAndroid Build Coastguard Worker // Repeatedly collect the entire heap until either
2055*795d594fSAndroid Build Coastguard Worker // (a) this was insufficiently productive at reclaiming memory and we should give upt to avoid
2056*795d594fSAndroid Build Coastguard Worker // "GC thrashing", or
2057*795d594fSAndroid Build Coastguard Worker // (b) GC was sufficiently productive (reclaimed min_freed_to_continue bytes) AND allowed us to
2058*795d594fSAndroid Build Coastguard Worker // satisfy the allocation request.
2059*795d594fSAndroid Build Coastguard Worker bool gc_ran;
2060*795d594fSAndroid Build Coastguard Worker int gc_attempts = 0;
2061*795d594fSAndroid Build Coastguard Worker // A requested GC can fail to run because either someone else beat us to it, or because we can't
2062*795d594fSAndroid Build Coastguard Worker // run a GC in this state. In the latter case, we return quickly. Just try a small number of
2063*795d594fSAndroid Build Coastguard Worker // times.
2064*795d594fSAndroid Build Coastguard Worker static constexpr int kMaxGcAttempts = 5;
2065*795d594fSAndroid Build Coastguard Worker do {
2066*795d594fSAndroid Build Coastguard Worker bytes_freed_before = GetBytesFreedEver();
2067*795d594fSAndroid Build Coastguard Worker pre_oome_gc_count_.fetch_add(1, std::memory_order_relaxed);
2068*795d594fSAndroid Build Coastguard Worker // TODO(b/353333767): Do this only if nobody else beats us to it. If we're having trouble
2069*795d594fSAndroid Build Coastguard Worker // allocating, probably other threads are in the same boat.
2070*795d594fSAndroid Build Coastguard Worker starting_gc_num = GetCurrentGcNum();
2071*795d594fSAndroid Build Coastguard Worker gc_ran = PERFORM_SUSPENDING_OPERATION(
2072*795d594fSAndroid Build Coastguard Worker CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true, starting_gc_num + 1) !=
2073*795d594fSAndroid Build Coastguard Worker collector::kGcTypeNone);
2074*795d594fSAndroid Build Coastguard Worker ++gc_attempts;
2075*795d594fSAndroid Build Coastguard Worker if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
2076*795d594fSAndroid Build Coastguard Worker (!instrumented && EntrypointsInstrumented())) {
2077*795d594fSAndroid Build Coastguard Worker return nullptr;
2078*795d594fSAndroid Build Coastguard Worker }
2079*795d594fSAndroid Build Coastguard Worker bool ran_homogeneous_space_compaction = false;
2080*795d594fSAndroid Build Coastguard Worker bool immediately_reclaimed_enough = have_reclaimed_enough();
2081*795d594fSAndroid Build Coastguard Worker if (!immediately_reclaimed_enough) {
2082*795d594fSAndroid Build Coastguard Worker const uint64_t current_time = NanoTime();
2083*795d594fSAndroid Build Coastguard Worker if (allocator == kAllocatorTypeRosAlloc || allocator == kAllocatorTypeDlMalloc) {
2084*795d594fSAndroid Build Coastguard Worker if (use_homogeneous_space_compaction_for_oom_ &&
2085*795d594fSAndroid Build Coastguard Worker current_time - last_time_homogeneous_space_compaction_by_oom_ >
2086*795d594fSAndroid Build Coastguard Worker min_interval_homogeneous_space_compaction_by_oom_) {
2087*795d594fSAndroid Build Coastguard Worker last_time_homogeneous_space_compaction_by_oom_ = current_time;
2088*795d594fSAndroid Build Coastguard Worker ran_homogeneous_space_compaction =
2089*795d594fSAndroid Build Coastguard Worker (PERFORM_SUSPENDING_OPERATION(PerformHomogeneousSpaceCompact()) ==
2090*795d594fSAndroid Build Coastguard Worker HomogeneousSpaceCompactResult::kSuccess);
2091*795d594fSAndroid Build Coastguard Worker // Thread suspension could have occurred.
2092*795d594fSAndroid Build Coastguard Worker if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
2093*795d594fSAndroid Build Coastguard Worker (!instrumented && EntrypointsInstrumented())) {
2094*795d594fSAndroid Build Coastguard Worker return nullptr;
2095*795d594fSAndroid Build Coastguard Worker }
2096*795d594fSAndroid Build Coastguard Worker // Always print that we ran homogeneous space compation since this can cause jank.
2097*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Ran heap homogeneous space compaction, "
2098*795d594fSAndroid Build Coastguard Worker << " requested defragmentation "
2099*795d594fSAndroid Build Coastguard Worker << count_requested_homogeneous_space_compaction_.load()
2100*795d594fSAndroid Build Coastguard Worker << " performed defragmentation "
2101*795d594fSAndroid Build Coastguard Worker << count_performed_homogeneous_space_compaction_.load()
2102*795d594fSAndroid Build Coastguard Worker << " ignored homogeneous space compaction "
2103*795d594fSAndroid Build Coastguard Worker << count_ignored_homogeneous_space_compaction_.load()
2104*795d594fSAndroid Build Coastguard Worker << " delayed count = "
2105*795d594fSAndroid Build Coastguard Worker << count_delayed_oom_.load();
2106*795d594fSAndroid Build Coastguard Worker }
2107*795d594fSAndroid Build Coastguard Worker }
2108*795d594fSAndroid Build Coastguard Worker }
2109*795d594fSAndroid Build Coastguard Worker if (immediately_reclaimed_enough ||
2110*795d594fSAndroid Build Coastguard Worker (ran_homogeneous_space_compaction && have_reclaimed_enough())) {
2111*795d594fSAndroid Build Coastguard Worker mirror::Object* ptr = TryToAllocate<true, true>(
2112*795d594fSAndroid Build Coastguard Worker self, allocator, alloc_size, bytes_allocated, usable_size, bytes_tl_bulk_allocated);
2113*795d594fSAndroid Build Coastguard Worker if (ptr != nullptr) {
2114*795d594fSAndroid Build Coastguard Worker if (ran_homogeneous_space_compaction) {
2115*795d594fSAndroid Build Coastguard Worker count_delayed_oom_++;
2116*795d594fSAndroid Build Coastguard Worker }
2117*795d594fSAndroid Build Coastguard Worker return ptr;
2118*795d594fSAndroid Build Coastguard Worker }
2119*795d594fSAndroid Build Coastguard Worker }
2120*795d594fSAndroid Build Coastguard Worker // This loops only if we reclaimed plenty of memory, but presumably some other thread beat us
2121*795d594fSAndroid Build Coastguard Worker // to allocating it. In the very unlikely case that we're running into a serious fragmentation
2122*795d594fSAndroid Build Coastguard Worker // issue, and there is no other thread allocating, GCs will quickly become unsuccessful, and we
2123*795d594fSAndroid Build Coastguard Worker // will stop then. If another thread is allocating aggressively, this may go on for a while,
2124*795d594fSAndroid Build Coastguard Worker // but we are still making progress somewhere.
2125*795d594fSAndroid Build Coastguard Worker } while ((!gc_ran && gc_attempts < kMaxGcAttempts) ||
2126*795d594fSAndroid Build Coastguard Worker GetBytesFreedEver() - bytes_freed_before > min_freed_to_continue);
2127*795d594fSAndroid Build Coastguard Worker #undef PERFORM_SUSPENDING_OPERATION
2128*795d594fSAndroid Build Coastguard Worker // Throw an OOM error.
2129*795d594fSAndroid Build Coastguard Worker {
2130*795d594fSAndroid Build Coastguard Worker ScopedAllowThreadSuspension ats;
2131*795d594fSAndroid Build Coastguard Worker ThrowOutOfMemoryError(self, alloc_size, allocator);
2132*795d594fSAndroid Build Coastguard Worker }
2133*795d594fSAndroid Build Coastguard Worker return nullptr;
2134*795d594fSAndroid Build Coastguard Worker }
2135*795d594fSAndroid Build Coastguard Worker
SetTargetHeapUtilization(float target)2136*795d594fSAndroid Build Coastguard Worker void Heap::SetTargetHeapUtilization(float target) {
2137*795d594fSAndroid Build Coastguard Worker DCHECK_GT(target, 0.1f); // asserted in Java code
2138*795d594fSAndroid Build Coastguard Worker DCHECK_LT(target, 1.0f);
2139*795d594fSAndroid Build Coastguard Worker target_utilization_ = target;
2140*795d594fSAndroid Build Coastguard Worker }
2141*795d594fSAndroid Build Coastguard Worker
GetObjectsAllocated() const2142*795d594fSAndroid Build Coastguard Worker size_t Heap::GetObjectsAllocated() const {
2143*795d594fSAndroid Build Coastguard Worker Thread* const self = Thread::Current();
2144*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc(self, ThreadState::kWaitingForGetObjectsAllocated);
2145*795d594fSAndroid Build Coastguard Worker // Prevent GC running during GetObjectsAllocated since we may get a checkpoint request that tells
2146*795d594fSAndroid Build Coastguard Worker // us to suspend while we are doing SuspendAll. b/35232978
2147*795d594fSAndroid Build Coastguard Worker gc::ScopedGCCriticalSection gcs(Thread::Current(),
2148*795d594fSAndroid Build Coastguard Worker gc::kGcCauseGetObjectsAllocated,
2149*795d594fSAndroid Build Coastguard Worker gc::kCollectorTypeGetObjectsAllocated);
2150*795d594fSAndroid Build Coastguard Worker // Need SuspendAll here to prevent lock violation if RosAlloc does it during InspectAll.
2151*795d594fSAndroid Build Coastguard Worker ScopedSuspendAll ssa(__FUNCTION__);
2152*795d594fSAndroid Build Coastguard Worker ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2153*795d594fSAndroid Build Coastguard Worker size_t total = 0;
2154*795d594fSAndroid Build Coastguard Worker for (space::AllocSpace* space : alloc_spaces_) {
2155*795d594fSAndroid Build Coastguard Worker total += space->GetObjectsAllocated();
2156*795d594fSAndroid Build Coastguard Worker }
2157*795d594fSAndroid Build Coastguard Worker return total;
2158*795d594fSAndroid Build Coastguard Worker }
2159*795d594fSAndroid Build Coastguard Worker
GetBytesAllocatedEver() const2160*795d594fSAndroid Build Coastguard Worker uint64_t Heap::GetBytesAllocatedEver() const {
2161*795d594fSAndroid Build Coastguard Worker // Force the returned value to be monotonically increasing, in the sense that if this is called
2162*795d594fSAndroid Build Coastguard Worker // at A and B, such that A happens-before B, then the call at B returns a value no smaller than
2163*795d594fSAndroid Build Coastguard Worker // that at A. This is not otherwise guaranteed, since num_bytes_allocated_ is decremented first,
2164*795d594fSAndroid Build Coastguard Worker // and total_bytes_freed_ever_ is incremented later.
2165*795d594fSAndroid Build Coastguard Worker static std::atomic<uint64_t> max_bytes_so_far(0);
2166*795d594fSAndroid Build Coastguard Worker uint64_t so_far = max_bytes_so_far.load(std::memory_order_relaxed);
2167*795d594fSAndroid Build Coastguard Worker uint64_t current_bytes = GetBytesFreedEver(std::memory_order_acquire) + GetBytesAllocated();
2168*795d594fSAndroid Build Coastguard Worker DCHECK(current_bytes < (static_cast<uint64_t>(1) << 63)); // result is "positive".
2169*795d594fSAndroid Build Coastguard Worker do {
2170*795d594fSAndroid Build Coastguard Worker if (current_bytes <= so_far) {
2171*795d594fSAndroid Build Coastguard Worker return so_far;
2172*795d594fSAndroid Build Coastguard Worker }
2173*795d594fSAndroid Build Coastguard Worker } while (!max_bytes_so_far.compare_exchange_weak(so_far /* updated */,
2174*795d594fSAndroid Build Coastguard Worker current_bytes, std::memory_order_relaxed));
2175*795d594fSAndroid Build Coastguard Worker return current_bytes;
2176*795d594fSAndroid Build Coastguard Worker }
2177*795d594fSAndroid Build Coastguard Worker
2178*795d594fSAndroid Build Coastguard Worker // Check whether the given object is an instance of the given class.
MatchesClass(mirror::Object * obj,Handle<mirror::Class> h_class,bool use_is_assignable_from)2179*795d594fSAndroid Build Coastguard Worker static bool MatchesClass(mirror::Object* obj,
2180*795d594fSAndroid Build Coastguard Worker Handle<mirror::Class> h_class,
2181*795d594fSAndroid Build Coastguard Worker bool use_is_assignable_from) REQUIRES_SHARED(Locks::mutator_lock_) {
2182*795d594fSAndroid Build Coastguard Worker mirror::Class* instance_class = obj->GetClass();
2183*795d594fSAndroid Build Coastguard Worker CHECK(instance_class != nullptr);
2184*795d594fSAndroid Build Coastguard Worker ObjPtr<mirror::Class> klass = h_class.Get();
2185*795d594fSAndroid Build Coastguard Worker if (use_is_assignable_from) {
2186*795d594fSAndroid Build Coastguard Worker return klass != nullptr && klass->IsAssignableFrom(instance_class);
2187*795d594fSAndroid Build Coastguard Worker }
2188*795d594fSAndroid Build Coastguard Worker return instance_class == klass;
2189*795d594fSAndroid Build Coastguard Worker }
2190*795d594fSAndroid Build Coastguard Worker
CountInstances(const std::vector<Handle<mirror::Class>> & classes,bool use_is_assignable_from,uint64_t * counts)2191*795d594fSAndroid Build Coastguard Worker void Heap::CountInstances(const std::vector<Handle<mirror::Class>>& classes,
2192*795d594fSAndroid Build Coastguard Worker bool use_is_assignable_from,
2193*795d594fSAndroid Build Coastguard Worker uint64_t* counts) {
2194*795d594fSAndroid Build Coastguard Worker auto instance_counter = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2195*795d594fSAndroid Build Coastguard Worker for (size_t i = 0; i < classes.size(); ++i) {
2196*795d594fSAndroid Build Coastguard Worker if (MatchesClass(obj, classes[i], use_is_assignable_from)) {
2197*795d594fSAndroid Build Coastguard Worker ++counts[i];
2198*795d594fSAndroid Build Coastguard Worker }
2199*795d594fSAndroid Build Coastguard Worker }
2200*795d594fSAndroid Build Coastguard Worker };
2201*795d594fSAndroid Build Coastguard Worker VisitObjects(instance_counter);
2202*795d594fSAndroid Build Coastguard Worker }
2203*795d594fSAndroid Build Coastguard Worker
CollectGarbage(bool clear_soft_references,GcCause cause)2204*795d594fSAndroid Build Coastguard Worker void Heap::CollectGarbage(bool clear_soft_references, GcCause cause) {
2205*795d594fSAndroid Build Coastguard Worker // Even if we waited for a GC we still need to do another GC since weaks allocated during the
2206*795d594fSAndroid Build Coastguard Worker // last GC will not have necessarily been cleared.
2207*795d594fSAndroid Build Coastguard Worker CollectGarbageInternal(gc_plan_.back(), cause, clear_soft_references, GC_NUM_ANY);
2208*795d594fSAndroid Build Coastguard Worker }
2209*795d594fSAndroid Build Coastguard Worker
SupportHomogeneousSpaceCompactAndCollectorTransitions() const2210*795d594fSAndroid Build Coastguard Worker bool Heap::SupportHomogeneousSpaceCompactAndCollectorTransitions() const {
2211*795d594fSAndroid Build Coastguard Worker return main_space_backup_.get() != nullptr && main_space_ != nullptr &&
2212*795d594fSAndroid Build Coastguard Worker foreground_collector_type_ == kCollectorTypeCMS;
2213*795d594fSAndroid Build Coastguard Worker }
2214*795d594fSAndroid Build Coastguard Worker
PerformHomogeneousSpaceCompact()2215*795d594fSAndroid Build Coastguard Worker HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
2216*795d594fSAndroid Build Coastguard Worker Thread* self = Thread::Current();
2217*795d594fSAndroid Build Coastguard Worker // Inc requested homogeneous space compaction.
2218*795d594fSAndroid Build Coastguard Worker count_requested_homogeneous_space_compaction_++;
2219*795d594fSAndroid Build Coastguard Worker // Store performed homogeneous space compaction at a new request arrival.
2220*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc(self, ThreadState::kWaitingPerformingGc);
2221*795d594fSAndroid Build Coastguard Worker Locks::mutator_lock_->AssertNotHeld(self);
2222*795d594fSAndroid Build Coastguard Worker {
2223*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc2(self, ThreadState::kWaitingForGcToComplete);
2224*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *gc_complete_lock_);
2225*795d594fSAndroid Build Coastguard Worker // Ensure there is only one GC at a time.
2226*795d594fSAndroid Build Coastguard Worker WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
2227*795d594fSAndroid Build Coastguard Worker // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable
2228*795d594fSAndroid Build Coastguard Worker // count is non zero.
2229*795d594fSAndroid Build Coastguard Worker // If the collector type changed to something which doesn't benefit from homogeneous space
2230*795d594fSAndroid Build Coastguard Worker // compaction, exit.
2231*795d594fSAndroid Build Coastguard Worker if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
2232*795d594fSAndroid Build Coastguard Worker !main_space_->CanMoveObjects()) {
2233*795d594fSAndroid Build Coastguard Worker return kErrorReject;
2234*795d594fSAndroid Build Coastguard Worker }
2235*795d594fSAndroid Build Coastguard Worker if (!SupportHomogeneousSpaceCompactAndCollectorTransitions()) {
2236*795d594fSAndroid Build Coastguard Worker return kErrorUnsupported;
2237*795d594fSAndroid Build Coastguard Worker }
2238*795d594fSAndroid Build Coastguard Worker collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
2239*795d594fSAndroid Build Coastguard Worker }
2240*795d594fSAndroid Build Coastguard Worker if (Runtime::Current()->IsShuttingDown(self)) {
2241*795d594fSAndroid Build Coastguard Worker // Don't allow heap transitions to happen if the runtime is shutting down since these can
2242*795d594fSAndroid Build Coastguard Worker // cause objects to get finalized.
2243*795d594fSAndroid Build Coastguard Worker FinishGC(self, collector::kGcTypeNone);
2244*795d594fSAndroid Build Coastguard Worker return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
2245*795d594fSAndroid Build Coastguard Worker }
2246*795d594fSAndroid Build Coastguard Worker collector::GarbageCollector* collector;
2247*795d594fSAndroid Build Coastguard Worker {
2248*795d594fSAndroid Build Coastguard Worker ScopedSuspendAll ssa(__FUNCTION__);
2249*795d594fSAndroid Build Coastguard Worker uint64_t start_time = NanoTime();
2250*795d594fSAndroid Build Coastguard Worker // Launch compaction.
2251*795d594fSAndroid Build Coastguard Worker space::MallocSpace* to_space = main_space_backup_.release();
2252*795d594fSAndroid Build Coastguard Worker space::MallocSpace* from_space = main_space_;
2253*795d594fSAndroid Build Coastguard Worker to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2254*795d594fSAndroid Build Coastguard Worker const uint64_t space_size_before_compaction = from_space->Size();
2255*795d594fSAndroid Build Coastguard Worker AddSpace(to_space);
2256*795d594fSAndroid Build Coastguard Worker // Make sure that we will have enough room to copy.
2257*795d594fSAndroid Build Coastguard Worker CHECK_GE(to_space->GetFootprintLimit(), from_space->GetFootprintLimit());
2258*795d594fSAndroid Build Coastguard Worker collector = Compact(to_space, from_space, kGcCauseHomogeneousSpaceCompact);
2259*795d594fSAndroid Build Coastguard Worker const uint64_t space_size_after_compaction = to_space->Size();
2260*795d594fSAndroid Build Coastguard Worker main_space_ = to_space;
2261*795d594fSAndroid Build Coastguard Worker main_space_backup_.reset(from_space);
2262*795d594fSAndroid Build Coastguard Worker RemoveSpace(from_space);
2263*795d594fSAndroid Build Coastguard Worker SetSpaceAsDefault(main_space_); // Set as default to reset the proper dlmalloc space.
2264*795d594fSAndroid Build Coastguard Worker // Update performed homogeneous space compaction count.
2265*795d594fSAndroid Build Coastguard Worker count_performed_homogeneous_space_compaction_++;
2266*795d594fSAndroid Build Coastguard Worker // Print statics log and resume all threads.
2267*795d594fSAndroid Build Coastguard Worker uint64_t duration = NanoTime() - start_time;
2268*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
2269*795d594fSAndroid Build Coastguard Worker << PrettySize(space_size_before_compaction) << " -> "
2270*795d594fSAndroid Build Coastguard Worker << PrettySize(space_size_after_compaction) << " compact-ratio: "
2271*795d594fSAndroid Build Coastguard Worker << std::fixed << static_cast<double>(space_size_after_compaction) /
2272*795d594fSAndroid Build Coastguard Worker static_cast<double>(space_size_before_compaction);
2273*795d594fSAndroid Build Coastguard Worker }
2274*795d594fSAndroid Build Coastguard Worker // Finish GC.
2275*795d594fSAndroid Build Coastguard Worker // Get the references we need to enqueue.
2276*795d594fSAndroid Build Coastguard Worker SelfDeletingTask* clear = reference_processor_->CollectClearedReferences(self);
2277*795d594fSAndroid Build Coastguard Worker GrowForUtilization(semi_space_collector_);
2278*795d594fSAndroid Build Coastguard Worker LogGC(kGcCauseHomogeneousSpaceCompact, collector);
2279*795d594fSAndroid Build Coastguard Worker FinishGC(self, collector::kGcTypeFull);
2280*795d594fSAndroid Build Coastguard Worker // Enqueue any references after losing the GC locks.
2281*795d594fSAndroid Build Coastguard Worker clear->Run(self);
2282*795d594fSAndroid Build Coastguard Worker clear->Finalize();
2283*795d594fSAndroid Build Coastguard Worker {
2284*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(self);
2285*795d594fSAndroid Build Coastguard Worker soa.Vm()->UnloadNativeLibraries();
2286*795d594fSAndroid Build Coastguard Worker }
2287*795d594fSAndroid Build Coastguard Worker return HomogeneousSpaceCompactResult::kSuccess;
2288*795d594fSAndroid Build Coastguard Worker }
2289*795d594fSAndroid Build Coastguard Worker
SetDefaultConcurrentStartBytes()2290*795d594fSAndroid Build Coastguard Worker void Heap::SetDefaultConcurrentStartBytes() {
2291*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *gc_complete_lock_);
2292*795d594fSAndroid Build Coastguard Worker if (collector_type_running_ != kCollectorTypeNone) {
2293*795d594fSAndroid Build Coastguard Worker // If a collector is already running, just let it set concurrent_start_bytes_ .
2294*795d594fSAndroid Build Coastguard Worker return;
2295*795d594fSAndroid Build Coastguard Worker }
2296*795d594fSAndroid Build Coastguard Worker SetDefaultConcurrentStartBytesLocked();
2297*795d594fSAndroid Build Coastguard Worker }
2298*795d594fSAndroid Build Coastguard Worker
SetDefaultConcurrentStartBytesLocked()2299*795d594fSAndroid Build Coastguard Worker void Heap::SetDefaultConcurrentStartBytesLocked() {
2300*795d594fSAndroid Build Coastguard Worker if (IsGcConcurrent()) {
2301*795d594fSAndroid Build Coastguard Worker size_t target_footprint = target_footprint_.load(std::memory_order_relaxed);
2302*795d594fSAndroid Build Coastguard Worker size_t reserve_bytes = target_footprint / 4;
2303*795d594fSAndroid Build Coastguard Worker reserve_bytes = std::min(reserve_bytes, kMaxConcurrentRemainingBytes);
2304*795d594fSAndroid Build Coastguard Worker reserve_bytes = std::max(reserve_bytes, kMinConcurrentRemainingBytes);
2305*795d594fSAndroid Build Coastguard Worker concurrent_start_bytes_ = UnsignedDifference(target_footprint, reserve_bytes);
2306*795d594fSAndroid Build Coastguard Worker } else {
2307*795d594fSAndroid Build Coastguard Worker concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2308*795d594fSAndroid Build Coastguard Worker }
2309*795d594fSAndroid Build Coastguard Worker }
2310*795d594fSAndroid Build Coastguard Worker
ChangeCollector(CollectorType collector_type)2311*795d594fSAndroid Build Coastguard Worker void Heap::ChangeCollector(CollectorType collector_type) {
2312*795d594fSAndroid Build Coastguard Worker // TODO: Only do this with all mutators suspended to avoid races.
2313*795d594fSAndroid Build Coastguard Worker if (collector_type != collector_type_) {
2314*795d594fSAndroid Build Coastguard Worker collector_type_ = collector_type;
2315*795d594fSAndroid Build Coastguard Worker gc_plan_.clear();
2316*795d594fSAndroid Build Coastguard Worker switch (collector_type_) {
2317*795d594fSAndroid Build Coastguard Worker case kCollectorTypeCC: {
2318*795d594fSAndroid Build Coastguard Worker if (use_generational_cc_) {
2319*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypeSticky);
2320*795d594fSAndroid Build Coastguard Worker }
2321*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypeFull);
2322*795d594fSAndroid Build Coastguard Worker if (use_tlab_) {
2323*795d594fSAndroid Build Coastguard Worker ChangeAllocator(kAllocatorTypeRegionTLAB);
2324*795d594fSAndroid Build Coastguard Worker } else {
2325*795d594fSAndroid Build Coastguard Worker ChangeAllocator(kAllocatorTypeRegion);
2326*795d594fSAndroid Build Coastguard Worker }
2327*795d594fSAndroid Build Coastguard Worker break;
2328*795d594fSAndroid Build Coastguard Worker }
2329*795d594fSAndroid Build Coastguard Worker case kCollectorTypeCMC: {
2330*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypeFull);
2331*795d594fSAndroid Build Coastguard Worker if (use_tlab_) {
2332*795d594fSAndroid Build Coastguard Worker ChangeAllocator(kAllocatorTypeTLAB);
2333*795d594fSAndroid Build Coastguard Worker } else {
2334*795d594fSAndroid Build Coastguard Worker ChangeAllocator(kAllocatorTypeBumpPointer);
2335*795d594fSAndroid Build Coastguard Worker }
2336*795d594fSAndroid Build Coastguard Worker break;
2337*795d594fSAndroid Build Coastguard Worker }
2338*795d594fSAndroid Build Coastguard Worker case kCollectorTypeSS: {
2339*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypeFull);
2340*795d594fSAndroid Build Coastguard Worker if (use_tlab_) {
2341*795d594fSAndroid Build Coastguard Worker ChangeAllocator(kAllocatorTypeTLAB);
2342*795d594fSAndroid Build Coastguard Worker } else {
2343*795d594fSAndroid Build Coastguard Worker ChangeAllocator(kAllocatorTypeBumpPointer);
2344*795d594fSAndroid Build Coastguard Worker }
2345*795d594fSAndroid Build Coastguard Worker break;
2346*795d594fSAndroid Build Coastguard Worker }
2347*795d594fSAndroid Build Coastguard Worker case kCollectorTypeMS: {
2348*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypeSticky);
2349*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypePartial);
2350*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypeFull);
2351*795d594fSAndroid Build Coastguard Worker ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
2352*795d594fSAndroid Build Coastguard Worker break;
2353*795d594fSAndroid Build Coastguard Worker }
2354*795d594fSAndroid Build Coastguard Worker case kCollectorTypeCMS: {
2355*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypeSticky);
2356*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypePartial);
2357*795d594fSAndroid Build Coastguard Worker gc_plan_.push_back(collector::kGcTypeFull);
2358*795d594fSAndroid Build Coastguard Worker ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
2359*795d594fSAndroid Build Coastguard Worker break;
2360*795d594fSAndroid Build Coastguard Worker }
2361*795d594fSAndroid Build Coastguard Worker default: {
2362*795d594fSAndroid Build Coastguard Worker UNIMPLEMENTED(FATAL);
2363*795d594fSAndroid Build Coastguard Worker UNREACHABLE();
2364*795d594fSAndroid Build Coastguard Worker }
2365*795d594fSAndroid Build Coastguard Worker }
2366*795d594fSAndroid Build Coastguard Worker SetDefaultConcurrentStartBytesLocked();
2367*795d594fSAndroid Build Coastguard Worker }
2368*795d594fSAndroid Build Coastguard Worker }
2369*795d594fSAndroid Build Coastguard Worker
2370*795d594fSAndroid Build Coastguard Worker // Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
2371*795d594fSAndroid Build Coastguard Worker class ZygoteCompactingCollector final : public collector::SemiSpace {
2372*795d594fSAndroid Build Coastguard Worker public:
ZygoteCompactingCollector(gc::Heap * heap,bool is_running_on_memory_tool)2373*795d594fSAndroid Build Coastguard Worker ZygoteCompactingCollector(gc::Heap* heap, bool is_running_on_memory_tool)
2374*795d594fSAndroid Build Coastguard Worker : SemiSpace(heap, "zygote collector"),
2375*795d594fSAndroid Build Coastguard Worker bin_live_bitmap_(nullptr),
2376*795d594fSAndroid Build Coastguard Worker bin_mark_bitmap_(nullptr),
2377*795d594fSAndroid Build Coastguard Worker is_running_on_memory_tool_(is_running_on_memory_tool) {}
2378*795d594fSAndroid Build Coastguard Worker
BuildBins(space::ContinuousSpace * space)2379*795d594fSAndroid Build Coastguard Worker void BuildBins(space::ContinuousSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
2380*795d594fSAndroid Build Coastguard Worker bin_live_bitmap_ = space->GetLiveBitmap();
2381*795d594fSAndroid Build Coastguard Worker bin_mark_bitmap_ = space->GetMarkBitmap();
2382*795d594fSAndroid Build Coastguard Worker uintptr_t prev = reinterpret_cast<uintptr_t>(space->Begin());
2383*795d594fSAndroid Build Coastguard Worker WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2384*795d594fSAndroid Build Coastguard Worker // Note: This requires traversing the space in increasing order of object addresses.
2385*795d594fSAndroid Build Coastguard Worker auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2386*795d594fSAndroid Build Coastguard Worker uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
2387*795d594fSAndroid Build Coastguard Worker size_t bin_size = object_addr - prev;
2388*795d594fSAndroid Build Coastguard Worker // Add the bin consisting of the end of the previous object to the start of the current object.
2389*795d594fSAndroid Build Coastguard Worker AddBin(bin_size, prev);
2390*795d594fSAndroid Build Coastguard Worker prev = object_addr + RoundUp(obj->SizeOf<kDefaultVerifyFlags>(), kObjectAlignment);
2391*795d594fSAndroid Build Coastguard Worker };
2392*795d594fSAndroid Build Coastguard Worker bin_live_bitmap_->Walk(visitor);
2393*795d594fSAndroid Build Coastguard Worker // Add the last bin which spans after the last object to the end of the space.
2394*795d594fSAndroid Build Coastguard Worker AddBin(reinterpret_cast<uintptr_t>(space->End()) - prev, prev);
2395*795d594fSAndroid Build Coastguard Worker }
2396*795d594fSAndroid Build Coastguard Worker
2397*795d594fSAndroid Build Coastguard Worker private:
2398*795d594fSAndroid Build Coastguard Worker // Maps from bin sizes to locations.
2399*795d594fSAndroid Build Coastguard Worker std::multimap<size_t, uintptr_t> bins_;
2400*795d594fSAndroid Build Coastguard Worker // Live bitmap of the space which contains the bins.
2401*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
2402*795d594fSAndroid Build Coastguard Worker // Mark bitmap of the space which contains the bins.
2403*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
2404*795d594fSAndroid Build Coastguard Worker const bool is_running_on_memory_tool_;
2405*795d594fSAndroid Build Coastguard Worker
AddBin(size_t size,uintptr_t position)2406*795d594fSAndroid Build Coastguard Worker void AddBin(size_t size, uintptr_t position) {
2407*795d594fSAndroid Build Coastguard Worker if (is_running_on_memory_tool_) {
2408*795d594fSAndroid Build Coastguard Worker MEMORY_TOOL_MAKE_DEFINED(reinterpret_cast<void*>(position), size);
2409*795d594fSAndroid Build Coastguard Worker }
2410*795d594fSAndroid Build Coastguard Worker if (size != 0) {
2411*795d594fSAndroid Build Coastguard Worker bins_.insert(std::make_pair(size, position));
2412*795d594fSAndroid Build Coastguard Worker }
2413*795d594fSAndroid Build Coastguard Worker }
2414*795d594fSAndroid Build Coastguard Worker
ShouldSweepSpace(space::ContinuousSpace * space) const2415*795d594fSAndroid Build Coastguard Worker bool ShouldSweepSpace([[maybe_unused]] space::ContinuousSpace* space) const override {
2416*795d594fSAndroid Build Coastguard Worker // Don't sweep any spaces since we probably blasted the internal accounting of the free list
2417*795d594fSAndroid Build Coastguard Worker // allocator.
2418*795d594fSAndroid Build Coastguard Worker return false;
2419*795d594fSAndroid Build Coastguard Worker }
2420*795d594fSAndroid Build Coastguard Worker
MarkNonForwardedObject(mirror::Object * obj)2421*795d594fSAndroid Build Coastguard Worker mirror::Object* MarkNonForwardedObject(mirror::Object* obj) override
2422*795d594fSAndroid Build Coastguard Worker REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
2423*795d594fSAndroid Build Coastguard Worker size_t obj_size = obj->SizeOf<kDefaultVerifyFlags>();
2424*795d594fSAndroid Build Coastguard Worker size_t alloc_size = RoundUp(obj_size, kObjectAlignment);
2425*795d594fSAndroid Build Coastguard Worker mirror::Object* forward_address;
2426*795d594fSAndroid Build Coastguard Worker // Find the smallest bin which we can move obj in.
2427*795d594fSAndroid Build Coastguard Worker auto it = bins_.lower_bound(alloc_size);
2428*795d594fSAndroid Build Coastguard Worker if (it == bins_.end()) {
2429*795d594fSAndroid Build Coastguard Worker // No available space in the bins, place it in the target space instead (grows the zygote
2430*795d594fSAndroid Build Coastguard Worker // space).
2431*795d594fSAndroid Build Coastguard Worker size_t bytes_allocated, unused_bytes_tl_bulk_allocated;
2432*795d594fSAndroid Build Coastguard Worker forward_address = to_space_->Alloc(
2433*795d594fSAndroid Build Coastguard Worker self_, alloc_size, &bytes_allocated, nullptr, &unused_bytes_tl_bulk_allocated);
2434*795d594fSAndroid Build Coastguard Worker if (to_space_live_bitmap_ != nullptr) {
2435*795d594fSAndroid Build Coastguard Worker to_space_live_bitmap_->Set(forward_address);
2436*795d594fSAndroid Build Coastguard Worker } else {
2437*795d594fSAndroid Build Coastguard Worker GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
2438*795d594fSAndroid Build Coastguard Worker GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
2439*795d594fSAndroid Build Coastguard Worker }
2440*795d594fSAndroid Build Coastguard Worker } else {
2441*795d594fSAndroid Build Coastguard Worker size_t size = it->first;
2442*795d594fSAndroid Build Coastguard Worker uintptr_t pos = it->second;
2443*795d594fSAndroid Build Coastguard Worker bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
2444*795d594fSAndroid Build Coastguard Worker forward_address = reinterpret_cast<mirror::Object*>(pos);
2445*795d594fSAndroid Build Coastguard Worker // Set the live and mark bits so that sweeping system weaks works properly.
2446*795d594fSAndroid Build Coastguard Worker bin_live_bitmap_->Set(forward_address);
2447*795d594fSAndroid Build Coastguard Worker bin_mark_bitmap_->Set(forward_address);
2448*795d594fSAndroid Build Coastguard Worker DCHECK_GE(size, alloc_size);
2449*795d594fSAndroid Build Coastguard Worker // Add a new bin with the remaining space.
2450*795d594fSAndroid Build Coastguard Worker AddBin(size - alloc_size, pos + alloc_size);
2451*795d594fSAndroid Build Coastguard Worker }
2452*795d594fSAndroid Build Coastguard Worker // Copy the object over to its new location.
2453*795d594fSAndroid Build Coastguard Worker // Historical note: We did not use `alloc_size` to avoid a Valgrind error.
2454*795d594fSAndroid Build Coastguard Worker memcpy(reinterpret_cast<void*>(forward_address), obj, obj_size);
2455*795d594fSAndroid Build Coastguard Worker if (kUseBakerReadBarrier) {
2456*795d594fSAndroid Build Coastguard Worker obj->AssertReadBarrierState();
2457*795d594fSAndroid Build Coastguard Worker forward_address->AssertReadBarrierState();
2458*795d594fSAndroid Build Coastguard Worker }
2459*795d594fSAndroid Build Coastguard Worker return forward_address;
2460*795d594fSAndroid Build Coastguard Worker }
2461*795d594fSAndroid Build Coastguard Worker };
2462*795d594fSAndroid Build Coastguard Worker
UnBindBitmaps()2463*795d594fSAndroid Build Coastguard Worker void Heap::UnBindBitmaps() {
2464*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
2465*795d594fSAndroid Build Coastguard Worker for (const auto& space : GetContinuousSpaces()) {
2466*795d594fSAndroid Build Coastguard Worker if (space->IsContinuousMemMapAllocSpace()) {
2467*795d594fSAndroid Build Coastguard Worker space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2468*795d594fSAndroid Build Coastguard Worker if (alloc_space->GetLiveBitmap() != nullptr && alloc_space->HasBoundBitmaps()) {
2469*795d594fSAndroid Build Coastguard Worker alloc_space->UnBindBitmaps();
2470*795d594fSAndroid Build Coastguard Worker }
2471*795d594fSAndroid Build Coastguard Worker }
2472*795d594fSAndroid Build Coastguard Worker }
2473*795d594fSAndroid Build Coastguard Worker }
2474*795d594fSAndroid Build Coastguard Worker
IncrementFreedEver()2475*795d594fSAndroid Build Coastguard Worker void Heap::IncrementFreedEver() {
2476*795d594fSAndroid Build Coastguard Worker // Counters are updated only by us, but may be read concurrently.
2477*795d594fSAndroid Build Coastguard Worker // The updates should become visible after the corresponding live object info.
2478*795d594fSAndroid Build Coastguard Worker total_objects_freed_ever_.store(total_objects_freed_ever_.load(std::memory_order_relaxed)
2479*795d594fSAndroid Build Coastguard Worker + GetCurrentGcIteration()->GetFreedObjects()
2480*795d594fSAndroid Build Coastguard Worker + GetCurrentGcIteration()->GetFreedLargeObjects(),
2481*795d594fSAndroid Build Coastguard Worker std::memory_order_release);
2482*795d594fSAndroid Build Coastguard Worker total_bytes_freed_ever_.store(total_bytes_freed_ever_.load(std::memory_order_relaxed)
2483*795d594fSAndroid Build Coastguard Worker + GetCurrentGcIteration()->GetFreedBytes()
2484*795d594fSAndroid Build Coastguard Worker + GetCurrentGcIteration()->GetFreedLargeObjectBytes(),
2485*795d594fSAndroid Build Coastguard Worker std::memory_order_release);
2486*795d594fSAndroid Build Coastguard Worker }
2487*795d594fSAndroid Build Coastguard Worker
2488*795d594fSAndroid Build Coastguard Worker #pragma clang diagnostic push
2489*795d594fSAndroid Build Coastguard Worker #if !ART_USE_FUTEXES
2490*795d594fSAndroid Build Coastguard Worker // Frame gets too large, perhaps due to Bionic pthread_mutex_lock size. We don't care.
2491*795d594fSAndroid Build Coastguard Worker # pragma clang diagnostic ignored "-Wframe-larger-than="
2492*795d594fSAndroid Build Coastguard Worker #endif
2493*795d594fSAndroid Build Coastguard Worker // This has a large frame, but shouldn't be run anywhere near the stack limit.
2494*795d594fSAndroid Build Coastguard Worker // FIXME: BUT it did exceed... http://b/197647048
2495*795d594fSAndroid Build Coastguard Worker # pragma clang diagnostic ignored "-Wframe-larger-than="
PreZygoteFork()2496*795d594fSAndroid Build Coastguard Worker void Heap::PreZygoteFork() {
2497*795d594fSAndroid Build Coastguard Worker if (!HasZygoteSpace()) {
2498*795d594fSAndroid Build Coastguard Worker // We still want to GC in case there is some unreachable non moving objects that could cause a
2499*795d594fSAndroid Build Coastguard Worker // suboptimal bin packing when we compact the zygote space.
2500*795d594fSAndroid Build Coastguard Worker CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false, GC_NUM_ANY);
2501*795d594fSAndroid Build Coastguard Worker // Trim the pages at the end of the non moving space. Trim while not holding zygote lock since
2502*795d594fSAndroid Build Coastguard Worker // the trim process may require locking the mutator lock.
2503*795d594fSAndroid Build Coastguard Worker non_moving_space_->Trim();
2504*795d594fSAndroid Build Coastguard Worker }
2505*795d594fSAndroid Build Coastguard Worker // We need to close userfaultfd fd for app/webview zygotes to avoid getattr
2506*795d594fSAndroid Build Coastguard Worker // (stat) on the fd during fork.
2507*795d594fSAndroid Build Coastguard Worker Thread* self = Thread::Current();
2508*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, zygote_creation_lock_);
2509*795d594fSAndroid Build Coastguard Worker // Try to see if we have any Zygote spaces.
2510*795d594fSAndroid Build Coastguard Worker if (HasZygoteSpace()) {
2511*795d594fSAndroid Build Coastguard Worker return;
2512*795d594fSAndroid Build Coastguard Worker }
2513*795d594fSAndroid Build Coastguard Worker Runtime* runtime = Runtime::Current();
2514*795d594fSAndroid Build Coastguard Worker // Setup linear-alloc pool for post-zygote fork allocations before freezing
2515*795d594fSAndroid Build Coastguard Worker // snapshots of intern-table and class-table.
2516*795d594fSAndroid Build Coastguard Worker runtime->SetupLinearAllocForPostZygoteFork(self);
2517*795d594fSAndroid Build Coastguard Worker runtime->GetInternTable()->AddNewTable();
2518*795d594fSAndroid Build Coastguard Worker runtime->GetClassLinker()->MoveClassTableToPreZygote();
2519*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Starting PreZygoteFork";
2520*795d594fSAndroid Build Coastguard Worker // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
2521*795d594fSAndroid Build Coastguard Worker // there.
2522*795d594fSAndroid Build Coastguard Worker non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2523*795d594fSAndroid Build Coastguard Worker const bool same_space = non_moving_space_ == main_space_;
2524*795d594fSAndroid Build Coastguard Worker if (kCompactZygote) {
2525*795d594fSAndroid Build Coastguard Worker // Temporarily disable rosalloc verification because the zygote
2526*795d594fSAndroid Build Coastguard Worker // compaction will mess up the rosalloc internal metadata.
2527*795d594fSAndroid Build Coastguard Worker ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
2528*795d594fSAndroid Build Coastguard Worker ZygoteCompactingCollector zygote_collector(this, is_running_on_memory_tool_);
2529*795d594fSAndroid Build Coastguard Worker zygote_collector.BuildBins(non_moving_space_);
2530*795d594fSAndroid Build Coastguard Worker // Create a new bump pointer space which we will compact into.
2531*795d594fSAndroid Build Coastguard Worker space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
2532*795d594fSAndroid Build Coastguard Worker non_moving_space_->Limit());
2533*795d594fSAndroid Build Coastguard Worker // Compact the bump pointer space to a new zygote bump pointer space.
2534*795d594fSAndroid Build Coastguard Worker bool reset_main_space = false;
2535*795d594fSAndroid Build Coastguard Worker if (IsMovingGc(collector_type_)) {
2536*795d594fSAndroid Build Coastguard Worker if (collector_type_ == kCollectorTypeCC) {
2537*795d594fSAndroid Build Coastguard Worker zygote_collector.SetFromSpace(region_space_);
2538*795d594fSAndroid Build Coastguard Worker } else {
2539*795d594fSAndroid Build Coastguard Worker zygote_collector.SetFromSpace(bump_pointer_space_);
2540*795d594fSAndroid Build Coastguard Worker }
2541*795d594fSAndroid Build Coastguard Worker } else {
2542*795d594fSAndroid Build Coastguard Worker CHECK(main_space_ != nullptr);
2543*795d594fSAndroid Build Coastguard Worker CHECK_NE(main_space_, non_moving_space_)
2544*795d594fSAndroid Build Coastguard Worker << "Does not make sense to compact within the same space";
2545*795d594fSAndroid Build Coastguard Worker // Copy from the main space.
2546*795d594fSAndroid Build Coastguard Worker zygote_collector.SetFromSpace(main_space_);
2547*795d594fSAndroid Build Coastguard Worker reset_main_space = true;
2548*795d594fSAndroid Build Coastguard Worker }
2549*795d594fSAndroid Build Coastguard Worker zygote_collector.SetToSpace(&target_space);
2550*795d594fSAndroid Build Coastguard Worker zygote_collector.SetSwapSemiSpaces(false);
2551*795d594fSAndroid Build Coastguard Worker zygote_collector.Run(kGcCauseCollectorTransition, false);
2552*795d594fSAndroid Build Coastguard Worker if (reset_main_space) {
2553*795d594fSAndroid Build Coastguard Worker main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2554*795d594fSAndroid Build Coastguard Worker madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
2555*795d594fSAndroid Build Coastguard Worker MemMap mem_map = main_space_->ReleaseMemMap();
2556*795d594fSAndroid Build Coastguard Worker RemoveSpace(main_space_);
2557*795d594fSAndroid Build Coastguard Worker space::Space* old_main_space = main_space_;
2558*795d594fSAndroid Build Coastguard Worker CreateMainMallocSpace(std::move(mem_map),
2559*795d594fSAndroid Build Coastguard Worker kDefaultInitialSize,
2560*795d594fSAndroid Build Coastguard Worker std::min(mem_map.Size(), growth_limit_),
2561*795d594fSAndroid Build Coastguard Worker mem_map.Size());
2562*795d594fSAndroid Build Coastguard Worker delete old_main_space;
2563*795d594fSAndroid Build Coastguard Worker AddSpace(main_space_);
2564*795d594fSAndroid Build Coastguard Worker } else {
2565*795d594fSAndroid Build Coastguard Worker if (collector_type_ == kCollectorTypeCC) {
2566*795d594fSAndroid Build Coastguard Worker region_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2567*795d594fSAndroid Build Coastguard Worker // Evacuated everything out of the region space, clear the mark bitmap.
2568*795d594fSAndroid Build Coastguard Worker region_space_->GetMarkBitmap()->Clear();
2569*795d594fSAndroid Build Coastguard Worker } else {
2570*795d594fSAndroid Build Coastguard Worker bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2571*795d594fSAndroid Build Coastguard Worker }
2572*795d594fSAndroid Build Coastguard Worker }
2573*795d594fSAndroid Build Coastguard Worker if (temp_space_ != nullptr) {
2574*795d594fSAndroid Build Coastguard Worker CHECK(temp_space_->IsEmpty());
2575*795d594fSAndroid Build Coastguard Worker }
2576*795d594fSAndroid Build Coastguard Worker IncrementFreedEver();
2577*795d594fSAndroid Build Coastguard Worker // Update the end and write out image.
2578*795d594fSAndroid Build Coastguard Worker non_moving_space_->SetEnd(target_space.End());
2579*795d594fSAndroid Build Coastguard Worker non_moving_space_->SetLimit(target_space.Limit());
2580*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Create zygote space with size=" << non_moving_space_->Size() << " bytes";
2581*795d594fSAndroid Build Coastguard Worker }
2582*795d594fSAndroid Build Coastguard Worker // Change the collector to the post zygote one.
2583*795d594fSAndroid Build Coastguard Worker ChangeCollector(foreground_collector_type_);
2584*795d594fSAndroid Build Coastguard Worker // Save the old space so that we can remove it after we complete creating the zygote space.
2585*795d594fSAndroid Build Coastguard Worker space::MallocSpace* old_alloc_space = non_moving_space_;
2586*795d594fSAndroid Build Coastguard Worker // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
2587*795d594fSAndroid Build Coastguard Worker // the remaining available space.
2588*795d594fSAndroid Build Coastguard Worker // Remove the old space before creating the zygote space since creating the zygote space sets
2589*795d594fSAndroid Build Coastguard Worker // the old alloc space's bitmaps to null.
2590*795d594fSAndroid Build Coastguard Worker RemoveSpace(old_alloc_space);
2591*795d594fSAndroid Build Coastguard Worker if (collector::SemiSpace::kUseRememberedSet) {
2592*795d594fSAndroid Build Coastguard Worker // Consistency bound check.
2593*795d594fSAndroid Build Coastguard Worker FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
2594*795d594fSAndroid Build Coastguard Worker // Remove the remembered set for the now zygote space (the old
2595*795d594fSAndroid Build Coastguard Worker // non-moving space). Note now that we have compacted objects into
2596*795d594fSAndroid Build Coastguard Worker // the zygote space, the data in the remembered set is no longer
2597*795d594fSAndroid Build Coastguard Worker // needed. The zygote space will instead have a mod-union table
2598*795d594fSAndroid Build Coastguard Worker // from this point on.
2599*795d594fSAndroid Build Coastguard Worker RemoveRememberedSet(old_alloc_space);
2600*795d594fSAndroid Build Coastguard Worker }
2601*795d594fSAndroid Build Coastguard Worker // Remaining space becomes the new non moving space.
2602*795d594fSAndroid Build Coastguard Worker zygote_space_ = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName, low_memory_mode_,
2603*795d594fSAndroid Build Coastguard Worker &non_moving_space_);
2604*795d594fSAndroid Build Coastguard Worker CHECK(!non_moving_space_->CanMoveObjects());
2605*795d594fSAndroid Build Coastguard Worker if (same_space) {
2606*795d594fSAndroid Build Coastguard Worker main_space_ = non_moving_space_;
2607*795d594fSAndroid Build Coastguard Worker SetSpaceAsDefault(main_space_);
2608*795d594fSAndroid Build Coastguard Worker }
2609*795d594fSAndroid Build Coastguard Worker delete old_alloc_space;
2610*795d594fSAndroid Build Coastguard Worker CHECK(HasZygoteSpace()) << "Failed creating zygote space";
2611*795d594fSAndroid Build Coastguard Worker AddSpace(zygote_space_);
2612*795d594fSAndroid Build Coastguard Worker non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2613*795d594fSAndroid Build Coastguard Worker AddSpace(non_moving_space_);
2614*795d594fSAndroid Build Coastguard Worker constexpr bool set_mark_bit = kUseBakerReadBarrier
2615*795d594fSAndroid Build Coastguard Worker && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects;
2616*795d594fSAndroid Build Coastguard Worker if (set_mark_bit) {
2617*795d594fSAndroid Build Coastguard Worker // Treat all of the objects in the zygote as marked to avoid unnecessary dirty pages. This is
2618*795d594fSAndroid Build Coastguard Worker // safe since we mark all of the objects that may reference non immune objects as gray.
2619*795d594fSAndroid Build Coastguard Worker zygote_space_->SetMarkBitInLiveObjects();
2620*795d594fSAndroid Build Coastguard Worker }
2621*795d594fSAndroid Build Coastguard Worker
2622*795d594fSAndroid Build Coastguard Worker // Create the zygote space mod union table.
2623*795d594fSAndroid Build Coastguard Worker accounting::ModUnionTable* mod_union_table =
2624*795d594fSAndroid Build Coastguard Worker new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space_);
2625*795d594fSAndroid Build Coastguard Worker CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
2626*795d594fSAndroid Build Coastguard Worker
2627*795d594fSAndroid Build Coastguard Worker if (collector_type_ != kCollectorTypeCC && collector_type_ != kCollectorTypeCMC) {
2628*795d594fSAndroid Build Coastguard Worker // Set all the cards in the mod-union table since we don't know which objects contain references
2629*795d594fSAndroid Build Coastguard Worker // to large objects.
2630*795d594fSAndroid Build Coastguard Worker mod_union_table->SetCards();
2631*795d594fSAndroid Build Coastguard Worker } else {
2632*795d594fSAndroid Build Coastguard Worker // Make sure to clear the zygote space cards so that we don't dirty pages in the next GC. There
2633*795d594fSAndroid Build Coastguard Worker // may be dirty cards from the zygote compaction or reference processing. These cards are not
2634*795d594fSAndroid Build Coastguard Worker // necessary to have marked since the zygote space may not refer to any objects not in the
2635*795d594fSAndroid Build Coastguard Worker // zygote or image spaces at this point.
2636*795d594fSAndroid Build Coastguard Worker mod_union_table->ProcessCards();
2637*795d594fSAndroid Build Coastguard Worker mod_union_table->ClearTable();
2638*795d594fSAndroid Build Coastguard Worker
2639*795d594fSAndroid Build Coastguard Worker // For CC and CMC we never collect zygote large objects. This means we do not need to set the
2640*795d594fSAndroid Build Coastguard Worker // cards for the zygote mod-union table and we can also clear all of the existing image
2641*795d594fSAndroid Build Coastguard Worker // mod-union tables. The existing mod-union tables are only for image spaces and may only
2642*795d594fSAndroid Build Coastguard Worker // reference zygote and image objects.
2643*795d594fSAndroid Build Coastguard Worker for (auto& pair : mod_union_tables_) {
2644*795d594fSAndroid Build Coastguard Worker CHECK(pair.first->IsImageSpace());
2645*795d594fSAndroid Build Coastguard Worker CHECK(!pair.first->AsImageSpace()->GetImageHeader().IsAppImage());
2646*795d594fSAndroid Build Coastguard Worker accounting::ModUnionTable* table = pair.second;
2647*795d594fSAndroid Build Coastguard Worker table->ClearTable();
2648*795d594fSAndroid Build Coastguard Worker }
2649*795d594fSAndroid Build Coastguard Worker }
2650*795d594fSAndroid Build Coastguard Worker AddModUnionTable(mod_union_table);
2651*795d594fSAndroid Build Coastguard Worker large_object_space_->SetAllLargeObjectsAsZygoteObjects(self, set_mark_bit);
2652*795d594fSAndroid Build Coastguard Worker if (collector::SemiSpace::kUseRememberedSet) {
2653*795d594fSAndroid Build Coastguard Worker // Add a new remembered set for the post-zygote non-moving space.
2654*795d594fSAndroid Build Coastguard Worker accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2655*795d594fSAndroid Build Coastguard Worker new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2656*795d594fSAndroid Build Coastguard Worker non_moving_space_);
2657*795d594fSAndroid Build Coastguard Worker CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2658*795d594fSAndroid Build Coastguard Worker << "Failed to create post-zygote non-moving space remembered set";
2659*795d594fSAndroid Build Coastguard Worker AddRememberedSet(post_zygote_non_moving_space_rem_set);
2660*795d594fSAndroid Build Coastguard Worker }
2661*795d594fSAndroid Build Coastguard Worker }
2662*795d594fSAndroid Build Coastguard Worker #pragma clang diagnostic pop
2663*795d594fSAndroid Build Coastguard Worker
FlushAllocStack()2664*795d594fSAndroid Build Coastguard Worker void Heap::FlushAllocStack() {
2665*795d594fSAndroid Build Coastguard Worker MarkAllocStackAsLive(allocation_stack_.get());
2666*795d594fSAndroid Build Coastguard Worker allocation_stack_->Reset();
2667*795d594fSAndroid Build Coastguard Worker }
2668*795d594fSAndroid Build Coastguard Worker
MarkAllocStack(accounting::ContinuousSpaceBitmap * bitmap1,accounting::ContinuousSpaceBitmap * bitmap2,accounting::LargeObjectBitmap * large_objects,accounting::ObjectStack * stack)2669*795d594fSAndroid Build Coastguard Worker void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2670*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* bitmap2,
2671*795d594fSAndroid Build Coastguard Worker accounting::LargeObjectBitmap* large_objects,
2672*795d594fSAndroid Build Coastguard Worker accounting::ObjectStack* stack) {
2673*795d594fSAndroid Build Coastguard Worker DCHECK(bitmap1 != nullptr);
2674*795d594fSAndroid Build Coastguard Worker DCHECK(bitmap2 != nullptr);
2675*795d594fSAndroid Build Coastguard Worker const auto* limit = stack->End();
2676*795d594fSAndroid Build Coastguard Worker for (auto* it = stack->Begin(); it != limit; ++it) {
2677*795d594fSAndroid Build Coastguard Worker const mirror::Object* obj = it->AsMirrorPtr();
2678*795d594fSAndroid Build Coastguard Worker if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2679*795d594fSAndroid Build Coastguard Worker if (bitmap1->HasAddress(obj)) {
2680*795d594fSAndroid Build Coastguard Worker bitmap1->Set(obj);
2681*795d594fSAndroid Build Coastguard Worker } else if (bitmap2->HasAddress(obj)) {
2682*795d594fSAndroid Build Coastguard Worker bitmap2->Set(obj);
2683*795d594fSAndroid Build Coastguard Worker } else {
2684*795d594fSAndroid Build Coastguard Worker DCHECK(large_objects != nullptr);
2685*795d594fSAndroid Build Coastguard Worker large_objects->Set(obj);
2686*795d594fSAndroid Build Coastguard Worker }
2687*795d594fSAndroid Build Coastguard Worker }
2688*795d594fSAndroid Build Coastguard Worker }
2689*795d594fSAndroid Build Coastguard Worker }
2690*795d594fSAndroid Build Coastguard Worker
SwapSemiSpaces()2691*795d594fSAndroid Build Coastguard Worker void Heap::SwapSemiSpaces() {
2692*795d594fSAndroid Build Coastguard Worker CHECK(bump_pointer_space_ != nullptr);
2693*795d594fSAndroid Build Coastguard Worker CHECK(temp_space_ != nullptr);
2694*795d594fSAndroid Build Coastguard Worker std::swap(bump_pointer_space_, temp_space_);
2695*795d594fSAndroid Build Coastguard Worker }
2696*795d594fSAndroid Build Coastguard Worker
Compact(space::ContinuousMemMapAllocSpace * target_space,space::ContinuousMemMapAllocSpace * source_space,GcCause gc_cause)2697*795d594fSAndroid Build Coastguard Worker collector::GarbageCollector* Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2698*795d594fSAndroid Build Coastguard Worker space::ContinuousMemMapAllocSpace* source_space,
2699*795d594fSAndroid Build Coastguard Worker GcCause gc_cause) {
2700*795d594fSAndroid Build Coastguard Worker CHECK(kMovingCollector);
2701*795d594fSAndroid Build Coastguard Worker if (target_space != source_space) {
2702*795d594fSAndroid Build Coastguard Worker // Don't swap spaces since this isn't a typical semi space collection.
2703*795d594fSAndroid Build Coastguard Worker semi_space_collector_->SetSwapSemiSpaces(false);
2704*795d594fSAndroid Build Coastguard Worker semi_space_collector_->SetFromSpace(source_space);
2705*795d594fSAndroid Build Coastguard Worker semi_space_collector_->SetToSpace(target_space);
2706*795d594fSAndroid Build Coastguard Worker semi_space_collector_->Run(gc_cause, false);
2707*795d594fSAndroid Build Coastguard Worker return semi_space_collector_;
2708*795d594fSAndroid Build Coastguard Worker }
2709*795d594fSAndroid Build Coastguard Worker LOG(FATAL) << "Unsupported";
2710*795d594fSAndroid Build Coastguard Worker UNREACHABLE();
2711*795d594fSAndroid Build Coastguard Worker }
2712*795d594fSAndroid Build Coastguard Worker
TraceHeapSize(size_t heap_size)2713*795d594fSAndroid Build Coastguard Worker void Heap::TraceHeapSize(size_t heap_size) {
2714*795d594fSAndroid Build Coastguard Worker ATraceIntegerValue("Heap size (KB)", heap_size / KB);
2715*795d594fSAndroid Build Coastguard Worker }
2716*795d594fSAndroid Build Coastguard Worker
2717*795d594fSAndroid Build Coastguard Worker #if defined(__GLIBC__)
2718*795d594fSAndroid Build Coastguard Worker # define IF_GLIBC(x) x
2719*795d594fSAndroid Build Coastguard Worker #else
2720*795d594fSAndroid Build Coastguard Worker # define IF_GLIBC(x)
2721*795d594fSAndroid Build Coastguard Worker #endif
2722*795d594fSAndroid Build Coastguard Worker
GetNativeBytes()2723*795d594fSAndroid Build Coastguard Worker size_t Heap::GetNativeBytes() {
2724*795d594fSAndroid Build Coastguard Worker size_t malloc_bytes;
2725*795d594fSAndroid Build Coastguard Worker #if defined(__BIONIC__) || defined(__GLIBC__) || defined(ANDROID_HOST_MUSL)
2726*795d594fSAndroid Build Coastguard Worker IF_GLIBC(size_t mmapped_bytes;)
2727*795d594fSAndroid Build Coastguard Worker struct mallinfo mi = mallinfo();
2728*795d594fSAndroid Build Coastguard Worker // In spite of the documentation, the jemalloc version of this call seems to do what we want,
2729*795d594fSAndroid Build Coastguard Worker // and it is thread-safe.
2730*795d594fSAndroid Build Coastguard Worker if (sizeof(size_t) > sizeof(mi.uordblks) && sizeof(size_t) > sizeof(mi.hblkhd)) {
2731*795d594fSAndroid Build Coastguard Worker // Shouldn't happen, but glibc declares uordblks as int.
2732*795d594fSAndroid Build Coastguard Worker // Avoiding sign extension gets us correct behavior for another 2 GB.
2733*795d594fSAndroid Build Coastguard Worker malloc_bytes = (unsigned int)mi.uordblks;
2734*795d594fSAndroid Build Coastguard Worker IF_GLIBC(mmapped_bytes = (unsigned int)mi.hblkhd;)
2735*795d594fSAndroid Build Coastguard Worker } else {
2736*795d594fSAndroid Build Coastguard Worker malloc_bytes = mi.uordblks;
2737*795d594fSAndroid Build Coastguard Worker IF_GLIBC(mmapped_bytes = mi.hblkhd;)
2738*795d594fSAndroid Build Coastguard Worker }
2739*795d594fSAndroid Build Coastguard Worker // From the spec, it appeared mmapped_bytes <= malloc_bytes. Reality was sometimes
2740*795d594fSAndroid Build Coastguard Worker // dramatically different. (b/119580449 was an early bug.) If so, we try to fudge it.
2741*795d594fSAndroid Build Coastguard Worker // However, malloc implementations seem to interpret hblkhd differently, namely as
2742*795d594fSAndroid Build Coastguard Worker // mapped blocks backing the entire heap (e.g. jemalloc) vs. large objects directly
2743*795d594fSAndroid Build Coastguard Worker // allocated via mmap (e.g. glibc). Thus we now only do this for glibc, where it
2744*795d594fSAndroid Build Coastguard Worker // previously helped, and which appears to use a reading of the spec compatible
2745*795d594fSAndroid Build Coastguard Worker // with our adjustment.
2746*795d594fSAndroid Build Coastguard Worker #if defined(__GLIBC__)
2747*795d594fSAndroid Build Coastguard Worker if (mmapped_bytes > malloc_bytes) {
2748*795d594fSAndroid Build Coastguard Worker malloc_bytes = mmapped_bytes;
2749*795d594fSAndroid Build Coastguard Worker }
2750*795d594fSAndroid Build Coastguard Worker #endif // GLIBC
2751*795d594fSAndroid Build Coastguard Worker #else // Neither Bionic nor Glibc
2752*795d594fSAndroid Build Coastguard Worker // We should hit this case only in contexts in which GC triggering is not critical. Effectively
2753*795d594fSAndroid Build Coastguard Worker // disable GC triggering based on malloc().
2754*795d594fSAndroid Build Coastguard Worker malloc_bytes = 1000;
2755*795d594fSAndroid Build Coastguard Worker #endif
2756*795d594fSAndroid Build Coastguard Worker return malloc_bytes + native_bytes_registered_.load(std::memory_order_relaxed);
2757*795d594fSAndroid Build Coastguard Worker // An alternative would be to get RSS from /proc/self/statm. Empirically, that's no
2758*795d594fSAndroid Build Coastguard Worker // more expensive, and it would allow us to count memory allocated by means other than malloc.
2759*795d594fSAndroid Build Coastguard Worker // However it would change as pages are unmapped and remapped due to memory pressure, among
2760*795d594fSAndroid Build Coastguard Worker // other things. It seems risky to trigger GCs as a result of such changes.
2761*795d594fSAndroid Build Coastguard Worker }
2762*795d594fSAndroid Build Coastguard Worker
GCNumberLt(uint32_t gc_num1,uint32_t gc_num2)2763*795d594fSAndroid Build Coastguard Worker static inline bool GCNumberLt(uint32_t gc_num1, uint32_t gc_num2) {
2764*795d594fSAndroid Build Coastguard Worker // unsigned comparison, assuming a non-huge difference, but dealing correctly with wrapping.
2765*795d594fSAndroid Build Coastguard Worker uint32_t difference = gc_num2 - gc_num1;
2766*795d594fSAndroid Build Coastguard Worker bool completed_more_than_requested = difference > 0x80000000;
2767*795d594fSAndroid Build Coastguard Worker return difference > 0 && !completed_more_than_requested;
2768*795d594fSAndroid Build Coastguard Worker }
2769*795d594fSAndroid Build Coastguard Worker
2770*795d594fSAndroid Build Coastguard Worker
CollectGarbageInternal(collector::GcType gc_type,GcCause gc_cause,bool clear_soft_references,uint32_t requested_gc_num)2771*795d594fSAndroid Build Coastguard Worker collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type,
2772*795d594fSAndroid Build Coastguard Worker GcCause gc_cause,
2773*795d594fSAndroid Build Coastguard Worker bool clear_soft_references,
2774*795d594fSAndroid Build Coastguard Worker uint32_t requested_gc_num) {
2775*795d594fSAndroid Build Coastguard Worker Thread* self = Thread::Current();
2776*795d594fSAndroid Build Coastguard Worker Runtime* runtime = Runtime::Current();
2777*795d594fSAndroid Build Coastguard Worker // If the heap can't run the GC, silently fail and return that no GC was run.
2778*795d594fSAndroid Build Coastguard Worker switch (gc_type) {
2779*795d594fSAndroid Build Coastguard Worker case collector::kGcTypePartial: {
2780*795d594fSAndroid Build Coastguard Worker if (!HasZygoteSpace()) {
2781*795d594fSAndroid Build Coastguard Worker // Do not increment gcs_completed_ . We should retry with kGcTypeFull.
2782*795d594fSAndroid Build Coastguard Worker return collector::kGcTypeNone;
2783*795d594fSAndroid Build Coastguard Worker }
2784*795d594fSAndroid Build Coastguard Worker break;
2785*795d594fSAndroid Build Coastguard Worker }
2786*795d594fSAndroid Build Coastguard Worker default: {
2787*795d594fSAndroid Build Coastguard Worker // Other GC types don't have any special cases which makes them not runnable. The main case
2788*795d594fSAndroid Build Coastguard Worker // here is full GC.
2789*795d594fSAndroid Build Coastguard Worker }
2790*795d594fSAndroid Build Coastguard Worker }
2791*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc(self, ThreadState::kWaitingPerformingGc);
2792*795d594fSAndroid Build Coastguard Worker Locks::mutator_lock_->AssertNotHeld(self);
2793*795d594fSAndroid Build Coastguard Worker SelfDeletingTask* clear; // Unconditionally set below.
2794*795d594fSAndroid Build Coastguard Worker {
2795*795d594fSAndroid Build Coastguard Worker // We should not ever become runnable and re-suspend while executing a GC.
2796*795d594fSAndroid Build Coastguard Worker // This would likely cause a deadlock if we acted on a suspension request.
2797*795d594fSAndroid Build Coastguard Worker // TODO: We really want to assert that we don't transition to kRunnable.
2798*795d594fSAndroid Build Coastguard Worker ScopedAssertNoThreadSuspension scoped_assert("Performing GC");
2799*795d594fSAndroid Build Coastguard Worker if (self->IsHandlingStackOverflow<kNativeStackType>()) {
2800*795d594fSAndroid Build Coastguard Worker // If we are throwing a stack overflow error we probably don't have enough remaining stack
2801*795d594fSAndroid Build Coastguard Worker // space to run the GC. Note: we only care if the native stack has overflowed. If the
2802*795d594fSAndroid Build Coastguard Worker // simulated stack overflows it is still possible that the native stack has room to run the
2803*795d594fSAndroid Build Coastguard Worker // GC.
2804*795d594fSAndroid Build Coastguard Worker
2805*795d594fSAndroid Build Coastguard Worker // Count this as a GC in case someone is waiting for it to complete.
2806*795d594fSAndroid Build Coastguard Worker gcs_completed_.fetch_add(1, std::memory_order_release);
2807*795d594fSAndroid Build Coastguard Worker return collector::kGcTypeNone;
2808*795d594fSAndroid Build Coastguard Worker }
2809*795d594fSAndroid Build Coastguard Worker bool compacting_gc;
2810*795d594fSAndroid Build Coastguard Worker {
2811*795d594fSAndroid Build Coastguard Worker gc_complete_lock_->AssertNotHeld(self);
2812*795d594fSAndroid Build Coastguard Worker // Already not runnable; just switch suspended states. We remain in a suspended state until
2813*795d594fSAndroid Build Coastguard Worker // FinishGC(). This avoids the complicated dance in StartGC().
2814*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc2(self, ThreadState::kWaitingForGcToComplete);
2815*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *gc_complete_lock_);
2816*795d594fSAndroid Build Coastguard Worker // Ensure there is only one GC at a time.
2817*795d594fSAndroid Build Coastguard Worker WaitForGcToCompleteLocked(gc_cause, self);
2818*795d594fSAndroid Build Coastguard Worker if (requested_gc_num != GC_NUM_ANY && !GCNumberLt(GetCurrentGcNum(), requested_gc_num)) {
2819*795d594fSAndroid Build Coastguard Worker // The appropriate GC was already triggered elsewhere.
2820*795d594fSAndroid Build Coastguard Worker return collector::kGcTypeNone;
2821*795d594fSAndroid Build Coastguard Worker }
2822*795d594fSAndroid Build Coastguard Worker compacting_gc = IsMovingGc(collector_type_);
2823*795d594fSAndroid Build Coastguard Worker // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2824*795d594fSAndroid Build Coastguard Worker if (compacting_gc && disable_moving_gc_count_ != 0) {
2825*795d594fSAndroid Build Coastguard Worker LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2826*795d594fSAndroid Build Coastguard Worker // Again count this as a GC.
2827*795d594fSAndroid Build Coastguard Worker gcs_completed_.fetch_add(1, std::memory_order_release);
2828*795d594fSAndroid Build Coastguard Worker return collector::kGcTypeNone;
2829*795d594fSAndroid Build Coastguard Worker }
2830*795d594fSAndroid Build Coastguard Worker if (gc_disabled_for_shutdown_) {
2831*795d594fSAndroid Build Coastguard Worker gcs_completed_.fetch_add(1, std::memory_order_release);
2832*795d594fSAndroid Build Coastguard Worker return collector::kGcTypeNone;
2833*795d594fSAndroid Build Coastguard Worker }
2834*795d594fSAndroid Build Coastguard Worker collector_type_running_ = collector_type_;
2835*795d594fSAndroid Build Coastguard Worker last_gc_cause_ = gc_cause;
2836*795d594fSAndroid Build Coastguard Worker }
2837*795d594fSAndroid Build Coastguard Worker if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2838*795d594fSAndroid Build Coastguard Worker ++runtime->GetStats()->gc_for_alloc_count;
2839*795d594fSAndroid Build Coastguard Worker ++self->GetStats()->gc_for_alloc_count;
2840*795d594fSAndroid Build Coastguard Worker }
2841*795d594fSAndroid Build Coastguard Worker const size_t bytes_allocated_before_gc = GetBytesAllocated();
2842*795d594fSAndroid Build Coastguard Worker
2843*795d594fSAndroid Build Coastguard Worker DCHECK_LT(gc_type, collector::kGcTypeMax);
2844*795d594fSAndroid Build Coastguard Worker DCHECK_NE(gc_type, collector::kGcTypeNone);
2845*795d594fSAndroid Build Coastguard Worker
2846*795d594fSAndroid Build Coastguard Worker collector::GarbageCollector* collector = nullptr;
2847*795d594fSAndroid Build Coastguard Worker // TODO: Clean this up.
2848*795d594fSAndroid Build Coastguard Worker if (compacting_gc) {
2849*795d594fSAndroid Build Coastguard Worker DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
2850*795d594fSAndroid Build Coastguard Worker current_allocator_ == kAllocatorTypeTLAB ||
2851*795d594fSAndroid Build Coastguard Worker current_allocator_ == kAllocatorTypeRegion ||
2852*795d594fSAndroid Build Coastguard Worker current_allocator_ == kAllocatorTypeRegionTLAB);
2853*795d594fSAndroid Build Coastguard Worker switch (collector_type_) {
2854*795d594fSAndroid Build Coastguard Worker case kCollectorTypeSS:
2855*795d594fSAndroid Build Coastguard Worker semi_space_collector_->SetFromSpace(bump_pointer_space_);
2856*795d594fSAndroid Build Coastguard Worker semi_space_collector_->SetToSpace(temp_space_);
2857*795d594fSAndroid Build Coastguard Worker semi_space_collector_->SetSwapSemiSpaces(true);
2858*795d594fSAndroid Build Coastguard Worker collector = semi_space_collector_;
2859*795d594fSAndroid Build Coastguard Worker break;
2860*795d594fSAndroid Build Coastguard Worker case kCollectorTypeCMC:
2861*795d594fSAndroid Build Coastguard Worker collector = mark_compact_;
2862*795d594fSAndroid Build Coastguard Worker break;
2863*795d594fSAndroid Build Coastguard Worker case kCollectorTypeCC:
2864*795d594fSAndroid Build Coastguard Worker collector::ConcurrentCopying* active_cc_collector;
2865*795d594fSAndroid Build Coastguard Worker if (use_generational_cc_) {
2866*795d594fSAndroid Build Coastguard Worker // TODO: Other threads must do the flip checkpoint before they start poking at
2867*795d594fSAndroid Build Coastguard Worker // active_concurrent_copying_collector_. So we should not concurrency here.
2868*795d594fSAndroid Build Coastguard Worker active_cc_collector = (gc_type == collector::kGcTypeSticky) ?
2869*795d594fSAndroid Build Coastguard Worker young_concurrent_copying_collector_ :
2870*795d594fSAndroid Build Coastguard Worker concurrent_copying_collector_;
2871*795d594fSAndroid Build Coastguard Worker active_concurrent_copying_collector_.store(active_cc_collector,
2872*795d594fSAndroid Build Coastguard Worker std::memory_order_relaxed);
2873*795d594fSAndroid Build Coastguard Worker DCHECK(active_cc_collector->RegionSpace() == region_space_);
2874*795d594fSAndroid Build Coastguard Worker collector = active_cc_collector;
2875*795d594fSAndroid Build Coastguard Worker } else {
2876*795d594fSAndroid Build Coastguard Worker collector = active_concurrent_copying_collector_.load(std::memory_order_relaxed);
2877*795d594fSAndroid Build Coastguard Worker }
2878*795d594fSAndroid Build Coastguard Worker break;
2879*795d594fSAndroid Build Coastguard Worker default:
2880*795d594fSAndroid Build Coastguard Worker LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
2881*795d594fSAndroid Build Coastguard Worker }
2882*795d594fSAndroid Build Coastguard Worker // temp_space_ will be null for kCollectorTypeCMC.
2883*795d594fSAndroid Build Coastguard Worker if (temp_space_ != nullptr &&
2884*795d594fSAndroid Build Coastguard Worker collector != active_concurrent_copying_collector_.load(std::memory_order_relaxed)) {
2885*795d594fSAndroid Build Coastguard Worker temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2886*795d594fSAndroid Build Coastguard Worker if (kIsDebugBuild) {
2887*795d594fSAndroid Build Coastguard Worker // Try to read each page of the memory map in case mprotect didn't work properly
2888*795d594fSAndroid Build Coastguard Worker // b/19894268.
2889*795d594fSAndroid Build Coastguard Worker temp_space_->GetMemMap()->TryReadable();
2890*795d594fSAndroid Build Coastguard Worker }
2891*795d594fSAndroid Build Coastguard Worker CHECK(temp_space_->IsEmpty());
2892*795d594fSAndroid Build Coastguard Worker }
2893*795d594fSAndroid Build Coastguard Worker } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2894*795d594fSAndroid Build Coastguard Worker current_allocator_ == kAllocatorTypeDlMalloc) {
2895*795d594fSAndroid Build Coastguard Worker collector = FindCollectorByGcType(gc_type);
2896*795d594fSAndroid Build Coastguard Worker } else {
2897*795d594fSAndroid Build Coastguard Worker LOG(FATAL) << "Invalid current allocator " << current_allocator_;
2898*795d594fSAndroid Build Coastguard Worker }
2899*795d594fSAndroid Build Coastguard Worker
2900*795d594fSAndroid Build Coastguard Worker CHECK(collector != nullptr) << "Could not find garbage collector with collector_type="
2901*795d594fSAndroid Build Coastguard Worker << static_cast<size_t>(collector_type_)
2902*795d594fSAndroid Build Coastguard Worker << " and gc_type=" << gc_type;
2903*795d594fSAndroid Build Coastguard Worker collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
2904*795d594fSAndroid Build Coastguard Worker IncrementFreedEver();
2905*795d594fSAndroid Build Coastguard Worker RequestTrim(self);
2906*795d594fSAndroid Build Coastguard Worker // Collect cleared references.
2907*795d594fSAndroid Build Coastguard Worker clear = reference_processor_->CollectClearedReferences(self);
2908*795d594fSAndroid Build Coastguard Worker // Grow the heap so that we know when to perform the next GC.
2909*795d594fSAndroid Build Coastguard Worker GrowForUtilization(collector, bytes_allocated_before_gc);
2910*795d594fSAndroid Build Coastguard Worker old_native_bytes_allocated_.store(GetNativeBytes());
2911*795d594fSAndroid Build Coastguard Worker LogGC(gc_cause, collector);
2912*795d594fSAndroid Build Coastguard Worker FinishGC(self, gc_type);
2913*795d594fSAndroid Build Coastguard Worker // We're suspended up to this point.
2914*795d594fSAndroid Build Coastguard Worker }
2915*795d594fSAndroid Build Coastguard Worker // Actually enqueue all cleared references. Do this after the GC has officially finished since
2916*795d594fSAndroid Build Coastguard Worker // otherwise we can deadlock.
2917*795d594fSAndroid Build Coastguard Worker clear->Run(self);
2918*795d594fSAndroid Build Coastguard Worker clear->Finalize();
2919*795d594fSAndroid Build Coastguard Worker // Inform DDMS that a GC completed.
2920*795d594fSAndroid Build Coastguard Worker Dbg::GcDidFinish();
2921*795d594fSAndroid Build Coastguard Worker
2922*795d594fSAndroid Build Coastguard Worker // Unload native libraries for class unloading. We do this after calling FinishGC to prevent
2923*795d594fSAndroid Build Coastguard Worker // deadlocks in case the JNI_OnUnload function does allocations.
2924*795d594fSAndroid Build Coastguard Worker {
2925*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(self);
2926*795d594fSAndroid Build Coastguard Worker soa.Vm()->UnloadNativeLibraries();
2927*795d594fSAndroid Build Coastguard Worker }
2928*795d594fSAndroid Build Coastguard Worker return gc_type;
2929*795d594fSAndroid Build Coastguard Worker }
2930*795d594fSAndroid Build Coastguard Worker
LogGC(GcCause gc_cause,collector::GarbageCollector * collector)2931*795d594fSAndroid Build Coastguard Worker void Heap::LogGC(GcCause gc_cause, collector::GarbageCollector* collector) {
2932*795d594fSAndroid Build Coastguard Worker const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2933*795d594fSAndroid Build Coastguard Worker const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
2934*795d594fSAndroid Build Coastguard Worker // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
2935*795d594fSAndroid Build Coastguard Worker // (mutator time blocked >= long_pause_log_threshold_).
2936*795d594fSAndroid Build Coastguard Worker bool log_gc = kLogAllGCs || (gc_cause == kGcCauseExplicit && always_log_explicit_gcs_);
2937*795d594fSAndroid Build Coastguard Worker if (!log_gc && CareAboutPauseTimes()) {
2938*795d594fSAndroid Build Coastguard Worker // GC for alloc pauses the allocating thread, so consider it as a pause.
2939*795d594fSAndroid Build Coastguard Worker log_gc = duration > long_gc_log_threshold_ ||
2940*795d594fSAndroid Build Coastguard Worker (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
2941*795d594fSAndroid Build Coastguard Worker for (uint64_t pause : pause_times) {
2942*795d594fSAndroid Build Coastguard Worker log_gc = log_gc || pause >= long_pause_log_threshold_;
2943*795d594fSAndroid Build Coastguard Worker }
2944*795d594fSAndroid Build Coastguard Worker }
2945*795d594fSAndroid Build Coastguard Worker bool is_sampled = false;
2946*795d594fSAndroid Build Coastguard Worker if (UNLIKELY(gc_stress_mode_)) {
2947*795d594fSAndroid Build Coastguard Worker static std::atomic_int64_t accumulated_duration_ns = 0;
2948*795d594fSAndroid Build Coastguard Worker accumulated_duration_ns += duration;
2949*795d594fSAndroid Build Coastguard Worker if (accumulated_duration_ns >= kGcStressModeGcLogSampleFrequencyNs) {
2950*795d594fSAndroid Build Coastguard Worker accumulated_duration_ns -= kGcStressModeGcLogSampleFrequencyNs;
2951*795d594fSAndroid Build Coastguard Worker log_gc = true;
2952*795d594fSAndroid Build Coastguard Worker is_sampled = true;
2953*795d594fSAndroid Build Coastguard Worker }
2954*795d594fSAndroid Build Coastguard Worker }
2955*795d594fSAndroid Build Coastguard Worker if (log_gc) {
2956*795d594fSAndroid Build Coastguard Worker const size_t percent_free = GetPercentFree();
2957*795d594fSAndroid Build Coastguard Worker const size_t current_heap_size = GetBytesAllocated();
2958*795d594fSAndroid Build Coastguard Worker const size_t total_memory = GetTotalMemory();
2959*795d594fSAndroid Build Coastguard Worker std::ostringstream pause_string;
2960*795d594fSAndroid Build Coastguard Worker for (size_t i = 0; i < pause_times.size(); ++i) {
2961*795d594fSAndroid Build Coastguard Worker pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2962*795d594fSAndroid Build Coastguard Worker << ((i != pause_times.size() - 1) ? "," : "");
2963*795d594fSAndroid Build Coastguard Worker }
2964*795d594fSAndroid Build Coastguard Worker LOG(INFO) << gc_cause << " " << collector->GetName()
2965*795d594fSAndroid Build Coastguard Worker << (is_sampled ? " (sampled)" : "")
2966*795d594fSAndroid Build Coastguard Worker << " GC freed "
2967*795d594fSAndroid Build Coastguard Worker << PrettySize(current_gc_iteration_.GetFreedBytes()) << " AllocSpace bytes, "
2968*795d594fSAndroid Build Coastguard Worker << current_gc_iteration_.GetFreedLargeObjects() << "("
2969*795d594fSAndroid Build Coastguard Worker << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
2970*795d594fSAndroid Build Coastguard Worker << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2971*795d594fSAndroid Build Coastguard Worker << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2972*795d594fSAndroid Build Coastguard Worker << " total " << PrettyDuration((duration / 1000) * 1000);
2973*795d594fSAndroid Build Coastguard Worker VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
2974*795d594fSAndroid Build Coastguard Worker }
2975*795d594fSAndroid Build Coastguard Worker }
2976*795d594fSAndroid Build Coastguard Worker
FinishGC(Thread * self,collector::GcType gc_type)2977*795d594fSAndroid Build Coastguard Worker void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2978*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *gc_complete_lock_);
2979*795d594fSAndroid Build Coastguard Worker collector_type_running_ = kCollectorTypeNone;
2980*795d594fSAndroid Build Coastguard Worker if (gc_type != collector::kGcTypeNone) {
2981*795d594fSAndroid Build Coastguard Worker last_gc_type_ = gc_type;
2982*795d594fSAndroid Build Coastguard Worker
2983*795d594fSAndroid Build Coastguard Worker // Update stats.
2984*795d594fSAndroid Build Coastguard Worker ++gc_count_last_window_;
2985*795d594fSAndroid Build Coastguard Worker if (running_collection_is_blocking_) {
2986*795d594fSAndroid Build Coastguard Worker // If the currently running collection was a blocking one,
2987*795d594fSAndroid Build Coastguard Worker // increment the counters and reset the flag.
2988*795d594fSAndroid Build Coastguard Worker ++blocking_gc_count_;
2989*795d594fSAndroid Build Coastguard Worker blocking_gc_time_ += GetCurrentGcIteration()->GetDurationNs();
2990*795d594fSAndroid Build Coastguard Worker ++blocking_gc_count_last_window_;
2991*795d594fSAndroid Build Coastguard Worker }
2992*795d594fSAndroid Build Coastguard Worker // Update the gc count rate histograms if due.
2993*795d594fSAndroid Build Coastguard Worker UpdateGcCountRateHistograms();
2994*795d594fSAndroid Build Coastguard Worker }
2995*795d594fSAndroid Build Coastguard Worker // Reset.
2996*795d594fSAndroid Build Coastguard Worker running_collection_is_blocking_ = false;
2997*795d594fSAndroid Build Coastguard Worker thread_running_gc_ = nullptr;
2998*795d594fSAndroid Build Coastguard Worker if (gc_type != collector::kGcTypeNone) {
2999*795d594fSAndroid Build Coastguard Worker gcs_completed_.fetch_add(1, std::memory_order_release);
3000*795d594fSAndroid Build Coastguard Worker }
3001*795d594fSAndroid Build Coastguard Worker // Wake anyone who may have been waiting for the GC to complete.
3002*795d594fSAndroid Build Coastguard Worker gc_complete_cond_->Broadcast(self);
3003*795d594fSAndroid Build Coastguard Worker }
3004*795d594fSAndroid Build Coastguard Worker
UpdateGcCountRateHistograms()3005*795d594fSAndroid Build Coastguard Worker void Heap::UpdateGcCountRateHistograms() {
3006*795d594fSAndroid Build Coastguard Worker // Invariant: if the time since the last update includes more than
3007*795d594fSAndroid Build Coastguard Worker // one windows, all the GC runs (if > 0) must have happened in first
3008*795d594fSAndroid Build Coastguard Worker // window because otherwise the update must have already taken place
3009*795d594fSAndroid Build Coastguard Worker // at an earlier GC run. So, we report the non-first windows with
3010*795d594fSAndroid Build Coastguard Worker // zero counts to the histograms.
3011*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
3012*795d594fSAndroid Build Coastguard Worker uint64_t now = NanoTime();
3013*795d594fSAndroid Build Coastguard Worker DCHECK_GE(now, last_update_time_gc_count_rate_histograms_);
3014*795d594fSAndroid Build Coastguard Worker uint64_t time_since_last_update = now - last_update_time_gc_count_rate_histograms_;
3015*795d594fSAndroid Build Coastguard Worker uint64_t num_of_windows = time_since_last_update / kGcCountRateHistogramWindowDuration;
3016*795d594fSAndroid Build Coastguard Worker
3017*795d594fSAndroid Build Coastguard Worker // The computed number of windows can be incoherently high if NanoTime() is not monotonic.
3018*795d594fSAndroid Build Coastguard Worker // Setting a limit on its maximum value reduces the impact on CPU time in such cases.
3019*795d594fSAndroid Build Coastguard Worker if (num_of_windows > kGcCountRateHistogramMaxNumMissedWindows) {
3020*795d594fSAndroid Build Coastguard Worker LOG(WARNING) << "Reducing the number of considered missed Gc histogram windows from "
3021*795d594fSAndroid Build Coastguard Worker << num_of_windows << " to " << kGcCountRateHistogramMaxNumMissedWindows;
3022*795d594fSAndroid Build Coastguard Worker num_of_windows = kGcCountRateHistogramMaxNumMissedWindows;
3023*795d594fSAndroid Build Coastguard Worker }
3024*795d594fSAndroid Build Coastguard Worker
3025*795d594fSAndroid Build Coastguard Worker if (time_since_last_update >= kGcCountRateHistogramWindowDuration) {
3026*795d594fSAndroid Build Coastguard Worker // Record the first window.
3027*795d594fSAndroid Build Coastguard Worker gc_count_rate_histogram_.AddValue(gc_count_last_window_ - 1); // Exclude the current run.
3028*795d594fSAndroid Build Coastguard Worker blocking_gc_count_rate_histogram_.AddValue(running_collection_is_blocking_ ?
3029*795d594fSAndroid Build Coastguard Worker blocking_gc_count_last_window_ - 1 : blocking_gc_count_last_window_);
3030*795d594fSAndroid Build Coastguard Worker // Record the other windows (with zero counts).
3031*795d594fSAndroid Build Coastguard Worker for (uint64_t i = 0; i < num_of_windows - 1; ++i) {
3032*795d594fSAndroid Build Coastguard Worker gc_count_rate_histogram_.AddValue(0);
3033*795d594fSAndroid Build Coastguard Worker blocking_gc_count_rate_histogram_.AddValue(0);
3034*795d594fSAndroid Build Coastguard Worker }
3035*795d594fSAndroid Build Coastguard Worker // Update the last update time and reset the counters.
3036*795d594fSAndroid Build Coastguard Worker last_update_time_gc_count_rate_histograms_ =
3037*795d594fSAndroid Build Coastguard Worker (now / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
3038*795d594fSAndroid Build Coastguard Worker gc_count_last_window_ = 1; // Include the current run.
3039*795d594fSAndroid Build Coastguard Worker blocking_gc_count_last_window_ = running_collection_is_blocking_ ? 1 : 0;
3040*795d594fSAndroid Build Coastguard Worker }
3041*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
3042*795d594fSAndroid Build Coastguard Worker }
3043*795d594fSAndroid Build Coastguard Worker
3044*795d594fSAndroid Build Coastguard Worker class RootMatchesObjectVisitor : public SingleRootVisitor {
3045*795d594fSAndroid Build Coastguard Worker public:
RootMatchesObjectVisitor(const mirror::Object * obj)3046*795d594fSAndroid Build Coastguard Worker explicit RootMatchesObjectVisitor(const mirror::Object* obj) : obj_(obj) { }
3047*795d594fSAndroid Build Coastguard Worker
VisitRoot(mirror::Object * root,const RootInfo & info)3048*795d594fSAndroid Build Coastguard Worker void VisitRoot(mirror::Object* root, const RootInfo& info)
3049*795d594fSAndroid Build Coastguard Worker override REQUIRES_SHARED(Locks::mutator_lock_) {
3050*795d594fSAndroid Build Coastguard Worker if (root == obj_) {
3051*795d594fSAndroid Build Coastguard Worker LOG(INFO) << "Object " << obj_ << " is a root " << info.ToString();
3052*795d594fSAndroid Build Coastguard Worker }
3053*795d594fSAndroid Build Coastguard Worker }
3054*795d594fSAndroid Build Coastguard Worker
3055*795d594fSAndroid Build Coastguard Worker private:
3056*795d594fSAndroid Build Coastguard Worker const mirror::Object* const obj_;
3057*795d594fSAndroid Build Coastguard Worker };
3058*795d594fSAndroid Build Coastguard Worker
3059*795d594fSAndroid Build Coastguard Worker
3060*795d594fSAndroid Build Coastguard Worker class ScanVisitor {
3061*795d594fSAndroid Build Coastguard Worker public:
operator ()(const mirror::Object * obj) const3062*795d594fSAndroid Build Coastguard Worker void operator()(const mirror::Object* obj) const {
3063*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Would have rescanned object " << obj;
3064*795d594fSAndroid Build Coastguard Worker }
3065*795d594fSAndroid Build Coastguard Worker };
3066*795d594fSAndroid Build Coastguard Worker
3067*795d594fSAndroid Build Coastguard Worker // Verify a reference from an object.
3068*795d594fSAndroid Build Coastguard Worker class VerifyReferenceVisitor : public SingleRootVisitor {
3069*795d594fSAndroid Build Coastguard Worker public:
VerifyReferenceVisitor(Thread * self,Heap * heap,size_t * fail_count,bool verify_referent)3070*795d594fSAndroid Build Coastguard Worker VerifyReferenceVisitor(Thread* self, Heap* heap, size_t* fail_count, bool verify_referent)
3071*795d594fSAndroid Build Coastguard Worker REQUIRES_SHARED(Locks::mutator_lock_)
3072*795d594fSAndroid Build Coastguard Worker : self_(self), heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
3073*795d594fSAndroid Build Coastguard Worker CHECK_EQ(self_, Thread::Current());
3074*795d594fSAndroid Build Coastguard Worker }
3075*795d594fSAndroid Build Coastguard Worker
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const3076*795d594fSAndroid Build Coastguard Worker void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
3077*795d594fSAndroid Build Coastguard Worker REQUIRES_SHARED(Locks::mutator_lock_) {
3078*795d594fSAndroid Build Coastguard Worker if (verify_referent_) {
3079*795d594fSAndroid Build Coastguard Worker VerifyReference(ref.Ptr(), ref->GetReferent(), mirror::Reference::ReferentOffset());
3080*795d594fSAndroid Build Coastguard Worker }
3081*795d594fSAndroid Build Coastguard Worker }
3082*795d594fSAndroid Build Coastguard Worker
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static) const3083*795d594fSAndroid Build Coastguard Worker void operator()(ObjPtr<mirror::Object> obj,
3084*795d594fSAndroid Build Coastguard Worker MemberOffset offset,
3085*795d594fSAndroid Build Coastguard Worker [[maybe_unused]] bool is_static) const REQUIRES_SHARED(Locks::mutator_lock_) {
3086*795d594fSAndroid Build Coastguard Worker VerifyReference(obj.Ptr(), obj->GetFieldObject<mirror::Object>(offset), offset);
3087*795d594fSAndroid Build Coastguard Worker }
3088*795d594fSAndroid Build Coastguard Worker
IsLive(ObjPtr<mirror::Object> obj) const3089*795d594fSAndroid Build Coastguard Worker bool IsLive(ObjPtr<mirror::Object> obj) const NO_THREAD_SAFETY_ANALYSIS {
3090*795d594fSAndroid Build Coastguard Worker return heap_->IsLiveObjectLocked(obj, true, false, true);
3091*795d594fSAndroid Build Coastguard Worker }
3092*795d594fSAndroid Build Coastguard Worker
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const3093*795d594fSAndroid Build Coastguard Worker void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
3094*795d594fSAndroid Build Coastguard Worker REQUIRES_SHARED(Locks::mutator_lock_) {
3095*795d594fSAndroid Build Coastguard Worker if (!root->IsNull()) {
3096*795d594fSAndroid Build Coastguard Worker VisitRoot(root);
3097*795d594fSAndroid Build Coastguard Worker }
3098*795d594fSAndroid Build Coastguard Worker }
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const3099*795d594fSAndroid Build Coastguard Worker void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
3100*795d594fSAndroid Build Coastguard Worker REQUIRES_SHARED(Locks::mutator_lock_) {
3101*795d594fSAndroid Build Coastguard Worker const_cast<VerifyReferenceVisitor*>(this)->VisitRoot(
3102*795d594fSAndroid Build Coastguard Worker root->AsMirrorPtr(), RootInfo(kRootVMInternal));
3103*795d594fSAndroid Build Coastguard Worker }
3104*795d594fSAndroid Build Coastguard Worker
VisitRoot(mirror::Object * root,const RootInfo & root_info)3105*795d594fSAndroid Build Coastguard Worker void VisitRoot(mirror::Object* root, const RootInfo& root_info) override
3106*795d594fSAndroid Build Coastguard Worker REQUIRES_SHARED(Locks::mutator_lock_) {
3107*795d594fSAndroid Build Coastguard Worker if (root == nullptr) {
3108*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Root is null with info " << root_info.GetType();
3109*795d594fSAndroid Build Coastguard Worker } else if (!VerifyReference(nullptr, root, MemberOffset(0))) {
3110*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Root " << root << " is dead with type " << mirror::Object::PrettyTypeOf(root)
3111*795d594fSAndroid Build Coastguard Worker << " thread_id= " << root_info.GetThreadId() << " root_type= " << root_info.GetType();
3112*795d594fSAndroid Build Coastguard Worker }
3113*795d594fSAndroid Build Coastguard Worker }
3114*795d594fSAndroid Build Coastguard Worker
3115*795d594fSAndroid Build Coastguard Worker private:
3116*795d594fSAndroid Build Coastguard Worker // TODO: Fix the no thread safety analysis.
3117*795d594fSAndroid Build Coastguard Worker // Returns false on failure.
VerifyReference(mirror::Object * obj,mirror::Object * ref,MemberOffset offset) const3118*795d594fSAndroid Build Coastguard Worker bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
3119*795d594fSAndroid Build Coastguard Worker NO_THREAD_SAFETY_ANALYSIS {
3120*795d594fSAndroid Build Coastguard Worker if (ref == nullptr || IsLive(ref)) {
3121*795d594fSAndroid Build Coastguard Worker // Verify that the reference is live.
3122*795d594fSAndroid Build Coastguard Worker return true;
3123*795d594fSAndroid Build Coastguard Worker }
3124*795d594fSAndroid Build Coastguard Worker CHECK_EQ(self_, Thread::Current()); // fail_count_ is private to the calling thread.
3125*795d594fSAndroid Build Coastguard Worker *fail_count_ += 1;
3126*795d594fSAndroid Build Coastguard Worker if (*fail_count_ == 1) {
3127*795d594fSAndroid Build Coastguard Worker // Only print message for the first failure to prevent spam.
3128*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
3129*795d594fSAndroid Build Coastguard Worker }
3130*795d594fSAndroid Build Coastguard Worker if (obj != nullptr) {
3131*795d594fSAndroid Build Coastguard Worker // Only do this part for non roots.
3132*795d594fSAndroid Build Coastguard Worker accounting::CardTable* card_table = heap_->GetCardTable();
3133*795d594fSAndroid Build Coastguard Worker accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
3134*795d594fSAndroid Build Coastguard Worker accounting::ObjectStack* live_stack = heap_->live_stack_.get();
3135*795d594fSAndroid Build Coastguard Worker uint8_t* card_addr = card_table->CardFromAddr(obj);
3136*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
3137*795d594fSAndroid Build Coastguard Worker << offset << "\n card value = " << static_cast<int>(*card_addr);
3138*795d594fSAndroid Build Coastguard Worker if (heap_->IsValidObjectAddress(obj->GetClass())) {
3139*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Obj type " << obj->PrettyTypeOf();
3140*795d594fSAndroid Build Coastguard Worker } else {
3141*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
3142*795d594fSAndroid Build Coastguard Worker }
3143*795d594fSAndroid Build Coastguard Worker
3144*795d594fSAndroid Build Coastguard Worker // Attempt to find the class inside of the recently freed objects.
3145*795d594fSAndroid Build Coastguard Worker space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
3146*795d594fSAndroid Build Coastguard Worker if (ref_space != nullptr && ref_space->IsMallocSpace()) {
3147*795d594fSAndroid Build Coastguard Worker space::MallocSpace* space = ref_space->AsMallocSpace();
3148*795d594fSAndroid Build Coastguard Worker mirror::Class* ref_class = space->FindRecentFreedObject(ref);
3149*795d594fSAndroid Build Coastguard Worker if (ref_class != nullptr) {
3150*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
3151*795d594fSAndroid Build Coastguard Worker << ref_class->PrettyClass();
3152*795d594fSAndroid Build Coastguard Worker } else {
3153*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
3154*795d594fSAndroid Build Coastguard Worker }
3155*795d594fSAndroid Build Coastguard Worker }
3156*795d594fSAndroid Build Coastguard Worker
3157*795d594fSAndroid Build Coastguard Worker if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
3158*795d594fSAndroid Build Coastguard Worker ref->GetClass()->IsClass()) {
3159*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Ref type " << ref->PrettyTypeOf();
3160*795d594fSAndroid Build Coastguard Worker } else {
3161*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
3162*795d594fSAndroid Build Coastguard Worker << ") is not a valid heap address";
3163*795d594fSAndroid Build Coastguard Worker }
3164*795d594fSAndroid Build Coastguard Worker
3165*795d594fSAndroid Build Coastguard Worker card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
3166*795d594fSAndroid Build Coastguard Worker void* cover_begin = card_table->AddrFromCard(card_addr);
3167*795d594fSAndroid Build Coastguard Worker void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
3168*795d594fSAndroid Build Coastguard Worker accounting::CardTable::kCardSize);
3169*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
3170*795d594fSAndroid Build Coastguard Worker << "-" << cover_end;
3171*795d594fSAndroid Build Coastguard Worker accounting::ContinuousSpaceBitmap* bitmap =
3172*795d594fSAndroid Build Coastguard Worker heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
3173*795d594fSAndroid Build Coastguard Worker
3174*795d594fSAndroid Build Coastguard Worker if (bitmap == nullptr) {
3175*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " has no bitmap";
3176*795d594fSAndroid Build Coastguard Worker if (!VerifyClassClass(obj->GetClass())) {
3177*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " failed class verification!";
3178*795d594fSAndroid Build Coastguard Worker }
3179*795d594fSAndroid Build Coastguard Worker } else {
3180*795d594fSAndroid Build Coastguard Worker // Print out how the object is live.
3181*795d594fSAndroid Build Coastguard Worker if (bitmap->Test(obj)) {
3182*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " found in live bitmap";
3183*795d594fSAndroid Build Coastguard Worker }
3184*795d594fSAndroid Build Coastguard Worker if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
3185*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " found in allocation stack";
3186*795d594fSAndroid Build Coastguard Worker }
3187*795d594fSAndroid Build Coastguard Worker if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
3188*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " found in live stack";
3189*795d594fSAndroid Build Coastguard Worker }
3190*795d594fSAndroid Build Coastguard Worker if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
3191*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Ref " << ref << " found in allocation stack";
3192*795d594fSAndroid Build Coastguard Worker }
3193*795d594fSAndroid Build Coastguard Worker if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
3194*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Ref " << ref << " found in live stack";
3195*795d594fSAndroid Build Coastguard Worker }
3196*795d594fSAndroid Build Coastguard Worker // Attempt to see if the card table missed the reference.
3197*795d594fSAndroid Build Coastguard Worker ScanVisitor scan_visitor;
3198*795d594fSAndroid Build Coastguard Worker uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
3199*795d594fSAndroid Build Coastguard Worker card_table->Scan<false>(bitmap, byte_cover_begin,
3200*795d594fSAndroid Build Coastguard Worker byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
3201*795d594fSAndroid Build Coastguard Worker }
3202*795d594fSAndroid Build Coastguard Worker
3203*795d594fSAndroid Build Coastguard Worker // Search to see if any of the roots reference our object.
3204*795d594fSAndroid Build Coastguard Worker RootMatchesObjectVisitor visitor1(obj);
3205*795d594fSAndroid Build Coastguard Worker Runtime::Current()->VisitRoots(&visitor1);
3206*795d594fSAndroid Build Coastguard Worker // Search to see if any of the roots reference our reference.
3207*795d594fSAndroid Build Coastguard Worker RootMatchesObjectVisitor visitor2(ref);
3208*795d594fSAndroid Build Coastguard Worker Runtime::Current()->VisitRoots(&visitor2);
3209*795d594fSAndroid Build Coastguard Worker }
3210*795d594fSAndroid Build Coastguard Worker return false;
3211*795d594fSAndroid Build Coastguard Worker }
3212*795d594fSAndroid Build Coastguard Worker
3213*795d594fSAndroid Build Coastguard Worker Thread* const self_;
3214*795d594fSAndroid Build Coastguard Worker Heap* const heap_;
3215*795d594fSAndroid Build Coastguard Worker size_t* const fail_count_;
3216*795d594fSAndroid Build Coastguard Worker const bool verify_referent_;
3217*795d594fSAndroid Build Coastguard Worker };
3218*795d594fSAndroid Build Coastguard Worker
3219*795d594fSAndroid Build Coastguard Worker // Verify all references within an object, for use with HeapBitmap::Visit.
3220*795d594fSAndroid Build Coastguard Worker class VerifyObjectVisitor {
3221*795d594fSAndroid Build Coastguard Worker public:
VerifyObjectVisitor(Thread * self,Heap * heap,size_t * fail_count,bool verify_referent)3222*795d594fSAndroid Build Coastguard Worker VerifyObjectVisitor(Thread* self, Heap* heap, size_t* fail_count, bool verify_referent)
3223*795d594fSAndroid Build Coastguard Worker : self_(self), heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
3224*795d594fSAndroid Build Coastguard Worker
operator ()(mirror::Object * obj)3225*795d594fSAndroid Build Coastguard Worker void operator()(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
3226*795d594fSAndroid Build Coastguard Worker // Note: we are verifying the references in obj but not obj itself, this is because obj must
3227*795d594fSAndroid Build Coastguard Worker // be live or else how did we find it in the live bitmap?
3228*795d594fSAndroid Build Coastguard Worker VerifyReferenceVisitor visitor(self_, heap_, fail_count_, verify_referent_);
3229*795d594fSAndroid Build Coastguard Worker // The class doesn't count as a reference but we should verify it anyways.
3230*795d594fSAndroid Build Coastguard Worker obj->VisitReferences(visitor, visitor);
3231*795d594fSAndroid Build Coastguard Worker }
3232*795d594fSAndroid Build Coastguard Worker
VerifyRoots()3233*795d594fSAndroid Build Coastguard Worker void VerifyRoots() REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!Locks::heap_bitmap_lock_) {
3234*795d594fSAndroid Build Coastguard Worker ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
3235*795d594fSAndroid Build Coastguard Worker VerifyReferenceVisitor visitor(self_, heap_, fail_count_, verify_referent_);
3236*795d594fSAndroid Build Coastguard Worker Runtime::Current()->VisitRoots(&visitor);
3237*795d594fSAndroid Build Coastguard Worker }
3238*795d594fSAndroid Build Coastguard Worker
GetFailureCount() const3239*795d594fSAndroid Build Coastguard Worker uint32_t GetFailureCount() const REQUIRES(Locks::mutator_lock_) {
3240*795d594fSAndroid Build Coastguard Worker CHECK_EQ(self_, Thread::Current());
3241*795d594fSAndroid Build Coastguard Worker return *fail_count_;
3242*795d594fSAndroid Build Coastguard Worker }
3243*795d594fSAndroid Build Coastguard Worker
3244*795d594fSAndroid Build Coastguard Worker private:
3245*795d594fSAndroid Build Coastguard Worker Thread* const self_;
3246*795d594fSAndroid Build Coastguard Worker Heap* const heap_;
3247*795d594fSAndroid Build Coastguard Worker size_t* const fail_count_;
3248*795d594fSAndroid Build Coastguard Worker const bool verify_referent_;
3249*795d594fSAndroid Build Coastguard Worker };
3250*795d594fSAndroid Build Coastguard Worker
PushOnAllocationStackWithInternalGC(Thread * self,ObjPtr<mirror::Object> * obj)3251*795d594fSAndroid Build Coastguard Worker void Heap::PushOnAllocationStackWithInternalGC(Thread* self, ObjPtr<mirror::Object>* obj) {
3252*795d594fSAndroid Build Coastguard Worker // Slow path, the allocation stack push back must have already failed.
3253*795d594fSAndroid Build Coastguard Worker DCHECK(!allocation_stack_->AtomicPushBack(obj->Ptr()));
3254*795d594fSAndroid Build Coastguard Worker do {
3255*795d594fSAndroid Build Coastguard Worker // TODO: Add handle VerifyObject.
3256*795d594fSAndroid Build Coastguard Worker StackHandleScope<1> hs(self);
3257*795d594fSAndroid Build Coastguard Worker HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
3258*795d594fSAndroid Build Coastguard Worker // Push our object into the reserve region of the allocation stack. This is only required due
3259*795d594fSAndroid Build Coastguard Worker // to heap verification requiring that roots are live (either in the live bitmap or in the
3260*795d594fSAndroid Build Coastguard Worker // allocation stack).
3261*795d594fSAndroid Build Coastguard Worker CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
3262*795d594fSAndroid Build Coastguard Worker CollectGarbageInternal(collector::kGcTypeSticky,
3263*795d594fSAndroid Build Coastguard Worker kGcCauseForAlloc,
3264*795d594fSAndroid Build Coastguard Worker false,
3265*795d594fSAndroid Build Coastguard Worker GetCurrentGcNum() + 1);
3266*795d594fSAndroid Build Coastguard Worker } while (!allocation_stack_->AtomicPushBack(obj->Ptr()));
3267*795d594fSAndroid Build Coastguard Worker }
3268*795d594fSAndroid Build Coastguard Worker
PushOnThreadLocalAllocationStackWithInternalGC(Thread * self,ObjPtr<mirror::Object> * obj)3269*795d594fSAndroid Build Coastguard Worker void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self,
3270*795d594fSAndroid Build Coastguard Worker ObjPtr<mirror::Object>* obj) {
3271*795d594fSAndroid Build Coastguard Worker // Slow path, the allocation stack push back must have already failed.
3272*795d594fSAndroid Build Coastguard Worker DCHECK(!self->PushOnThreadLocalAllocationStack(obj->Ptr()));
3273*795d594fSAndroid Build Coastguard Worker StackReference<mirror::Object>* start_address;
3274*795d594fSAndroid Build Coastguard Worker StackReference<mirror::Object>* end_address;
3275*795d594fSAndroid Build Coastguard Worker while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
3276*795d594fSAndroid Build Coastguard Worker &end_address)) {
3277*795d594fSAndroid Build Coastguard Worker // TODO: Add handle VerifyObject.
3278*795d594fSAndroid Build Coastguard Worker StackHandleScope<1> hs(self);
3279*795d594fSAndroid Build Coastguard Worker HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
3280*795d594fSAndroid Build Coastguard Worker // Push our object into the reserve region of the allocaiton stack. This is only required due
3281*795d594fSAndroid Build Coastguard Worker // to heap verification requiring that roots are live (either in the live bitmap or in the
3282*795d594fSAndroid Build Coastguard Worker // allocation stack).
3283*795d594fSAndroid Build Coastguard Worker CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
3284*795d594fSAndroid Build Coastguard Worker // Push into the reserve allocation stack.
3285*795d594fSAndroid Build Coastguard Worker CollectGarbageInternal(collector::kGcTypeSticky,
3286*795d594fSAndroid Build Coastguard Worker kGcCauseForAlloc,
3287*795d594fSAndroid Build Coastguard Worker false,
3288*795d594fSAndroid Build Coastguard Worker GetCurrentGcNum() + 1);
3289*795d594fSAndroid Build Coastguard Worker }
3290*795d594fSAndroid Build Coastguard Worker self->SetThreadLocalAllocationStack(start_address, end_address);
3291*795d594fSAndroid Build Coastguard Worker // Retry on the new thread-local allocation stack.
3292*795d594fSAndroid Build Coastguard Worker CHECK(self->PushOnThreadLocalAllocationStack(obj->Ptr())); // Must succeed.
3293*795d594fSAndroid Build Coastguard Worker }
3294*795d594fSAndroid Build Coastguard Worker
3295*795d594fSAndroid Build Coastguard Worker // Must do this with mutators suspended since we are directly accessing the allocation stacks.
VerifyHeapReferences(bool verify_referents)3296*795d594fSAndroid Build Coastguard Worker size_t Heap::VerifyHeapReferences(bool verify_referents) {
3297*795d594fSAndroid Build Coastguard Worker Thread* self = Thread::Current();
3298*795d594fSAndroid Build Coastguard Worker Locks::mutator_lock_->AssertExclusiveHeld(self);
3299*795d594fSAndroid Build Coastguard Worker // Lets sort our allocation stacks so that we can efficiently binary search them.
3300*795d594fSAndroid Build Coastguard Worker allocation_stack_->Sort();
3301*795d594fSAndroid Build Coastguard Worker live_stack_->Sort();
3302*795d594fSAndroid Build Coastguard Worker // Since we sorted the allocation stack content, need to revoke all
3303*795d594fSAndroid Build Coastguard Worker // thread-local allocation stacks.
3304*795d594fSAndroid Build Coastguard Worker RevokeAllThreadLocalAllocationStacks(self);
3305*795d594fSAndroid Build Coastguard Worker size_t fail_count = 0;
3306*795d594fSAndroid Build Coastguard Worker VerifyObjectVisitor visitor(self, this, &fail_count, verify_referents);
3307*795d594fSAndroid Build Coastguard Worker // Verify objects in the allocation stack since these will be objects which were:
3308*795d594fSAndroid Build Coastguard Worker // 1. Allocated prior to the GC (pre GC verification).
3309*795d594fSAndroid Build Coastguard Worker // 2. Allocated during the GC (pre sweep GC verification).
3310*795d594fSAndroid Build Coastguard Worker // We don't want to verify the objects in the live stack since they themselves may be
3311*795d594fSAndroid Build Coastguard Worker // pointing to dead objects if they are not reachable.
3312*795d594fSAndroid Build Coastguard Worker VisitObjectsPaused(visitor);
3313*795d594fSAndroid Build Coastguard Worker // Verify the roots:
3314*795d594fSAndroid Build Coastguard Worker visitor.VerifyRoots();
3315*795d594fSAndroid Build Coastguard Worker if (visitor.GetFailureCount() > 0) {
3316*795d594fSAndroid Build Coastguard Worker // Dump mod-union tables.
3317*795d594fSAndroid Build Coastguard Worker for (const auto& table_pair : mod_union_tables_) {
3318*795d594fSAndroid Build Coastguard Worker accounting::ModUnionTable* mod_union_table = table_pair.second;
3319*795d594fSAndroid Build Coastguard Worker mod_union_table->Dump(LOG_STREAM(ERROR) << mod_union_table->GetName() << ": ");
3320*795d594fSAndroid Build Coastguard Worker }
3321*795d594fSAndroid Build Coastguard Worker // Dump remembered sets.
3322*795d594fSAndroid Build Coastguard Worker for (const auto& table_pair : remembered_sets_) {
3323*795d594fSAndroid Build Coastguard Worker accounting::RememberedSet* remembered_set = table_pair.second;
3324*795d594fSAndroid Build Coastguard Worker remembered_set->Dump(LOG_STREAM(ERROR) << remembered_set->GetName() << ": ");
3325*795d594fSAndroid Build Coastguard Worker }
3326*795d594fSAndroid Build Coastguard Worker DumpSpaces(LOG_STREAM(ERROR));
3327*795d594fSAndroid Build Coastguard Worker }
3328*795d594fSAndroid Build Coastguard Worker return visitor.GetFailureCount();
3329*795d594fSAndroid Build Coastguard Worker }
3330*795d594fSAndroid Build Coastguard Worker
3331*795d594fSAndroid Build Coastguard Worker class VerifyReferenceCardVisitor {
3332*795d594fSAndroid Build Coastguard Worker public:
VerifyReferenceCardVisitor(Heap * heap,bool * failed)3333*795d594fSAndroid Build Coastguard Worker VerifyReferenceCardVisitor(Heap* heap, bool* failed)
3334*795d594fSAndroid Build Coastguard Worker REQUIRES_SHARED(Locks::mutator_lock_,
3335*795d594fSAndroid Build Coastguard Worker Locks::heap_bitmap_lock_)
3336*795d594fSAndroid Build Coastguard Worker : heap_(heap), failed_(failed) {
3337*795d594fSAndroid Build Coastguard Worker }
3338*795d594fSAndroid Build Coastguard Worker
3339*795d594fSAndroid Build Coastguard Worker // There is no card marks for native roots on a class.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const3340*795d594fSAndroid Build Coastguard Worker void VisitRootIfNonNull(
3341*795d594fSAndroid Build Coastguard Worker [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const3342*795d594fSAndroid Build Coastguard Worker void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
3343*795d594fSAndroid Build Coastguard Worker
3344*795d594fSAndroid Build Coastguard Worker // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
3345*795d594fSAndroid Build Coastguard Worker // annotalysis on visitors.
operator ()(mirror::Object * obj,MemberOffset offset,bool is_static) const3346*795d594fSAndroid Build Coastguard Worker void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
3347*795d594fSAndroid Build Coastguard Worker NO_THREAD_SAFETY_ANALYSIS {
3348*795d594fSAndroid Build Coastguard Worker mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
3349*795d594fSAndroid Build Coastguard Worker // Filter out class references since changing an object's class does not mark the card as dirty.
3350*795d594fSAndroid Build Coastguard Worker // Also handles large objects, since the only reference they hold is a class reference.
3351*795d594fSAndroid Build Coastguard Worker if (ref != nullptr && !ref->IsClass()) {
3352*795d594fSAndroid Build Coastguard Worker accounting::CardTable* card_table = heap_->GetCardTable();
3353*795d594fSAndroid Build Coastguard Worker // If the object is not dirty and it is referencing something in the live stack other than
3354*795d594fSAndroid Build Coastguard Worker // class, then it must be on a dirty card.
3355*795d594fSAndroid Build Coastguard Worker if (!card_table->AddrIsInCardTable(obj)) {
3356*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
3357*795d594fSAndroid Build Coastguard Worker *failed_ = true;
3358*795d594fSAndroid Build Coastguard Worker } else if (!card_table->IsDirty(obj)) {
3359*795d594fSAndroid Build Coastguard Worker // TODO: Check mod-union tables.
3360*795d594fSAndroid Build Coastguard Worker // Card should be either kCardDirty if it got re-dirtied after we aged it, or
3361*795d594fSAndroid Build Coastguard Worker // kCardDirty - 1 if it didnt get touched since we aged it.
3362*795d594fSAndroid Build Coastguard Worker accounting::ObjectStack* live_stack = heap_->live_stack_.get();
3363*795d594fSAndroid Build Coastguard Worker if (live_stack->ContainsSorted(ref)) {
3364*795d594fSAndroid Build Coastguard Worker if (live_stack->ContainsSorted(obj)) {
3365*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " found in live stack";
3366*795d594fSAndroid Build Coastguard Worker }
3367*795d594fSAndroid Build Coastguard Worker if (heap_->GetLiveBitmap()->Test(obj)) {
3368*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " found in live bitmap";
3369*795d594fSAndroid Build Coastguard Worker }
3370*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << "Object " << obj << " " << mirror::Object::PrettyTypeOf(obj)
3371*795d594fSAndroid Build Coastguard Worker << " references " << ref << " " << mirror::Object::PrettyTypeOf(ref)
3372*795d594fSAndroid Build Coastguard Worker << " in live stack";
3373*795d594fSAndroid Build Coastguard Worker
3374*795d594fSAndroid Build Coastguard Worker // Print which field of the object is dead.
3375*795d594fSAndroid Build Coastguard Worker if (!obj->IsObjectArray()) {
3376*795d594fSAndroid Build Coastguard Worker ObjPtr<mirror::Class> klass = is_static ? obj->AsClass() : obj->GetClass();
3377*795d594fSAndroid Build Coastguard Worker CHECK(klass != nullptr);
3378*795d594fSAndroid Build Coastguard Worker for (ArtField& field : (is_static ? klass->GetSFields() : klass->GetIFields())) {
3379*795d594fSAndroid Build Coastguard Worker if (field.GetOffset().Int32Value() == offset.Int32Value()) {
3380*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
3381*795d594fSAndroid Build Coastguard Worker << field.PrettyField();
3382*795d594fSAndroid Build Coastguard Worker break;
3383*795d594fSAndroid Build Coastguard Worker }
3384*795d594fSAndroid Build Coastguard Worker }
3385*795d594fSAndroid Build Coastguard Worker } else {
3386*795d594fSAndroid Build Coastguard Worker ObjPtr<mirror::ObjectArray<mirror::Object>> object_array =
3387*795d594fSAndroid Build Coastguard Worker obj->AsObjectArray<mirror::Object>();
3388*795d594fSAndroid Build Coastguard Worker for (int32_t i = 0; i < object_array->GetLength(); ++i) {
3389*795d594fSAndroid Build Coastguard Worker if (object_array->Get(i) == ref) {
3390*795d594fSAndroid Build Coastguard Worker LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
3391*795d594fSAndroid Build Coastguard Worker }
3392*795d594fSAndroid Build Coastguard Worker }
3393*795d594fSAndroid Build Coastguard Worker }
3394*795d594fSAndroid Build Coastguard Worker
3395*795d594fSAndroid Build Coastguard Worker *failed_ = true;
3396*795d594fSAndroid Build Coastguard Worker }
3397*795d594fSAndroid Build Coastguard Worker }
3398*795d594fSAndroid Build Coastguard Worker }
3399*795d594fSAndroid Build Coastguard Worker }
3400*795d594fSAndroid Build Coastguard Worker
3401*795d594fSAndroid Build Coastguard Worker private:
3402*795d594fSAndroid Build Coastguard Worker Heap* const heap_;
3403*795d594fSAndroid Build Coastguard Worker bool* const failed_;
3404*795d594fSAndroid Build Coastguard Worker };
3405*795d594fSAndroid Build Coastguard Worker
3406*795d594fSAndroid Build Coastguard Worker class VerifyLiveStackReferences {
3407*795d594fSAndroid Build Coastguard Worker public:
VerifyLiveStackReferences(Heap * heap)3408*795d594fSAndroid Build Coastguard Worker explicit VerifyLiveStackReferences(Heap* heap)
3409*795d594fSAndroid Build Coastguard Worker : heap_(heap),
3410*795d594fSAndroid Build Coastguard Worker failed_(false) {}
3411*795d594fSAndroid Build Coastguard Worker
operator ()(mirror::Object * obj) const3412*795d594fSAndroid Build Coastguard Worker void operator()(mirror::Object* obj) const
3413*795d594fSAndroid Build Coastguard Worker REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
3414*795d594fSAndroid Build Coastguard Worker VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
3415*795d594fSAndroid Build Coastguard Worker obj->VisitReferences(visitor, VoidFunctor());
3416*795d594fSAndroid Build Coastguard Worker }
3417*795d594fSAndroid Build Coastguard Worker
Failed() const3418*795d594fSAndroid Build Coastguard Worker bool Failed() const {
3419*795d594fSAndroid Build Coastguard Worker return failed_;
3420*795d594fSAndroid Build Coastguard Worker }
3421*795d594fSAndroid Build Coastguard Worker
3422*795d594fSAndroid Build Coastguard Worker private:
3423*795d594fSAndroid Build Coastguard Worker Heap* const heap_;
3424*795d594fSAndroid Build Coastguard Worker bool failed_;
3425*795d594fSAndroid Build Coastguard Worker };
3426*795d594fSAndroid Build Coastguard Worker
VerifyMissingCardMarks()3427*795d594fSAndroid Build Coastguard Worker bool Heap::VerifyMissingCardMarks() {
3428*795d594fSAndroid Build Coastguard Worker Thread* self = Thread::Current();
3429*795d594fSAndroid Build Coastguard Worker Locks::mutator_lock_->AssertExclusiveHeld(self);
3430*795d594fSAndroid Build Coastguard Worker // We need to sort the live stack since we binary search it.
3431*795d594fSAndroid Build Coastguard Worker live_stack_->Sort();
3432*795d594fSAndroid Build Coastguard Worker // Since we sorted the allocation stack content, need to revoke all
3433*795d594fSAndroid Build Coastguard Worker // thread-local allocation stacks.
3434*795d594fSAndroid Build Coastguard Worker RevokeAllThreadLocalAllocationStacks(self);
3435*795d594fSAndroid Build Coastguard Worker VerifyLiveStackReferences visitor(this);
3436*795d594fSAndroid Build Coastguard Worker GetLiveBitmap()->Visit(visitor);
3437*795d594fSAndroid Build Coastguard Worker // We can verify objects in the live stack since none of these should reference dead objects.
3438*795d594fSAndroid Build Coastguard Worker for (auto* it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
3439*795d594fSAndroid Build Coastguard Worker if (!kUseThreadLocalAllocationStack || it->AsMirrorPtr() != nullptr) {
3440*795d594fSAndroid Build Coastguard Worker visitor(it->AsMirrorPtr());
3441*795d594fSAndroid Build Coastguard Worker }
3442*795d594fSAndroid Build Coastguard Worker }
3443*795d594fSAndroid Build Coastguard Worker return !visitor.Failed();
3444*795d594fSAndroid Build Coastguard Worker }
3445*795d594fSAndroid Build Coastguard Worker
SwapStacks()3446*795d594fSAndroid Build Coastguard Worker void Heap::SwapStacks() {
3447*795d594fSAndroid Build Coastguard Worker if (kUseThreadLocalAllocationStack) {
3448*795d594fSAndroid Build Coastguard Worker live_stack_->AssertAllZero();
3449*795d594fSAndroid Build Coastguard Worker }
3450*795d594fSAndroid Build Coastguard Worker allocation_stack_.swap(live_stack_);
3451*795d594fSAndroid Build Coastguard Worker }
3452*795d594fSAndroid Build Coastguard Worker
RevokeAllThreadLocalAllocationStacks(Thread * self)3453*795d594fSAndroid Build Coastguard Worker void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
3454*795d594fSAndroid Build Coastguard Worker // This must be called only during the pause.
3455*795d594fSAndroid Build Coastguard Worker DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
3456*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *Locks::runtime_shutdown_lock_);
3457*795d594fSAndroid Build Coastguard Worker MutexLock mu2(self, *Locks::thread_list_lock_);
3458*795d594fSAndroid Build Coastguard Worker std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
3459*795d594fSAndroid Build Coastguard Worker for (Thread* t : thread_list) {
3460*795d594fSAndroid Build Coastguard Worker t->RevokeThreadLocalAllocationStack();
3461*795d594fSAndroid Build Coastguard Worker }
3462*795d594fSAndroid Build Coastguard Worker }
3463*795d594fSAndroid Build Coastguard Worker
AssertThreadLocalBuffersAreRevoked(Thread * thread)3464*795d594fSAndroid Build Coastguard Worker void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
3465*795d594fSAndroid Build Coastguard Worker if (kIsDebugBuild) {
3466*795d594fSAndroid Build Coastguard Worker if (rosalloc_space_ != nullptr) {
3467*795d594fSAndroid Build Coastguard Worker rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
3468*795d594fSAndroid Build Coastguard Worker }
3469*795d594fSAndroid Build Coastguard Worker if (bump_pointer_space_ != nullptr) {
3470*795d594fSAndroid Build Coastguard Worker bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
3471*795d594fSAndroid Build Coastguard Worker }
3472*795d594fSAndroid Build Coastguard Worker }
3473*795d594fSAndroid Build Coastguard Worker }
3474*795d594fSAndroid Build Coastguard Worker
AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked()3475*795d594fSAndroid Build Coastguard Worker void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
3476*795d594fSAndroid Build Coastguard Worker if (kIsDebugBuild) {
3477*795d594fSAndroid Build Coastguard Worker if (bump_pointer_space_ != nullptr) {
3478*795d594fSAndroid Build Coastguard Worker bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
3479*795d594fSAndroid Build Coastguard Worker }
3480*795d594fSAndroid Build Coastguard Worker }
3481*795d594fSAndroid Build Coastguard Worker }
3482*795d594fSAndroid Build Coastguard Worker
FindModUnionTableFromSpace(space::Space * space)3483*795d594fSAndroid Build Coastguard Worker accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
3484*795d594fSAndroid Build Coastguard Worker auto it = mod_union_tables_.find(space);
3485*795d594fSAndroid Build Coastguard Worker if (it == mod_union_tables_.end()) {
3486*795d594fSAndroid Build Coastguard Worker return nullptr;
3487*795d594fSAndroid Build Coastguard Worker }
3488*795d594fSAndroid Build Coastguard Worker return it->second;
3489*795d594fSAndroid Build Coastguard Worker }
3490*795d594fSAndroid Build Coastguard Worker
FindRememberedSetFromSpace(space::Space * space)3491*795d594fSAndroid Build Coastguard Worker accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
3492*795d594fSAndroid Build Coastguard Worker auto it = remembered_sets_.find(space);
3493*795d594fSAndroid Build Coastguard Worker if (it == remembered_sets_.end()) {
3494*795d594fSAndroid Build Coastguard Worker return nullptr;
3495*795d594fSAndroid Build Coastguard Worker }
3496*795d594fSAndroid Build Coastguard Worker return it->second;
3497*795d594fSAndroid Build Coastguard Worker }
3498*795d594fSAndroid Build Coastguard Worker
ProcessCards(TimingLogger * timings,bool use_rem_sets,bool process_alloc_space_cards,bool clear_alloc_space_cards)3499*795d594fSAndroid Build Coastguard Worker void Heap::ProcessCards(TimingLogger* timings,
3500*795d594fSAndroid Build Coastguard Worker bool use_rem_sets,
3501*795d594fSAndroid Build Coastguard Worker bool process_alloc_space_cards,
3502*795d594fSAndroid Build Coastguard Worker bool clear_alloc_space_cards) {
3503*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t(__FUNCTION__, timings);
3504*795d594fSAndroid Build Coastguard Worker // Clear cards and keep track of cards cleared in the mod-union table.
3505*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
3506*795d594fSAndroid Build Coastguard Worker accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
3507*795d594fSAndroid Build Coastguard Worker accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
3508*795d594fSAndroid Build Coastguard Worker if (table != nullptr) {
3509*795d594fSAndroid Build Coastguard Worker const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
3510*795d594fSAndroid Build Coastguard Worker "ImageModUnionClearCards";
3511*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t2(name, timings);
3512*795d594fSAndroid Build Coastguard Worker table->ProcessCards();
3513*795d594fSAndroid Build Coastguard Worker } else if (use_rem_sets && rem_set != nullptr) {
3514*795d594fSAndroid Build Coastguard Worker DCHECK(collector::SemiSpace::kUseRememberedSet) << static_cast<int>(collector_type_);
3515*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t2("AllocSpaceRemSetClearCards", timings);
3516*795d594fSAndroid Build Coastguard Worker rem_set->ClearCards();
3517*795d594fSAndroid Build Coastguard Worker } else if (process_alloc_space_cards) {
3518*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t2("AllocSpaceClearCards", timings);
3519*795d594fSAndroid Build Coastguard Worker if (clear_alloc_space_cards) {
3520*795d594fSAndroid Build Coastguard Worker uint8_t* end = space->End();
3521*795d594fSAndroid Build Coastguard Worker if (space->IsImageSpace()) {
3522*795d594fSAndroid Build Coastguard Worker // Image space end is the end of the mirror objects, it is not necessarily page or card
3523*795d594fSAndroid Build Coastguard Worker // aligned. Align up so that the check in ClearCardRange does not fail.
3524*795d594fSAndroid Build Coastguard Worker end = AlignUp(end, accounting::CardTable::kCardSize);
3525*795d594fSAndroid Build Coastguard Worker }
3526*795d594fSAndroid Build Coastguard Worker card_table_->ClearCardRange(space->Begin(), end);
3527*795d594fSAndroid Build Coastguard Worker } else {
3528*795d594fSAndroid Build Coastguard Worker // No mod union table for the AllocSpace. Age the cards so that the GC knows that these
3529*795d594fSAndroid Build Coastguard Worker // cards were dirty before the GC started.
3530*795d594fSAndroid Build Coastguard Worker // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
3531*795d594fSAndroid Build Coastguard Worker // -> clean(cleaning thread).
3532*795d594fSAndroid Build Coastguard Worker // The races are we either end up with: Aged card, unaged card. Since we have the
3533*795d594fSAndroid Build Coastguard Worker // checkpoint roots and then we scan / update mod union tables after. We will always
3534*795d594fSAndroid Build Coastguard Worker // scan either card. If we end up with the non aged card, we scan it it in the pause.
3535*795d594fSAndroid Build Coastguard Worker card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
3536*795d594fSAndroid Build Coastguard Worker VoidFunctor());
3537*795d594fSAndroid Build Coastguard Worker }
3538*795d594fSAndroid Build Coastguard Worker }
3539*795d594fSAndroid Build Coastguard Worker }
3540*795d594fSAndroid Build Coastguard Worker }
3541*795d594fSAndroid Build Coastguard Worker
3542*795d594fSAndroid Build Coastguard Worker struct IdentityMarkHeapReferenceVisitor : public MarkObjectVisitor {
MarkObjectart::gc::IdentityMarkHeapReferenceVisitor3543*795d594fSAndroid Build Coastguard Worker mirror::Object* MarkObject(mirror::Object* obj) override {
3544*795d594fSAndroid Build Coastguard Worker return obj;
3545*795d594fSAndroid Build Coastguard Worker }
MarkHeapReferenceart::gc::IdentityMarkHeapReferenceVisitor3546*795d594fSAndroid Build Coastguard Worker void MarkHeapReference(mirror::HeapReference<mirror::Object>*, bool) override {
3547*795d594fSAndroid Build Coastguard Worker }
3548*795d594fSAndroid Build Coastguard Worker };
3549*795d594fSAndroid Build Coastguard Worker
PreGcVerificationPaused(collector::GarbageCollector * gc)3550*795d594fSAndroid Build Coastguard Worker void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
3551*795d594fSAndroid Build Coastguard Worker Thread* const self = Thread::Current();
3552*795d594fSAndroid Build Coastguard Worker TimingLogger* const timings = current_gc_iteration_.GetTimings();
3553*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t(__FUNCTION__, timings);
3554*795d594fSAndroid Build Coastguard Worker if (verify_pre_gc_heap_) {
3555*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyHeapReferences", timings);
3556*795d594fSAndroid Build Coastguard Worker size_t failures = VerifyHeapReferences();
3557*795d594fSAndroid Build Coastguard Worker if (failures > 0) {
3558*795d594fSAndroid Build Coastguard Worker LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3559*795d594fSAndroid Build Coastguard Worker << " failures";
3560*795d594fSAndroid Build Coastguard Worker }
3561*795d594fSAndroid Build Coastguard Worker }
3562*795d594fSAndroid Build Coastguard Worker // Check that all objects which reference things in the live stack are on dirty cards.
3563*795d594fSAndroid Build Coastguard Worker if (verify_missing_card_marks_) {
3564*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyMissingCardMarks", timings);
3565*795d594fSAndroid Build Coastguard Worker ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
3566*795d594fSAndroid Build Coastguard Worker SwapStacks();
3567*795d594fSAndroid Build Coastguard Worker // Sort the live stack so that we can quickly binary search it later.
3568*795d594fSAndroid Build Coastguard Worker CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
3569*795d594fSAndroid Build Coastguard Worker << " missing card mark verification failed\n" << DumpSpaces();
3570*795d594fSAndroid Build Coastguard Worker SwapStacks();
3571*795d594fSAndroid Build Coastguard Worker }
3572*795d594fSAndroid Build Coastguard Worker if (verify_mod_union_table_) {
3573*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyModUnionTables", timings);
3574*795d594fSAndroid Build Coastguard Worker ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
3575*795d594fSAndroid Build Coastguard Worker for (const auto& table_pair : mod_union_tables_) {
3576*795d594fSAndroid Build Coastguard Worker accounting::ModUnionTable* mod_union_table = table_pair.second;
3577*795d594fSAndroid Build Coastguard Worker IdentityMarkHeapReferenceVisitor visitor;
3578*795d594fSAndroid Build Coastguard Worker mod_union_table->UpdateAndMarkReferences(&visitor);
3579*795d594fSAndroid Build Coastguard Worker mod_union_table->Verify();
3580*795d594fSAndroid Build Coastguard Worker }
3581*795d594fSAndroid Build Coastguard Worker }
3582*795d594fSAndroid Build Coastguard Worker }
3583*795d594fSAndroid Build Coastguard Worker
PreGcVerification(collector::GarbageCollector * gc)3584*795d594fSAndroid Build Coastguard Worker void Heap::PreGcVerification(collector::GarbageCollector* gc) {
3585*795d594fSAndroid Build Coastguard Worker if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
3586*795d594fSAndroid Build Coastguard Worker collector::GarbageCollector::ScopedPause pause(gc, false);
3587*795d594fSAndroid Build Coastguard Worker PreGcVerificationPaused(gc);
3588*795d594fSAndroid Build Coastguard Worker }
3589*795d594fSAndroid Build Coastguard Worker }
3590*795d594fSAndroid Build Coastguard Worker
PrePauseRosAllocVerification(collector::GarbageCollector * gc)3591*795d594fSAndroid Build Coastguard Worker void Heap::PrePauseRosAllocVerification([[maybe_unused]] collector::GarbageCollector* gc) {
3592*795d594fSAndroid Build Coastguard Worker // TODO: Add a new runtime option for this?
3593*795d594fSAndroid Build Coastguard Worker if (verify_pre_gc_rosalloc_) {
3594*795d594fSAndroid Build Coastguard Worker RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
3595*795d594fSAndroid Build Coastguard Worker }
3596*795d594fSAndroid Build Coastguard Worker }
3597*795d594fSAndroid Build Coastguard Worker
PreSweepingGcVerification(collector::GarbageCollector * gc)3598*795d594fSAndroid Build Coastguard Worker void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
3599*795d594fSAndroid Build Coastguard Worker Thread* const self = Thread::Current();
3600*795d594fSAndroid Build Coastguard Worker TimingLogger* const timings = current_gc_iteration_.GetTimings();
3601*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t(__FUNCTION__, timings);
3602*795d594fSAndroid Build Coastguard Worker // Called before sweeping occurs since we want to make sure we are not going so reclaim any
3603*795d594fSAndroid Build Coastguard Worker // reachable objects.
3604*795d594fSAndroid Build Coastguard Worker if (verify_pre_sweeping_heap_) {
3605*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t2("(Paused)PostSweepingVerifyHeapReferences", timings);
3606*795d594fSAndroid Build Coastguard Worker CHECK_NE(self->GetState(), ThreadState::kRunnable);
3607*795d594fSAndroid Build Coastguard Worker {
3608*795d594fSAndroid Build Coastguard Worker WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3609*795d594fSAndroid Build Coastguard Worker // Swapping bound bitmaps does nothing.
3610*795d594fSAndroid Build Coastguard Worker gc->SwapBitmaps();
3611*795d594fSAndroid Build Coastguard Worker }
3612*795d594fSAndroid Build Coastguard Worker // Pass in false since concurrent reference processing can mean that the reference referents
3613*795d594fSAndroid Build Coastguard Worker // may point to dead objects at the point which PreSweepingGcVerification is called.
3614*795d594fSAndroid Build Coastguard Worker size_t failures = VerifyHeapReferences(false);
3615*795d594fSAndroid Build Coastguard Worker if (failures > 0) {
3616*795d594fSAndroid Build Coastguard Worker LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
3617*795d594fSAndroid Build Coastguard Worker << " failures";
3618*795d594fSAndroid Build Coastguard Worker }
3619*795d594fSAndroid Build Coastguard Worker {
3620*795d594fSAndroid Build Coastguard Worker WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3621*795d594fSAndroid Build Coastguard Worker gc->SwapBitmaps();
3622*795d594fSAndroid Build Coastguard Worker }
3623*795d594fSAndroid Build Coastguard Worker }
3624*795d594fSAndroid Build Coastguard Worker if (verify_pre_sweeping_rosalloc_) {
3625*795d594fSAndroid Build Coastguard Worker RosAllocVerification(timings, "PreSweepingRosAllocVerification");
3626*795d594fSAndroid Build Coastguard Worker }
3627*795d594fSAndroid Build Coastguard Worker }
3628*795d594fSAndroid Build Coastguard Worker
PostGcVerificationPaused(collector::GarbageCollector * gc)3629*795d594fSAndroid Build Coastguard Worker void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
3630*795d594fSAndroid Build Coastguard Worker // Only pause if we have to do some verification.
3631*795d594fSAndroid Build Coastguard Worker Thread* const self = Thread::Current();
3632*795d594fSAndroid Build Coastguard Worker TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
3633*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t(__FUNCTION__, timings);
3634*795d594fSAndroid Build Coastguard Worker if (verify_system_weaks_) {
3635*795d594fSAndroid Build Coastguard Worker ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3636*795d594fSAndroid Build Coastguard Worker collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
3637*795d594fSAndroid Build Coastguard Worker mark_sweep->VerifySystemWeaks();
3638*795d594fSAndroid Build Coastguard Worker }
3639*795d594fSAndroid Build Coastguard Worker if (verify_post_gc_rosalloc_) {
3640*795d594fSAndroid Build Coastguard Worker RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
3641*795d594fSAndroid Build Coastguard Worker }
3642*795d594fSAndroid Build Coastguard Worker if (verify_post_gc_heap_) {
3643*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t2("(Paused)PostGcVerifyHeapReferences", timings);
3644*795d594fSAndroid Build Coastguard Worker size_t failures = VerifyHeapReferences();
3645*795d594fSAndroid Build Coastguard Worker if (failures > 0) {
3646*795d594fSAndroid Build Coastguard Worker LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3647*795d594fSAndroid Build Coastguard Worker << " failures";
3648*795d594fSAndroid Build Coastguard Worker }
3649*795d594fSAndroid Build Coastguard Worker }
3650*795d594fSAndroid Build Coastguard Worker }
3651*795d594fSAndroid Build Coastguard Worker
PostGcVerification(collector::GarbageCollector * gc)3652*795d594fSAndroid Build Coastguard Worker void Heap::PostGcVerification(collector::GarbageCollector* gc) {
3653*795d594fSAndroid Build Coastguard Worker if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
3654*795d594fSAndroid Build Coastguard Worker collector::GarbageCollector::ScopedPause pause(gc, false);
3655*795d594fSAndroid Build Coastguard Worker PostGcVerificationPaused(gc);
3656*795d594fSAndroid Build Coastguard Worker }
3657*795d594fSAndroid Build Coastguard Worker }
3658*795d594fSAndroid Build Coastguard Worker
RosAllocVerification(TimingLogger * timings,const char * name)3659*795d594fSAndroid Build Coastguard Worker void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
3660*795d594fSAndroid Build Coastguard Worker TimingLogger::ScopedTiming t(name, timings);
3661*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
3662*795d594fSAndroid Build Coastguard Worker if (space->IsRosAllocSpace()) {
3663*795d594fSAndroid Build Coastguard Worker VLOG(heap) << name << " : " << space->GetName();
3664*795d594fSAndroid Build Coastguard Worker space->AsRosAllocSpace()->Verify();
3665*795d594fSAndroid Build Coastguard Worker }
3666*795d594fSAndroid Build Coastguard Worker }
3667*795d594fSAndroid Build Coastguard Worker }
3668*795d594fSAndroid Build Coastguard Worker
WaitForGcToComplete(GcCause cause,Thread * self)3669*795d594fSAndroid Build Coastguard Worker collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
3670*795d594fSAndroid Build Coastguard Worker ScopedThreadStateChange tsc(self, ThreadState::kWaitingForGcToComplete);
3671*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *gc_complete_lock_);
3672*795d594fSAndroid Build Coastguard Worker return WaitForGcToCompleteLocked(cause, self, /* only_one= */ true);
3673*795d594fSAndroid Build Coastguard Worker }
3674*795d594fSAndroid Build Coastguard Worker
WaitForGcToCompleteLocked(GcCause cause,Thread * self,bool only_one)3675*795d594fSAndroid Build Coastguard Worker collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self, bool only_one) {
3676*795d594fSAndroid Build Coastguard Worker gc_complete_cond_->CheckSafeToWait(self);
3677*795d594fSAndroid Build Coastguard Worker collector::GcType last_gc_type = collector::kGcTypeNone;
3678*795d594fSAndroid Build Coastguard Worker GcCause last_gc_cause = kGcCauseNone;
3679*795d594fSAndroid Build Coastguard Worker if (collector_type_running_ != kCollectorTypeNone) {
3680*795d594fSAndroid Build Coastguard Worker uint64_t wait_start = NanoTime();
3681*795d594fSAndroid Build Coastguard Worker uint32_t starting_gc_num = GetCurrentGcNum();
3682*795d594fSAndroid Build Coastguard Worker while (collector_type_running_ != kCollectorTypeNone &&
3683*795d594fSAndroid Build Coastguard Worker (!only_one || GCNumberLt(GetCurrentGcNum(), starting_gc_num + 1))) {
3684*795d594fSAndroid Build Coastguard Worker if (!task_processor_->IsRunningThread(self)) {
3685*795d594fSAndroid Build Coastguard Worker // The current thread is about to wait for a currently running
3686*795d594fSAndroid Build Coastguard Worker // collection to finish. If the waiting thread is not the heap
3687*795d594fSAndroid Build Coastguard Worker // task daemon thread, the currently running collection is
3688*795d594fSAndroid Build Coastguard Worker // considered as a blocking GC.
3689*795d594fSAndroid Build Coastguard Worker running_collection_is_blocking_ = true;
3690*795d594fSAndroid Build Coastguard Worker VLOG(gc) << "Waiting for a blocking GC " << cause;
3691*795d594fSAndroid Build Coastguard Worker }
3692*795d594fSAndroid Build Coastguard Worker SCOPED_TRACE << "GC: Wait For Completion " << cause;
3693*795d594fSAndroid Build Coastguard Worker // We must wait, change thread state then sleep on gc_complete_cond_;
3694*795d594fSAndroid Build Coastguard Worker gc_complete_cond_->Wait(self);
3695*795d594fSAndroid Build Coastguard Worker last_gc_type = last_gc_type_;
3696*795d594fSAndroid Build Coastguard Worker last_gc_cause = last_gc_cause_;
3697*795d594fSAndroid Build Coastguard Worker }
3698*795d594fSAndroid Build Coastguard Worker uint64_t wait_time = NanoTime() - wait_start;
3699*795d594fSAndroid Build Coastguard Worker total_wait_time_ += wait_time;
3700*795d594fSAndroid Build Coastguard Worker if (wait_time > long_pause_log_threshold_) {
3701*795d594fSAndroid Build Coastguard Worker LOG(INFO) << "WaitForGcToComplete blocked " << cause << " on " << last_gc_cause << " for "
3702*795d594fSAndroid Build Coastguard Worker << PrettyDuration(wait_time);
3703*795d594fSAndroid Build Coastguard Worker }
3704*795d594fSAndroid Build Coastguard Worker }
3705*795d594fSAndroid Build Coastguard Worker if (!task_processor_->IsRunningThread(self)) {
3706*795d594fSAndroid Build Coastguard Worker // The current thread is about to run a collection. If the thread
3707*795d594fSAndroid Build Coastguard Worker // is not the heap task daemon thread, it's considered as a
3708*795d594fSAndroid Build Coastguard Worker // blocking GC (i.e., blocking itself).
3709*795d594fSAndroid Build Coastguard Worker running_collection_is_blocking_ = true;
3710*795d594fSAndroid Build Coastguard Worker }
3711*795d594fSAndroid Build Coastguard Worker DCHECK(only_one || collector_type_running_ == kCollectorTypeNone);
3712*795d594fSAndroid Build Coastguard Worker return last_gc_type;
3713*795d594fSAndroid Build Coastguard Worker }
3714*795d594fSAndroid Build Coastguard Worker
DumpForSigQuit(std::ostream & os)3715*795d594fSAndroid Build Coastguard Worker void Heap::DumpForSigQuit(std::ostream& os) {
3716*795d594fSAndroid Build Coastguard Worker os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
3717*795d594fSAndroid Build Coastguard Worker << PrettySize(GetTotalMemory()) << "\n";
3718*795d594fSAndroid Build Coastguard Worker {
3719*795d594fSAndroid Build Coastguard Worker os << "Image spaces:\n";
3720*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(Thread::Current());
3721*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
3722*795d594fSAndroid Build Coastguard Worker if (space->IsImageSpace()) {
3723*795d594fSAndroid Build Coastguard Worker os << space->GetName() << "\n";
3724*795d594fSAndroid Build Coastguard Worker }
3725*795d594fSAndroid Build Coastguard Worker }
3726*795d594fSAndroid Build Coastguard Worker }
3727*795d594fSAndroid Build Coastguard Worker DumpGcPerformanceInfo(os);
3728*795d594fSAndroid Build Coastguard Worker }
3729*795d594fSAndroid Build Coastguard Worker
GetPercentFree()3730*795d594fSAndroid Build Coastguard Worker size_t Heap::GetPercentFree() {
3731*795d594fSAndroid Build Coastguard Worker return static_cast<size_t>(100.0f * static_cast<float>(
3732*795d594fSAndroid Build Coastguard Worker GetFreeMemory()) / target_footprint_.load(std::memory_order_relaxed));
3733*795d594fSAndroid Build Coastguard Worker }
3734*795d594fSAndroid Build Coastguard Worker
SetIdealFootprint(size_t target_footprint)3735*795d594fSAndroid Build Coastguard Worker void Heap::SetIdealFootprint(size_t target_footprint) {
3736*795d594fSAndroid Build Coastguard Worker if (target_footprint > GetMaxMemory()) {
3737*795d594fSAndroid Build Coastguard Worker VLOG(gc) << "Clamp target GC heap from " << PrettySize(target_footprint) << " to "
3738*795d594fSAndroid Build Coastguard Worker << PrettySize(GetMaxMemory());
3739*795d594fSAndroid Build Coastguard Worker target_footprint = GetMaxMemory();
3740*795d594fSAndroid Build Coastguard Worker }
3741*795d594fSAndroid Build Coastguard Worker target_footprint_.store(target_footprint, std::memory_order_relaxed);
3742*795d594fSAndroid Build Coastguard Worker }
3743*795d594fSAndroid Build Coastguard Worker
IsMovableObject(ObjPtr<mirror::Object> obj) const3744*795d594fSAndroid Build Coastguard Worker bool Heap::IsMovableObject(ObjPtr<mirror::Object> obj) const {
3745*795d594fSAndroid Build Coastguard Worker if (kMovingCollector) {
3746*795d594fSAndroid Build Coastguard Worker space::Space* space = FindContinuousSpaceFromObject(obj.Ptr(), true);
3747*795d594fSAndroid Build Coastguard Worker if (space != nullptr) {
3748*795d594fSAndroid Build Coastguard Worker // TODO: Check large object?
3749*795d594fSAndroid Build Coastguard Worker return space->CanMoveObjects();
3750*795d594fSAndroid Build Coastguard Worker }
3751*795d594fSAndroid Build Coastguard Worker }
3752*795d594fSAndroid Build Coastguard Worker return false;
3753*795d594fSAndroid Build Coastguard Worker }
3754*795d594fSAndroid Build Coastguard Worker
FindCollectorByGcType(collector::GcType gc_type)3755*795d594fSAndroid Build Coastguard Worker collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
3756*795d594fSAndroid Build Coastguard Worker for (auto* collector : garbage_collectors_) {
3757*795d594fSAndroid Build Coastguard Worker if (collector->GetCollectorType() == collector_type_ &&
3758*795d594fSAndroid Build Coastguard Worker collector->GetGcType() == gc_type) {
3759*795d594fSAndroid Build Coastguard Worker return collector;
3760*795d594fSAndroid Build Coastguard Worker }
3761*795d594fSAndroid Build Coastguard Worker }
3762*795d594fSAndroid Build Coastguard Worker return nullptr;
3763*795d594fSAndroid Build Coastguard Worker }
3764*795d594fSAndroid Build Coastguard Worker
HeapGrowthMultiplier() const3765*795d594fSAndroid Build Coastguard Worker double Heap::HeapGrowthMultiplier() const {
3766*795d594fSAndroid Build Coastguard Worker // If we don't care about pause times we are background, so return 1.0.
3767*795d594fSAndroid Build Coastguard Worker if (!CareAboutPauseTimes()) {
3768*795d594fSAndroid Build Coastguard Worker return 1.0;
3769*795d594fSAndroid Build Coastguard Worker }
3770*795d594fSAndroid Build Coastguard Worker return foreground_heap_growth_multiplier_;
3771*795d594fSAndroid Build Coastguard Worker }
3772*795d594fSAndroid Build Coastguard Worker
GrowForUtilization(collector::GarbageCollector * collector_ran,size_t bytes_allocated_before_gc)3773*795d594fSAndroid Build Coastguard Worker void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran,
3774*795d594fSAndroid Build Coastguard Worker size_t bytes_allocated_before_gc) {
3775*795d594fSAndroid Build Coastguard Worker // We're running in the thread that set collector_type_running_ to something other than none,
3776*795d594fSAndroid Build Coastguard Worker // thus ensuring that there is only one of us running. Thus
3777*795d594fSAndroid Build Coastguard Worker // collector_type_running_ != kCollectorTypeNone, but that's a little tricky to turn into a
3778*795d594fSAndroid Build Coastguard Worker // DCHECK.
3779*795d594fSAndroid Build Coastguard Worker
3780*795d594fSAndroid Build Coastguard Worker // We know what our utilization is at this moment.
3781*795d594fSAndroid Build Coastguard Worker // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
3782*795d594fSAndroid Build Coastguard Worker const size_t bytes_allocated = GetBytesAllocated();
3783*795d594fSAndroid Build Coastguard Worker // Trace the new heap size after the GC is finished.
3784*795d594fSAndroid Build Coastguard Worker TraceHeapSize(bytes_allocated);
3785*795d594fSAndroid Build Coastguard Worker uint64_t target_size, grow_bytes;
3786*795d594fSAndroid Build Coastguard Worker collector::GcType gc_type = collector_ran->GetGcType();
3787*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), process_state_update_lock_);
3788*795d594fSAndroid Build Coastguard Worker // Use the multiplier to grow more for foreground.
3789*795d594fSAndroid Build Coastguard Worker const double multiplier = HeapGrowthMultiplier();
3790*795d594fSAndroid Build Coastguard Worker if (gc_type != collector::kGcTypeSticky) {
3791*795d594fSAndroid Build Coastguard Worker // Grow the heap for non sticky GC.
3792*795d594fSAndroid Build Coastguard Worker uint64_t delta = bytes_allocated * (1.0 / GetTargetHeapUtilization() - 1.0);
3793*795d594fSAndroid Build Coastguard Worker DCHECK_LE(delta, std::numeric_limits<size_t>::max()) << "bytes_allocated=" << bytes_allocated
3794*795d594fSAndroid Build Coastguard Worker << " target_utilization_=" << target_utilization_;
3795*795d594fSAndroid Build Coastguard Worker grow_bytes = std::min(delta, static_cast<uint64_t>(max_free_));
3796*795d594fSAndroid Build Coastguard Worker grow_bytes = std::max(grow_bytes, static_cast<uint64_t>(min_free_));
3797*795d594fSAndroid Build Coastguard Worker target_size = bytes_allocated + static_cast<uint64_t>(grow_bytes * multiplier);
3798*795d594fSAndroid Build Coastguard Worker next_gc_type_ = collector::kGcTypeSticky;
3799*795d594fSAndroid Build Coastguard Worker } else {
3800*795d594fSAndroid Build Coastguard Worker collector::GcType non_sticky_gc_type = NonStickyGcType();
3801*795d594fSAndroid Build Coastguard Worker // Find what the next non sticky collector will be.
3802*795d594fSAndroid Build Coastguard Worker collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
3803*795d594fSAndroid Build Coastguard Worker if (use_generational_cc_) {
3804*795d594fSAndroid Build Coastguard Worker if (non_sticky_collector == nullptr) {
3805*795d594fSAndroid Build Coastguard Worker non_sticky_collector = FindCollectorByGcType(collector::kGcTypePartial);
3806*795d594fSAndroid Build Coastguard Worker }
3807*795d594fSAndroid Build Coastguard Worker CHECK(non_sticky_collector != nullptr);
3808*795d594fSAndroid Build Coastguard Worker }
3809*795d594fSAndroid Build Coastguard Worker double sticky_gc_throughput_adjustment = GetStickyGcThroughputAdjustment(use_generational_cc_);
3810*795d594fSAndroid Build Coastguard Worker
3811*795d594fSAndroid Build Coastguard Worker // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
3812*795d594fSAndroid Build Coastguard Worker // do another sticky collection next.
3813*795d594fSAndroid Build Coastguard Worker // We also check that the bytes allocated aren't over the target_footprint, or
3814*795d594fSAndroid Build Coastguard Worker // concurrent_start_bytes in case of concurrent GCs, in order to prevent a
3815*795d594fSAndroid Build Coastguard Worker // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
3816*795d594fSAndroid Build Coastguard Worker // if the sticky GC throughput always remained >= the full/partial throughput.
3817*795d594fSAndroid Build Coastguard Worker size_t target_footprint = target_footprint_.load(std::memory_order_relaxed);
3818*795d594fSAndroid Build Coastguard Worker if (current_gc_iteration_.GetEstimatedThroughput() * sticky_gc_throughput_adjustment >=
3819*795d594fSAndroid Build Coastguard Worker non_sticky_collector->GetEstimatedMeanThroughput() &&
3820*795d594fSAndroid Build Coastguard Worker non_sticky_collector->NumberOfIterations() > 0 &&
3821*795d594fSAndroid Build Coastguard Worker bytes_allocated <= (IsGcConcurrent() ? concurrent_start_bytes_ : target_footprint)) {
3822*795d594fSAndroid Build Coastguard Worker next_gc_type_ = collector::kGcTypeSticky;
3823*795d594fSAndroid Build Coastguard Worker } else {
3824*795d594fSAndroid Build Coastguard Worker next_gc_type_ = non_sticky_gc_type;
3825*795d594fSAndroid Build Coastguard Worker }
3826*795d594fSAndroid Build Coastguard Worker // If we have freed enough memory, shrink the heap back down.
3827*795d594fSAndroid Build Coastguard Worker const size_t adjusted_max_free = static_cast<size_t>(max_free_ * multiplier);
3828*795d594fSAndroid Build Coastguard Worker if (bytes_allocated + adjusted_max_free < target_footprint) {
3829*795d594fSAndroid Build Coastguard Worker target_size = bytes_allocated + adjusted_max_free;
3830*795d594fSAndroid Build Coastguard Worker grow_bytes = max_free_;
3831*795d594fSAndroid Build Coastguard Worker } else {
3832*795d594fSAndroid Build Coastguard Worker target_size = std::max(bytes_allocated, target_footprint);
3833*795d594fSAndroid Build Coastguard Worker // The same whether jank perceptible or not; just avoid the adjustment.
3834*795d594fSAndroid Build Coastguard Worker grow_bytes = 0;
3835*795d594fSAndroid Build Coastguard Worker }
3836*795d594fSAndroid Build Coastguard Worker }
3837*795d594fSAndroid Build Coastguard Worker CHECK_LE(target_size, std::numeric_limits<size_t>::max())
3838*795d594fSAndroid Build Coastguard Worker << " bytes_allocated:" << bytes_allocated
3839*795d594fSAndroid Build Coastguard Worker << " bytes_freed:" << current_gc_iteration_.GetFreedBytes()
3840*795d594fSAndroid Build Coastguard Worker << " large_obj_bytes_freed:" << current_gc_iteration_.GetFreedLargeObjectBytes();
3841*795d594fSAndroid Build Coastguard Worker if (!ignore_target_footprint_) {
3842*795d594fSAndroid Build Coastguard Worker SetIdealFootprint(target_size);
3843*795d594fSAndroid Build Coastguard Worker // Store target size (computed with foreground heap growth multiplier) for updating
3844*795d594fSAndroid Build Coastguard Worker // target_footprint_ when process state switches to foreground.
3845*795d594fSAndroid Build Coastguard Worker // target_size = 0 ensures that target_footprint_ is not updated on
3846*795d594fSAndroid Build Coastguard Worker // process-state switch.
3847*795d594fSAndroid Build Coastguard Worker min_foreground_target_footprint_ =
3848*795d594fSAndroid Build Coastguard Worker (multiplier <= 1.0 && grow_bytes > 0)
3849*795d594fSAndroid Build Coastguard Worker ? std::min(
3850*795d594fSAndroid Build Coastguard Worker bytes_allocated + static_cast<size_t>(grow_bytes * foreground_heap_growth_multiplier_),
3851*795d594fSAndroid Build Coastguard Worker GetMaxMemory())
3852*795d594fSAndroid Build Coastguard Worker : 0;
3853*795d594fSAndroid Build Coastguard Worker
3854*795d594fSAndroid Build Coastguard Worker if (IsGcConcurrent()) {
3855*795d594fSAndroid Build Coastguard Worker const uint64_t freed_bytes = current_gc_iteration_.GetFreedBytes() +
3856*795d594fSAndroid Build Coastguard Worker current_gc_iteration_.GetFreedLargeObjectBytes() +
3857*795d594fSAndroid Build Coastguard Worker current_gc_iteration_.GetFreedRevokeBytes();
3858*795d594fSAndroid Build Coastguard Worker // Records the number of bytes allocated at the time of GC finish,excluding the number of
3859*795d594fSAndroid Build Coastguard Worker // bytes allocated during GC.
3860*795d594fSAndroid Build Coastguard Worker num_bytes_alive_after_gc_ = UnsignedDifference(bytes_allocated_before_gc, freed_bytes);
3861*795d594fSAndroid Build Coastguard Worker // Bytes allocated will shrink by freed_bytes after the GC runs, so if we want to figure out
3862*795d594fSAndroid Build Coastguard Worker // how many bytes were allocated during the GC we need to add freed_bytes back on.
3863*795d594fSAndroid Build Coastguard Worker // Almost always bytes_allocated + freed_bytes >= bytes_allocated_before_gc.
3864*795d594fSAndroid Build Coastguard Worker const size_t bytes_allocated_during_gc =
3865*795d594fSAndroid Build Coastguard Worker UnsignedDifference(bytes_allocated + freed_bytes, bytes_allocated_before_gc);
3866*795d594fSAndroid Build Coastguard Worker // Calculate when to perform the next ConcurrentGC.
3867*795d594fSAndroid Build Coastguard Worker // Estimate how many remaining bytes we will have when we need to start the next GC.
3868*795d594fSAndroid Build Coastguard Worker size_t remaining_bytes = bytes_allocated_during_gc;
3869*795d594fSAndroid Build Coastguard Worker remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
3870*795d594fSAndroid Build Coastguard Worker remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
3871*795d594fSAndroid Build Coastguard Worker size_t target_footprint = target_footprint_.load(std::memory_order_relaxed);
3872*795d594fSAndroid Build Coastguard Worker if (UNLIKELY(remaining_bytes > target_footprint)) {
3873*795d594fSAndroid Build Coastguard Worker // A never going to happen situation that from the estimated allocation rate we will exceed
3874*795d594fSAndroid Build Coastguard Worker // the applications entire footprint with the given estimated allocation rate. Schedule
3875*795d594fSAndroid Build Coastguard Worker // another GC nearly straight away.
3876*795d594fSAndroid Build Coastguard Worker remaining_bytes = std::min(kMinConcurrentRemainingBytes, target_footprint);
3877*795d594fSAndroid Build Coastguard Worker }
3878*795d594fSAndroid Build Coastguard Worker DCHECK_LE(target_footprint_.load(std::memory_order_relaxed), GetMaxMemory());
3879*795d594fSAndroid Build Coastguard Worker // Start a concurrent GC when we get close to the estimated remaining bytes. When the
3880*795d594fSAndroid Build Coastguard Worker // allocation rate is very high, remaining_bytes could tell us that we should start a GC
3881*795d594fSAndroid Build Coastguard Worker // right away.
3882*795d594fSAndroid Build Coastguard Worker concurrent_start_bytes_ = std::max(target_footprint - remaining_bytes, bytes_allocated);
3883*795d594fSAndroid Build Coastguard Worker // Store concurrent_start_bytes_ (computed with foreground heap growth multiplier) for update
3884*795d594fSAndroid Build Coastguard Worker // itself when process state switches to foreground.
3885*795d594fSAndroid Build Coastguard Worker min_foreground_concurrent_start_bytes_ =
3886*795d594fSAndroid Build Coastguard Worker min_foreground_target_footprint_ != 0
3887*795d594fSAndroid Build Coastguard Worker ? std::max(min_foreground_target_footprint_ - remaining_bytes, bytes_allocated)
3888*795d594fSAndroid Build Coastguard Worker : 0;
3889*795d594fSAndroid Build Coastguard Worker }
3890*795d594fSAndroid Build Coastguard Worker }
3891*795d594fSAndroid Build Coastguard Worker }
3892*795d594fSAndroid Build Coastguard Worker
ClampGrowthLimit()3893*795d594fSAndroid Build Coastguard Worker void Heap::ClampGrowthLimit() {
3894*795d594fSAndroid Build Coastguard Worker // Use heap bitmap lock to guard against races with BindLiveToMarkBitmap.
3895*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(Thread::Current());
3896*795d594fSAndroid Build Coastguard Worker WriterMutexLock mu(soa.Self(), *Locks::heap_bitmap_lock_);
3897*795d594fSAndroid Build Coastguard Worker capacity_ = growth_limit_;
3898*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
3899*795d594fSAndroid Build Coastguard Worker if (space->IsMallocSpace()) {
3900*795d594fSAndroid Build Coastguard Worker gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3901*795d594fSAndroid Build Coastguard Worker malloc_space->ClampGrowthLimit();
3902*795d594fSAndroid Build Coastguard Worker }
3903*795d594fSAndroid Build Coastguard Worker }
3904*795d594fSAndroid Build Coastguard Worker if (large_object_space_ != nullptr) {
3905*795d594fSAndroid Build Coastguard Worker large_object_space_->ClampGrowthLimit(capacity_);
3906*795d594fSAndroid Build Coastguard Worker }
3907*795d594fSAndroid Build Coastguard Worker if (collector_type_ == kCollectorTypeCC) {
3908*795d594fSAndroid Build Coastguard Worker DCHECK(region_space_ != nullptr);
3909*795d594fSAndroid Build Coastguard Worker // Twice the capacity as CC needs extra space for evacuating objects.
3910*795d594fSAndroid Build Coastguard Worker region_space_->ClampGrowthLimit(2 * capacity_);
3911*795d594fSAndroid Build Coastguard Worker } else if (collector_type_ == kCollectorTypeCMC) {
3912*795d594fSAndroid Build Coastguard Worker DCHECK(gUseUserfaultfd);
3913*795d594fSAndroid Build Coastguard Worker DCHECK_NE(mark_compact_, nullptr);
3914*795d594fSAndroid Build Coastguard Worker DCHECK_NE(bump_pointer_space_, nullptr);
3915*795d594fSAndroid Build Coastguard Worker mark_compact_->ClampGrowthLimit(capacity_);
3916*795d594fSAndroid Build Coastguard Worker }
3917*795d594fSAndroid Build Coastguard Worker // This space isn't added for performance reasons.
3918*795d594fSAndroid Build Coastguard Worker if (main_space_backup_.get() != nullptr) {
3919*795d594fSAndroid Build Coastguard Worker main_space_backup_->ClampGrowthLimit();
3920*795d594fSAndroid Build Coastguard Worker }
3921*795d594fSAndroid Build Coastguard Worker }
3922*795d594fSAndroid Build Coastguard Worker
ClearGrowthLimit()3923*795d594fSAndroid Build Coastguard Worker void Heap::ClearGrowthLimit() {
3924*795d594fSAndroid Build Coastguard Worker if (target_footprint_.load(std::memory_order_relaxed) == growth_limit_
3925*795d594fSAndroid Build Coastguard Worker && growth_limit_ < capacity_) {
3926*795d594fSAndroid Build Coastguard Worker target_footprint_.store(capacity_, std::memory_order_relaxed);
3927*795d594fSAndroid Build Coastguard Worker SetDefaultConcurrentStartBytes();
3928*795d594fSAndroid Build Coastguard Worker }
3929*795d594fSAndroid Build Coastguard Worker growth_limit_ = capacity_;
3930*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(Thread::Current());
3931*795d594fSAndroid Build Coastguard Worker for (const auto& space : continuous_spaces_) {
3932*795d594fSAndroid Build Coastguard Worker if (space->IsMallocSpace()) {
3933*795d594fSAndroid Build Coastguard Worker gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3934*795d594fSAndroid Build Coastguard Worker malloc_space->ClearGrowthLimit();
3935*795d594fSAndroid Build Coastguard Worker malloc_space->SetFootprintLimit(malloc_space->Capacity());
3936*795d594fSAndroid Build Coastguard Worker }
3937*795d594fSAndroid Build Coastguard Worker }
3938*795d594fSAndroid Build Coastguard Worker // This space isn't added for performance reasons.
3939*795d594fSAndroid Build Coastguard Worker if (main_space_backup_.get() != nullptr) {
3940*795d594fSAndroid Build Coastguard Worker main_space_backup_->ClearGrowthLimit();
3941*795d594fSAndroid Build Coastguard Worker main_space_backup_->SetFootprintLimit(main_space_backup_->Capacity());
3942*795d594fSAndroid Build Coastguard Worker }
3943*795d594fSAndroid Build Coastguard Worker }
3944*795d594fSAndroid Build Coastguard Worker
AddFinalizerReference(Thread * self,ObjPtr<mirror::Object> * object)3945*795d594fSAndroid Build Coastguard Worker void Heap::AddFinalizerReference(Thread* self, ObjPtr<mirror::Object>* object) {
3946*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(self);
3947*795d594fSAndroid Build Coastguard Worker StackHandleScope<1u> hs(self);
3948*795d594fSAndroid Build Coastguard Worker // Use handle wrapper to update the `*object` if the object gets moved.
3949*795d594fSAndroid Build Coastguard Worker HandleWrapperObjPtr<mirror::Object> h_object = hs.NewHandleWrapper(object);
3950*795d594fSAndroid Build Coastguard Worker WellKnownClasses::java_lang_ref_FinalizerReference_add->InvokeStatic<'V', 'L'>(
3951*795d594fSAndroid Build Coastguard Worker self, h_object.Get());
3952*795d594fSAndroid Build Coastguard Worker }
3953*795d594fSAndroid Build Coastguard Worker
RequestConcurrentGCAndSaveObject(Thread * self,bool force_full,uint32_t observed_gc_num,ObjPtr<mirror::Object> * obj)3954*795d594fSAndroid Build Coastguard Worker void Heap::RequestConcurrentGCAndSaveObject(Thread* self,
3955*795d594fSAndroid Build Coastguard Worker bool force_full,
3956*795d594fSAndroid Build Coastguard Worker uint32_t observed_gc_num,
3957*795d594fSAndroid Build Coastguard Worker ObjPtr<mirror::Object>* obj) {
3958*795d594fSAndroid Build Coastguard Worker StackHandleScope<1> hs(self);
3959*795d594fSAndroid Build Coastguard Worker HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
3960*795d594fSAndroid Build Coastguard Worker RequestConcurrentGC(self, kGcCauseBackground, force_full, observed_gc_num);
3961*795d594fSAndroid Build Coastguard Worker }
3962*795d594fSAndroid Build Coastguard Worker
3963*795d594fSAndroid Build Coastguard Worker class Heap::ConcurrentGCTask : public HeapTask {
3964*795d594fSAndroid Build Coastguard Worker public:
ConcurrentGCTask(uint64_t target_time,GcCause cause,bool force_full,uint32_t gc_num)3965*795d594fSAndroid Build Coastguard Worker ConcurrentGCTask(uint64_t target_time, GcCause cause, bool force_full, uint32_t gc_num)
3966*795d594fSAndroid Build Coastguard Worker : HeapTask(target_time), cause_(cause), force_full_(force_full), my_gc_num_(gc_num) {}
Run(Thread * self)3967*795d594fSAndroid Build Coastguard Worker void Run(Thread* self) override {
3968*795d594fSAndroid Build Coastguard Worker Runtime* runtime = Runtime::Current();
3969*795d594fSAndroid Build Coastguard Worker gc::Heap* heap = runtime->GetHeap();
3970*795d594fSAndroid Build Coastguard Worker DCHECK(GCNumberLt(my_gc_num_, heap->GetCurrentGcNum() + 2)); // <= current_gc_num + 1
3971*795d594fSAndroid Build Coastguard Worker heap->ConcurrentGC(self, cause_, force_full_, my_gc_num_);
3972*795d594fSAndroid Build Coastguard Worker CHECK_IMPLIES(GCNumberLt(heap->GetCurrentGcNum(), my_gc_num_), runtime->IsShuttingDown(self));
3973*795d594fSAndroid Build Coastguard Worker }
3974*795d594fSAndroid Build Coastguard Worker
3975*795d594fSAndroid Build Coastguard Worker private:
3976*795d594fSAndroid Build Coastguard Worker const GcCause cause_;
3977*795d594fSAndroid Build Coastguard Worker const bool force_full_; // If true, force full (or partial) collection.
3978*795d594fSAndroid Build Coastguard Worker const uint32_t my_gc_num_; // Sequence number of requested GC.
3979*795d594fSAndroid Build Coastguard Worker };
3980*795d594fSAndroid Build Coastguard Worker
CanAddHeapTask(Thread * self)3981*795d594fSAndroid Build Coastguard Worker static bool CanAddHeapTask(Thread* self) REQUIRES(!Locks::runtime_shutdown_lock_) {
3982*795d594fSAndroid Build Coastguard Worker Runtime* runtime = Runtime::Current();
3983*795d594fSAndroid Build Coastguard Worker // We only care if the native stack has overflowed. If the simulated stack overflows, it is still
3984*795d594fSAndroid Build Coastguard Worker // possible that the native stack has room to add a heap task.
3985*795d594fSAndroid Build Coastguard Worker return runtime != nullptr && runtime->IsFinishedStarting() && !runtime->IsShuttingDown(self) &&
3986*795d594fSAndroid Build Coastguard Worker !self->IsHandlingStackOverflow<kNativeStackType>();
3987*795d594fSAndroid Build Coastguard Worker }
3988*795d594fSAndroid Build Coastguard Worker
RequestConcurrentGC(Thread * self,GcCause cause,bool force_full,uint32_t observed_gc_num)3989*795d594fSAndroid Build Coastguard Worker bool Heap::RequestConcurrentGC(Thread* self,
3990*795d594fSAndroid Build Coastguard Worker GcCause cause,
3991*795d594fSAndroid Build Coastguard Worker bool force_full,
3992*795d594fSAndroid Build Coastguard Worker uint32_t observed_gc_num) {
3993*795d594fSAndroid Build Coastguard Worker uint32_t max_gc_requested = max_gc_requested_.load(std::memory_order_relaxed);
3994*795d594fSAndroid Build Coastguard Worker if (!GCNumberLt(observed_gc_num, max_gc_requested)) {
3995*795d594fSAndroid Build Coastguard Worker // observed_gc_num >= max_gc_requested: Nobody beat us to requesting the next gc.
3996*795d594fSAndroid Build Coastguard Worker if (CanAddHeapTask(self)) {
3997*795d594fSAndroid Build Coastguard Worker // Since observed_gc_num >= max_gc_requested, this increases max_gc_requested_, if successful.
3998*795d594fSAndroid Build Coastguard Worker if (max_gc_requested_.CompareAndSetStrongRelaxed(max_gc_requested, observed_gc_num + 1)) {
3999*795d594fSAndroid Build Coastguard Worker task_processor_->AddTask(self, new ConcurrentGCTask(NanoTime(), // Start straight away.
4000*795d594fSAndroid Build Coastguard Worker cause,
4001*795d594fSAndroid Build Coastguard Worker force_full,
4002*795d594fSAndroid Build Coastguard Worker observed_gc_num + 1));
4003*795d594fSAndroid Build Coastguard Worker }
4004*795d594fSAndroid Build Coastguard Worker DCHECK(GCNumberLt(observed_gc_num, max_gc_requested_.load(std::memory_order_relaxed)));
4005*795d594fSAndroid Build Coastguard Worker // If we increased max_gc_requested_, then we added a task that will eventually cause
4006*795d594fSAndroid Build Coastguard Worker // gcs_completed_ to be incremented (to at least observed_gc_num + 1).
4007*795d594fSAndroid Build Coastguard Worker // If the CAS failed, somebody else did.
4008*795d594fSAndroid Build Coastguard Worker return true;
4009*795d594fSAndroid Build Coastguard Worker }
4010*795d594fSAndroid Build Coastguard Worker return false;
4011*795d594fSAndroid Build Coastguard Worker }
4012*795d594fSAndroid Build Coastguard Worker return true; // Vacuously.
4013*795d594fSAndroid Build Coastguard Worker }
4014*795d594fSAndroid Build Coastguard Worker
ConcurrentGC(Thread * self,GcCause cause,bool force_full,uint32_t requested_gc_num)4015*795d594fSAndroid Build Coastguard Worker void Heap::ConcurrentGC(Thread* self, GcCause cause, bool force_full, uint32_t requested_gc_num) {
4016*795d594fSAndroid Build Coastguard Worker if (!Runtime::Current()->IsShuttingDown(self)) {
4017*795d594fSAndroid Build Coastguard Worker // Wait for any GCs currently running to finish. If this incremented GC number, we're done.
4018*795d594fSAndroid Build Coastguard Worker WaitForGcToComplete(cause, self);
4019*795d594fSAndroid Build Coastguard Worker if (GCNumberLt(GetCurrentGcNum(), requested_gc_num)) {
4020*795d594fSAndroid Build Coastguard Worker collector::GcType next_gc_type = next_gc_type_;
4021*795d594fSAndroid Build Coastguard Worker // If forcing full and next gc type is sticky, override with a non-sticky type.
4022*795d594fSAndroid Build Coastguard Worker if (force_full && next_gc_type == collector::kGcTypeSticky) {
4023*795d594fSAndroid Build Coastguard Worker next_gc_type = NonStickyGcType();
4024*795d594fSAndroid Build Coastguard Worker }
4025*795d594fSAndroid Build Coastguard Worker // If we can't run the GC type we wanted to run, find the next appropriate one and try
4026*795d594fSAndroid Build Coastguard Worker // that instead. E.g. can't do partial, so do full instead.
4027*795d594fSAndroid Build Coastguard Worker // We must ensure that we run something that ends up incrementing gcs_completed_.
4028*795d594fSAndroid Build Coastguard Worker // In the kGcTypePartial case, the initial CollectGarbageInternal call may not have that
4029*795d594fSAndroid Build Coastguard Worker // effect, but the subsequent KGcTypeFull call will.
4030*795d594fSAndroid Build Coastguard Worker if (CollectGarbageInternal(next_gc_type, cause, false, requested_gc_num)
4031*795d594fSAndroid Build Coastguard Worker == collector::kGcTypeNone) {
4032*795d594fSAndroid Build Coastguard Worker for (collector::GcType gc_type : gc_plan_) {
4033*795d594fSAndroid Build Coastguard Worker if (!GCNumberLt(GetCurrentGcNum(), requested_gc_num)) {
4034*795d594fSAndroid Build Coastguard Worker // Somebody did it for us.
4035*795d594fSAndroid Build Coastguard Worker break;
4036*795d594fSAndroid Build Coastguard Worker }
4037*795d594fSAndroid Build Coastguard Worker // Attempt to run the collector, if we succeed, we are done.
4038*795d594fSAndroid Build Coastguard Worker if (gc_type > next_gc_type &&
4039*795d594fSAndroid Build Coastguard Worker CollectGarbageInternal(gc_type, cause, false, requested_gc_num)
4040*795d594fSAndroid Build Coastguard Worker != collector::kGcTypeNone) {
4041*795d594fSAndroid Build Coastguard Worker break;
4042*795d594fSAndroid Build Coastguard Worker }
4043*795d594fSAndroid Build Coastguard Worker }
4044*795d594fSAndroid Build Coastguard Worker }
4045*795d594fSAndroid Build Coastguard Worker }
4046*795d594fSAndroid Build Coastguard Worker }
4047*795d594fSAndroid Build Coastguard Worker }
4048*795d594fSAndroid Build Coastguard Worker
4049*795d594fSAndroid Build Coastguard Worker class Heap::CollectorTransitionTask : public HeapTask {
4050*795d594fSAndroid Build Coastguard Worker public:
CollectorTransitionTask(uint64_t target_time)4051*795d594fSAndroid Build Coastguard Worker explicit CollectorTransitionTask(uint64_t target_time) : HeapTask(target_time) {}
4052*795d594fSAndroid Build Coastguard Worker
Run(Thread * self)4053*795d594fSAndroid Build Coastguard Worker void Run(Thread* self) override {
4054*795d594fSAndroid Build Coastguard Worker gc::Heap* heap = Runtime::Current()->GetHeap();
4055*795d594fSAndroid Build Coastguard Worker heap->DoPendingCollectorTransition();
4056*795d594fSAndroid Build Coastguard Worker heap->ClearPendingCollectorTransition(self);
4057*795d594fSAndroid Build Coastguard Worker }
4058*795d594fSAndroid Build Coastguard Worker };
4059*795d594fSAndroid Build Coastguard Worker
ClearPendingCollectorTransition(Thread * self)4060*795d594fSAndroid Build Coastguard Worker void Heap::ClearPendingCollectorTransition(Thread* self) {
4061*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *pending_task_lock_);
4062*795d594fSAndroid Build Coastguard Worker pending_collector_transition_ = nullptr;
4063*795d594fSAndroid Build Coastguard Worker }
4064*795d594fSAndroid Build Coastguard Worker
RequestCollectorTransition(CollectorType desired_collector_type,uint64_t delta_time)4065*795d594fSAndroid Build Coastguard Worker void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
4066*795d594fSAndroid Build Coastguard Worker Thread* self = Thread::Current();
4067*795d594fSAndroid Build Coastguard Worker desired_collector_type_ = desired_collector_type;
4068*795d594fSAndroid Build Coastguard Worker if (desired_collector_type_ == collector_type_ || !CanAddHeapTask(self)) {
4069*795d594fSAndroid Build Coastguard Worker return;
4070*795d594fSAndroid Build Coastguard Worker }
4071*795d594fSAndroid Build Coastguard Worker if (collector_type_ == kCollectorTypeCC) {
4072*795d594fSAndroid Build Coastguard Worker // For CC, we invoke a full compaction when going to the background, but the collector type
4073*795d594fSAndroid Build Coastguard Worker // doesn't change.
4074*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(desired_collector_type_, kCollectorTypeCCBackground);
4075*795d594fSAndroid Build Coastguard Worker }
4076*795d594fSAndroid Build Coastguard Worker if (collector_type_ == kCollectorTypeCMC) {
4077*795d594fSAndroid Build Coastguard Worker // For CMC collector type doesn't change.
4078*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(desired_collector_type_, kCollectorTypeCMCBackground);
4079*795d594fSAndroid Build Coastguard Worker }
4080*795d594fSAndroid Build Coastguard Worker DCHECK_NE(collector_type_, kCollectorTypeCCBackground);
4081*795d594fSAndroid Build Coastguard Worker DCHECK_NE(collector_type_, kCollectorTypeCMCBackground);
4082*795d594fSAndroid Build Coastguard Worker CollectorTransitionTask* added_task = nullptr;
4083*795d594fSAndroid Build Coastguard Worker const uint64_t target_time = NanoTime() + delta_time;
4084*795d594fSAndroid Build Coastguard Worker {
4085*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *pending_task_lock_);
4086*795d594fSAndroid Build Coastguard Worker // If we have an existing collector transition, update the target time to be the new target.
4087*795d594fSAndroid Build Coastguard Worker if (pending_collector_transition_ != nullptr) {
4088*795d594fSAndroid Build Coastguard Worker task_processor_->UpdateTargetRunTime(self, pending_collector_transition_, target_time);
4089*795d594fSAndroid Build Coastguard Worker return;
4090*795d594fSAndroid Build Coastguard Worker }
4091*795d594fSAndroid Build Coastguard Worker added_task = new CollectorTransitionTask(target_time);
4092*795d594fSAndroid Build Coastguard Worker pending_collector_transition_ = added_task;
4093*795d594fSAndroid Build Coastguard Worker }
4094*795d594fSAndroid Build Coastguard Worker task_processor_->AddTask(self, added_task);
4095*795d594fSAndroid Build Coastguard Worker }
4096*795d594fSAndroid Build Coastguard Worker
4097*795d594fSAndroid Build Coastguard Worker class Heap::HeapTrimTask : public HeapTask {
4098*795d594fSAndroid Build Coastguard Worker public:
HeapTrimTask(uint64_t delta_time)4099*795d594fSAndroid Build Coastguard Worker explicit HeapTrimTask(uint64_t delta_time) : HeapTask(NanoTime() + delta_time) { }
Run(Thread * self)4100*795d594fSAndroid Build Coastguard Worker void Run(Thread* self) override {
4101*795d594fSAndroid Build Coastguard Worker gc::Heap* heap = Runtime::Current()->GetHeap();
4102*795d594fSAndroid Build Coastguard Worker heap->Trim(self);
4103*795d594fSAndroid Build Coastguard Worker heap->ClearPendingTrim(self);
4104*795d594fSAndroid Build Coastguard Worker }
4105*795d594fSAndroid Build Coastguard Worker };
4106*795d594fSAndroid Build Coastguard Worker
ClearPendingTrim(Thread * self)4107*795d594fSAndroid Build Coastguard Worker void Heap::ClearPendingTrim(Thread* self) {
4108*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *pending_task_lock_);
4109*795d594fSAndroid Build Coastguard Worker pending_heap_trim_ = nullptr;
4110*795d594fSAndroid Build Coastguard Worker }
4111*795d594fSAndroid Build Coastguard Worker
RequestTrim(Thread * self)4112*795d594fSAndroid Build Coastguard Worker void Heap::RequestTrim(Thread* self) {
4113*795d594fSAndroid Build Coastguard Worker if (!CanAddHeapTask(self)) {
4114*795d594fSAndroid Build Coastguard Worker return;
4115*795d594fSAndroid Build Coastguard Worker }
4116*795d594fSAndroid Build Coastguard Worker // GC completed and now we must decide whether to request a heap trim (advising pages back to the
4117*795d594fSAndroid Build Coastguard Worker // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
4118*795d594fSAndroid Build Coastguard Worker // a space it will hold its lock and can become a cause of jank.
4119*795d594fSAndroid Build Coastguard Worker // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
4120*795d594fSAndroid Build Coastguard Worker // forking.
4121*795d594fSAndroid Build Coastguard Worker
4122*795d594fSAndroid Build Coastguard Worker // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
4123*795d594fSAndroid Build Coastguard Worker // because that only marks object heads, so a large array looks like lots of empty space. We
4124*795d594fSAndroid Build Coastguard Worker // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
4125*795d594fSAndroid Build Coastguard Worker // to utilization (which is probably inversely proportional to how much benefit we can expect).
4126*795d594fSAndroid Build Coastguard Worker // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
4127*795d594fSAndroid Build Coastguard Worker // not how much use we're making of those pages.
4128*795d594fSAndroid Build Coastguard Worker HeapTrimTask* added_task = nullptr;
4129*795d594fSAndroid Build Coastguard Worker {
4130*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *pending_task_lock_);
4131*795d594fSAndroid Build Coastguard Worker if (pending_heap_trim_ != nullptr) {
4132*795d594fSAndroid Build Coastguard Worker // Already have a heap trim request in task processor, ignore this request.
4133*795d594fSAndroid Build Coastguard Worker return;
4134*795d594fSAndroid Build Coastguard Worker }
4135*795d594fSAndroid Build Coastguard Worker added_task = new HeapTrimTask(kHeapTrimWait);
4136*795d594fSAndroid Build Coastguard Worker pending_heap_trim_ = added_task;
4137*795d594fSAndroid Build Coastguard Worker }
4138*795d594fSAndroid Build Coastguard Worker task_processor_->AddTask(self, added_task);
4139*795d594fSAndroid Build Coastguard Worker }
4140*795d594fSAndroid Build Coastguard Worker
IncrementNumberOfBytesFreedRevoke(size_t freed_bytes_revoke)4141*795d594fSAndroid Build Coastguard Worker void Heap::IncrementNumberOfBytesFreedRevoke(size_t freed_bytes_revoke) {
4142*795d594fSAndroid Build Coastguard Worker size_t previous_num_bytes_freed_revoke =
4143*795d594fSAndroid Build Coastguard Worker num_bytes_freed_revoke_.fetch_add(freed_bytes_revoke, std::memory_order_relaxed);
4144*795d594fSAndroid Build Coastguard Worker // Check the updated value is less than the number of bytes allocated. There is a risk of
4145*795d594fSAndroid Build Coastguard Worker // execution being suspended between the increment above and the CHECK below, leading to
4146*795d594fSAndroid Build Coastguard Worker // the use of previous_num_bytes_freed_revoke in the comparison.
4147*795d594fSAndroid Build Coastguard Worker CHECK_GE(num_bytes_allocated_.load(std::memory_order_relaxed),
4148*795d594fSAndroid Build Coastguard Worker previous_num_bytes_freed_revoke + freed_bytes_revoke);
4149*795d594fSAndroid Build Coastguard Worker }
4150*795d594fSAndroid Build Coastguard Worker
RevokeThreadLocalBuffers(Thread * thread)4151*795d594fSAndroid Build Coastguard Worker void Heap::RevokeThreadLocalBuffers(Thread* thread) {
4152*795d594fSAndroid Build Coastguard Worker if (rosalloc_space_ != nullptr) {
4153*795d594fSAndroid Build Coastguard Worker size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
4154*795d594fSAndroid Build Coastguard Worker if (freed_bytes_revoke > 0U) {
4155*795d594fSAndroid Build Coastguard Worker IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
4156*795d594fSAndroid Build Coastguard Worker }
4157*795d594fSAndroid Build Coastguard Worker }
4158*795d594fSAndroid Build Coastguard Worker if (bump_pointer_space_ != nullptr) {
4159*795d594fSAndroid Build Coastguard Worker CHECK_EQ(bump_pointer_space_->RevokeThreadLocalBuffers(thread), 0U);
4160*795d594fSAndroid Build Coastguard Worker }
4161*795d594fSAndroid Build Coastguard Worker if (region_space_ != nullptr) {
4162*795d594fSAndroid Build Coastguard Worker CHECK_EQ(region_space_->RevokeThreadLocalBuffers(thread), 0U);
4163*795d594fSAndroid Build Coastguard Worker }
4164*795d594fSAndroid Build Coastguard Worker }
4165*795d594fSAndroid Build Coastguard Worker
RevokeRosAllocThreadLocalBuffers(Thread * thread)4166*795d594fSAndroid Build Coastguard Worker void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
4167*795d594fSAndroid Build Coastguard Worker if (rosalloc_space_ != nullptr) {
4168*795d594fSAndroid Build Coastguard Worker size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
4169*795d594fSAndroid Build Coastguard Worker if (freed_bytes_revoke > 0U) {
4170*795d594fSAndroid Build Coastguard Worker IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
4171*795d594fSAndroid Build Coastguard Worker }
4172*795d594fSAndroid Build Coastguard Worker }
4173*795d594fSAndroid Build Coastguard Worker }
4174*795d594fSAndroid Build Coastguard Worker
RevokeAllThreadLocalBuffers()4175*795d594fSAndroid Build Coastguard Worker void Heap::RevokeAllThreadLocalBuffers() {
4176*795d594fSAndroid Build Coastguard Worker if (rosalloc_space_ != nullptr) {
4177*795d594fSAndroid Build Coastguard Worker size_t freed_bytes_revoke = rosalloc_space_->RevokeAllThreadLocalBuffers();
4178*795d594fSAndroid Build Coastguard Worker if (freed_bytes_revoke > 0U) {
4179*795d594fSAndroid Build Coastguard Worker IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
4180*795d594fSAndroid Build Coastguard Worker }
4181*795d594fSAndroid Build Coastguard Worker }
4182*795d594fSAndroid Build Coastguard Worker if (bump_pointer_space_ != nullptr) {
4183*795d594fSAndroid Build Coastguard Worker CHECK_EQ(bump_pointer_space_->RevokeAllThreadLocalBuffers(), 0U);
4184*795d594fSAndroid Build Coastguard Worker }
4185*795d594fSAndroid Build Coastguard Worker if (region_space_ != nullptr) {
4186*795d594fSAndroid Build Coastguard Worker CHECK_EQ(region_space_->RevokeAllThreadLocalBuffers(), 0U);
4187*795d594fSAndroid Build Coastguard Worker }
4188*795d594fSAndroid Build Coastguard Worker }
4189*795d594fSAndroid Build Coastguard Worker
4190*795d594fSAndroid Build Coastguard Worker // For GC triggering purposes, we count old (pre-last-GC) and new native allocations as
4191*795d594fSAndroid Build Coastguard Worker // different fractions of Java allocations.
4192*795d594fSAndroid Build Coastguard Worker // For now, we essentially do not count old native allocations at all, so that we can preserve the
4193*795d594fSAndroid Build Coastguard Worker // existing behavior of not limiting native heap size. If we seriously considered it, we would
4194*795d594fSAndroid Build Coastguard Worker // have to adjust collection thresholds when we encounter large amounts of old native memory,
4195*795d594fSAndroid Build Coastguard Worker // and handle native out-of-memory situations.
4196*795d594fSAndroid Build Coastguard Worker
4197*795d594fSAndroid Build Coastguard Worker static constexpr size_t kOldNativeDiscountFactor = 65536; // Approximately infinite for now.
4198*795d594fSAndroid Build Coastguard Worker static constexpr size_t kNewNativeDiscountFactor = 2;
4199*795d594fSAndroid Build Coastguard Worker
4200*795d594fSAndroid Build Coastguard Worker // If weighted java + native memory use exceeds our target by kStopForNativeFactor, and
4201*795d594fSAndroid Build Coastguard Worker // newly allocated memory exceeds stop_for_native_allocs_, we wait for GC to complete to avoid
4202*795d594fSAndroid Build Coastguard Worker // running out of memory.
4203*795d594fSAndroid Build Coastguard Worker static constexpr float kStopForNativeFactor = 4.0;
4204*795d594fSAndroid Build Coastguard Worker
4205*795d594fSAndroid Build Coastguard Worker // Return the ratio of the weighted native + java allocated bytes to its target value.
4206*795d594fSAndroid Build Coastguard Worker // A return value > 1.0 means we should collect. Significantly larger values mean we're falling
4207*795d594fSAndroid Build Coastguard Worker // behind.
NativeMemoryOverTarget(size_t current_native_bytes,bool is_gc_concurrent)4208*795d594fSAndroid Build Coastguard Worker inline float Heap::NativeMemoryOverTarget(size_t current_native_bytes, bool is_gc_concurrent) {
4209*795d594fSAndroid Build Coastguard Worker // Collection check for native allocation. Does not enforce Java heap bounds.
4210*795d594fSAndroid Build Coastguard Worker // With adj_start_bytes defined below, effectively checks
4211*795d594fSAndroid Build Coastguard Worker // <java bytes allocd> + c1*<old native allocd> + c2*<new native allocd) >= adj_start_bytes,
4212*795d594fSAndroid Build Coastguard Worker // where c3 > 1, and currently c1 and c2 are 1 divided by the values defined above.
4213*795d594fSAndroid Build Coastguard Worker size_t old_native_bytes = old_native_bytes_allocated_.load(std::memory_order_relaxed);
4214*795d594fSAndroid Build Coastguard Worker if (old_native_bytes > current_native_bytes) {
4215*795d594fSAndroid Build Coastguard Worker // Net decrease; skip the check, but update old value.
4216*795d594fSAndroid Build Coastguard Worker // It's OK to lose an update if two stores race.
4217*795d594fSAndroid Build Coastguard Worker old_native_bytes_allocated_.store(current_native_bytes, std::memory_order_relaxed);
4218*795d594fSAndroid Build Coastguard Worker return 0.0;
4219*795d594fSAndroid Build Coastguard Worker } else {
4220*795d594fSAndroid Build Coastguard Worker size_t new_native_bytes = UnsignedDifference(current_native_bytes, old_native_bytes);
4221*795d594fSAndroid Build Coastguard Worker size_t weighted_native_bytes = new_native_bytes / kNewNativeDiscountFactor
4222*795d594fSAndroid Build Coastguard Worker + old_native_bytes / kOldNativeDiscountFactor;
4223*795d594fSAndroid Build Coastguard Worker size_t add_bytes_allowed = static_cast<size_t>(
4224*795d594fSAndroid Build Coastguard Worker NativeAllocationGcWatermark() * HeapGrowthMultiplier());
4225*795d594fSAndroid Build Coastguard Worker size_t java_gc_start_bytes = is_gc_concurrent
4226*795d594fSAndroid Build Coastguard Worker ? concurrent_start_bytes_
4227*795d594fSAndroid Build Coastguard Worker : target_footprint_.load(std::memory_order_relaxed);
4228*795d594fSAndroid Build Coastguard Worker size_t adj_start_bytes = UnsignedSum(java_gc_start_bytes,
4229*795d594fSAndroid Build Coastguard Worker add_bytes_allowed / kNewNativeDiscountFactor);
4230*795d594fSAndroid Build Coastguard Worker return static_cast<float>(GetBytesAllocated() + weighted_native_bytes)
4231*795d594fSAndroid Build Coastguard Worker / static_cast<float>(adj_start_bytes);
4232*795d594fSAndroid Build Coastguard Worker }
4233*795d594fSAndroid Build Coastguard Worker }
4234*795d594fSAndroid Build Coastguard Worker
CheckGCForNative(Thread * self)4235*795d594fSAndroid Build Coastguard Worker inline void Heap::CheckGCForNative(Thread* self) {
4236*795d594fSAndroid Build Coastguard Worker bool is_gc_concurrent = IsGcConcurrent();
4237*795d594fSAndroid Build Coastguard Worker uint32_t starting_gc_num = GetCurrentGcNum();
4238*795d594fSAndroid Build Coastguard Worker size_t current_native_bytes = GetNativeBytes();
4239*795d594fSAndroid Build Coastguard Worker float gc_urgency = NativeMemoryOverTarget(current_native_bytes, is_gc_concurrent);
4240*795d594fSAndroid Build Coastguard Worker if (UNLIKELY(gc_urgency >= 1.0)) {
4241*795d594fSAndroid Build Coastguard Worker if (is_gc_concurrent) {
4242*795d594fSAndroid Build Coastguard Worker bool requested =
4243*795d594fSAndroid Build Coastguard Worker RequestConcurrentGC(self, kGcCauseForNativeAlloc, /*force_full=*/true, starting_gc_num);
4244*795d594fSAndroid Build Coastguard Worker if (requested && gc_urgency > kStopForNativeFactor
4245*795d594fSAndroid Build Coastguard Worker && current_native_bytes > stop_for_native_allocs_) {
4246*795d594fSAndroid Build Coastguard Worker // We're in danger of running out of memory due to rampant native allocation.
4247*795d594fSAndroid Build Coastguard Worker if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
4248*795d594fSAndroid Build Coastguard Worker LOG(INFO) << "Stopping for native allocation, urgency: " << gc_urgency;
4249*795d594fSAndroid Build Coastguard Worker }
4250*795d594fSAndroid Build Coastguard Worker // Count how many times we do this, so we can warn if this becomes excessive.
4251*795d594fSAndroid Build Coastguard Worker // Stop after a while, out of excessive caution.
4252*795d594fSAndroid Build Coastguard Worker static constexpr int kGcWaitIters = 20;
4253*795d594fSAndroid Build Coastguard Worker for (int i = 1; i <= kGcWaitIters; ++i) {
4254*795d594fSAndroid Build Coastguard Worker if (!GCNumberLt(GetCurrentGcNum(), max_gc_requested_.load(std::memory_order_relaxed))
4255*795d594fSAndroid Build Coastguard Worker || WaitForGcToComplete(kGcCauseForNativeAlloc, self) != collector::kGcTypeNone) {
4256*795d594fSAndroid Build Coastguard Worker break;
4257*795d594fSAndroid Build Coastguard Worker }
4258*795d594fSAndroid Build Coastguard Worker CHECK(GCNumberLt(starting_gc_num, max_gc_requested_.load(std::memory_order_relaxed)));
4259*795d594fSAndroid Build Coastguard Worker if (i % 10 == 0) {
4260*795d594fSAndroid Build Coastguard Worker LOG(WARNING) << "Slept " << i << " times in native allocation, waiting for GC";
4261*795d594fSAndroid Build Coastguard Worker }
4262*795d594fSAndroid Build Coastguard Worker static constexpr int kGcWaitSleepMicros = 2000;
4263*795d594fSAndroid Build Coastguard Worker usleep(kGcWaitSleepMicros); // Encourage our requested GC to start.
4264*795d594fSAndroid Build Coastguard Worker }
4265*795d594fSAndroid Build Coastguard Worker }
4266*795d594fSAndroid Build Coastguard Worker } else {
4267*795d594fSAndroid Build Coastguard Worker CollectGarbageInternal(NonStickyGcType(), kGcCauseForNativeAlloc, false, starting_gc_num + 1);
4268*795d594fSAndroid Build Coastguard Worker }
4269*795d594fSAndroid Build Coastguard Worker }
4270*795d594fSAndroid Build Coastguard Worker }
4271*795d594fSAndroid Build Coastguard Worker
4272*795d594fSAndroid Build Coastguard Worker // About kNotifyNativeInterval allocations have occurred. Check whether we should garbage collect.
NotifyNativeAllocations(JNIEnv * env)4273*795d594fSAndroid Build Coastguard Worker void Heap::NotifyNativeAllocations(JNIEnv* env) {
4274*795d594fSAndroid Build Coastguard Worker native_objects_notified_.fetch_add(kNotifyNativeInterval, std::memory_order_relaxed);
4275*795d594fSAndroid Build Coastguard Worker CheckGCForNative(Thread::ForEnv(env));
4276*795d594fSAndroid Build Coastguard Worker }
4277*795d594fSAndroid Build Coastguard Worker
4278*795d594fSAndroid Build Coastguard Worker // Register a native allocation with an explicit size.
4279*795d594fSAndroid Build Coastguard Worker // This should only be done for large allocations of non-malloc memory, which we wouldn't
4280*795d594fSAndroid Build Coastguard Worker // otherwise see.
RegisterNativeAllocation(JNIEnv * env,size_t bytes)4281*795d594fSAndroid Build Coastguard Worker void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
4282*795d594fSAndroid Build Coastguard Worker // Cautiously check for a wrapped negative bytes argument.
4283*795d594fSAndroid Build Coastguard Worker DCHECK(sizeof(size_t) < 8 || bytes < (std::numeric_limits<size_t>::max() / 2));
4284*795d594fSAndroid Build Coastguard Worker native_bytes_registered_.fetch_add(bytes, std::memory_order_relaxed);
4285*795d594fSAndroid Build Coastguard Worker uint32_t objects_notified =
4286*795d594fSAndroid Build Coastguard Worker native_objects_notified_.fetch_add(1, std::memory_order_relaxed);
4287*795d594fSAndroid Build Coastguard Worker if (objects_notified % kNotifyNativeInterval == kNotifyNativeInterval - 1
4288*795d594fSAndroid Build Coastguard Worker || bytes > kCheckImmediatelyThreshold) {
4289*795d594fSAndroid Build Coastguard Worker CheckGCForNative(Thread::ForEnv(env));
4290*795d594fSAndroid Build Coastguard Worker }
4291*795d594fSAndroid Build Coastguard Worker // Heap profiler treats this as a Java allocation with a null object.
4292*795d594fSAndroid Build Coastguard Worker if (GetHeapSampler().IsEnabled()) {
4293*795d594fSAndroid Build Coastguard Worker JHPCheckNonTlabSampleAllocation(Thread::Current(), nullptr, bytes);
4294*795d594fSAndroid Build Coastguard Worker }
4295*795d594fSAndroid Build Coastguard Worker }
4296*795d594fSAndroid Build Coastguard Worker
RegisterNativeFree(JNIEnv *,size_t bytes)4297*795d594fSAndroid Build Coastguard Worker void Heap::RegisterNativeFree(JNIEnv*, size_t bytes) {
4298*795d594fSAndroid Build Coastguard Worker size_t allocated;
4299*795d594fSAndroid Build Coastguard Worker size_t new_freed_bytes;
4300*795d594fSAndroid Build Coastguard Worker do {
4301*795d594fSAndroid Build Coastguard Worker allocated = native_bytes_registered_.load(std::memory_order_relaxed);
4302*795d594fSAndroid Build Coastguard Worker new_freed_bytes = std::min(allocated, bytes);
4303*795d594fSAndroid Build Coastguard Worker // We should not be registering more free than allocated bytes.
4304*795d594fSAndroid Build Coastguard Worker // But correctly keep going in non-debug builds.
4305*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(new_freed_bytes, bytes);
4306*795d594fSAndroid Build Coastguard Worker } while (!native_bytes_registered_.CompareAndSetWeakRelaxed(allocated,
4307*795d594fSAndroid Build Coastguard Worker allocated - new_freed_bytes));
4308*795d594fSAndroid Build Coastguard Worker }
4309*795d594fSAndroid Build Coastguard Worker
GetTotalMemory() const4310*795d594fSAndroid Build Coastguard Worker size_t Heap::GetTotalMemory() const {
4311*795d594fSAndroid Build Coastguard Worker return std::max(target_footprint_.load(std::memory_order_relaxed), GetBytesAllocated());
4312*795d594fSAndroid Build Coastguard Worker }
4313*795d594fSAndroid Build Coastguard Worker
AddModUnionTable(accounting::ModUnionTable * mod_union_table)4314*795d594fSAndroid Build Coastguard Worker void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
4315*795d594fSAndroid Build Coastguard Worker DCHECK(mod_union_table != nullptr);
4316*795d594fSAndroid Build Coastguard Worker mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
4317*795d594fSAndroid Build Coastguard Worker }
4318*795d594fSAndroid Build Coastguard Worker
CheckPreconditionsForAllocObject(ObjPtr<mirror::Class> c,size_t byte_count)4319*795d594fSAndroid Build Coastguard Worker void Heap::CheckPreconditionsForAllocObject(ObjPtr<mirror::Class> c, size_t byte_count) {
4320*795d594fSAndroid Build Coastguard Worker // Compare rounded sizes since the allocation may have been retried after rounding the size.
4321*795d594fSAndroid Build Coastguard Worker // See b/37885600
4322*795d594fSAndroid Build Coastguard Worker CHECK(c == nullptr || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
4323*795d594fSAndroid Build Coastguard Worker (c->IsVariableSize() ||
4324*795d594fSAndroid Build Coastguard Worker RoundUp(c->GetObjectSize(), kObjectAlignment) ==
4325*795d594fSAndroid Build Coastguard Worker RoundUp(byte_count, kObjectAlignment)))
4326*795d594fSAndroid Build Coastguard Worker << "ClassFlags=" << c->GetClassFlags()
4327*795d594fSAndroid Build Coastguard Worker << " IsClassClass=" << c->IsClassClass()
4328*795d594fSAndroid Build Coastguard Worker << " byte_count=" << byte_count
4329*795d594fSAndroid Build Coastguard Worker << " IsVariableSize=" << c->IsVariableSize()
4330*795d594fSAndroid Build Coastguard Worker << " ObjectSize=" << c->GetObjectSize()
4331*795d594fSAndroid Build Coastguard Worker << " sizeof(Class)=" << sizeof(mirror::Class)
4332*795d594fSAndroid Build Coastguard Worker << " " << verification_->DumpObjectInfo(c.Ptr(), /*tag=*/ "klass");
4333*795d594fSAndroid Build Coastguard Worker CHECK_GE(byte_count, sizeof(mirror::Object));
4334*795d594fSAndroid Build Coastguard Worker }
4335*795d594fSAndroid Build Coastguard Worker
AddRememberedSet(accounting::RememberedSet * remembered_set)4336*795d594fSAndroid Build Coastguard Worker void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
4337*795d594fSAndroid Build Coastguard Worker CHECK(remembered_set != nullptr);
4338*795d594fSAndroid Build Coastguard Worker space::Space* space = remembered_set->GetSpace();
4339*795d594fSAndroid Build Coastguard Worker CHECK(space != nullptr);
4340*795d594fSAndroid Build Coastguard Worker CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
4341*795d594fSAndroid Build Coastguard Worker remembered_sets_.Put(space, remembered_set);
4342*795d594fSAndroid Build Coastguard Worker CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
4343*795d594fSAndroid Build Coastguard Worker }
4344*795d594fSAndroid Build Coastguard Worker
RemoveRememberedSet(space::Space * space)4345*795d594fSAndroid Build Coastguard Worker void Heap::RemoveRememberedSet(space::Space* space) {
4346*795d594fSAndroid Build Coastguard Worker CHECK(space != nullptr);
4347*795d594fSAndroid Build Coastguard Worker auto it = remembered_sets_.find(space);
4348*795d594fSAndroid Build Coastguard Worker CHECK(it != remembered_sets_.end());
4349*795d594fSAndroid Build Coastguard Worker delete it->second;
4350*795d594fSAndroid Build Coastguard Worker remembered_sets_.erase(it);
4351*795d594fSAndroid Build Coastguard Worker CHECK(remembered_sets_.find(space) == remembered_sets_.end());
4352*795d594fSAndroid Build Coastguard Worker }
4353*795d594fSAndroid Build Coastguard Worker
ClearMarkedObjects(bool release_eagerly)4354*795d594fSAndroid Build Coastguard Worker void Heap::ClearMarkedObjects(bool release_eagerly) {
4355*795d594fSAndroid Build Coastguard Worker // Clear all of the spaces' mark bitmaps.
4356*795d594fSAndroid Build Coastguard Worker for (const auto& space : GetContinuousSpaces()) {
4357*795d594fSAndroid Build Coastguard Worker if (space->GetLiveBitmap() != nullptr && !space->HasBoundBitmaps()) {
4358*795d594fSAndroid Build Coastguard Worker space->GetMarkBitmap()->Clear(release_eagerly);
4359*795d594fSAndroid Build Coastguard Worker }
4360*795d594fSAndroid Build Coastguard Worker }
4361*795d594fSAndroid Build Coastguard Worker // Clear the marked objects in the discontinous space object sets.
4362*795d594fSAndroid Build Coastguard Worker for (const auto& space : GetDiscontinuousSpaces()) {
4363*795d594fSAndroid Build Coastguard Worker space->GetMarkBitmap()->Clear(release_eagerly);
4364*795d594fSAndroid Build Coastguard Worker }
4365*795d594fSAndroid Build Coastguard Worker }
4366*795d594fSAndroid Build Coastguard Worker
SetAllocationRecords(AllocRecordObjectMap * records)4367*795d594fSAndroid Build Coastguard Worker void Heap::SetAllocationRecords(AllocRecordObjectMap* records) {
4368*795d594fSAndroid Build Coastguard Worker allocation_records_.reset(records);
4369*795d594fSAndroid Build Coastguard Worker }
4370*795d594fSAndroid Build Coastguard Worker
VisitAllocationRecords(RootVisitor * visitor) const4371*795d594fSAndroid Build Coastguard Worker void Heap::VisitAllocationRecords(RootVisitor* visitor) const {
4372*795d594fSAndroid Build Coastguard Worker if (IsAllocTrackingEnabled()) {
4373*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4374*795d594fSAndroid Build Coastguard Worker if (IsAllocTrackingEnabled()) {
4375*795d594fSAndroid Build Coastguard Worker GetAllocationRecords()->VisitRoots(visitor);
4376*795d594fSAndroid Build Coastguard Worker }
4377*795d594fSAndroid Build Coastguard Worker }
4378*795d594fSAndroid Build Coastguard Worker }
4379*795d594fSAndroid Build Coastguard Worker
SweepAllocationRecords(IsMarkedVisitor * visitor) const4380*795d594fSAndroid Build Coastguard Worker void Heap::SweepAllocationRecords(IsMarkedVisitor* visitor) const {
4381*795d594fSAndroid Build Coastguard Worker if (IsAllocTrackingEnabled()) {
4382*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4383*795d594fSAndroid Build Coastguard Worker if (IsAllocTrackingEnabled()) {
4384*795d594fSAndroid Build Coastguard Worker GetAllocationRecords()->SweepAllocationRecords(visitor);
4385*795d594fSAndroid Build Coastguard Worker }
4386*795d594fSAndroid Build Coastguard Worker }
4387*795d594fSAndroid Build Coastguard Worker }
4388*795d594fSAndroid Build Coastguard Worker
AllowNewAllocationRecords() const4389*795d594fSAndroid Build Coastguard Worker void Heap::AllowNewAllocationRecords() const {
4390*795d594fSAndroid Build Coastguard Worker CHECK(!gUseReadBarrier);
4391*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4392*795d594fSAndroid Build Coastguard Worker AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4393*795d594fSAndroid Build Coastguard Worker if (allocation_records != nullptr) {
4394*795d594fSAndroid Build Coastguard Worker allocation_records->AllowNewAllocationRecords();
4395*795d594fSAndroid Build Coastguard Worker }
4396*795d594fSAndroid Build Coastguard Worker }
4397*795d594fSAndroid Build Coastguard Worker
DisallowNewAllocationRecords() const4398*795d594fSAndroid Build Coastguard Worker void Heap::DisallowNewAllocationRecords() const {
4399*795d594fSAndroid Build Coastguard Worker CHECK(!gUseReadBarrier);
4400*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4401*795d594fSAndroid Build Coastguard Worker AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4402*795d594fSAndroid Build Coastguard Worker if (allocation_records != nullptr) {
4403*795d594fSAndroid Build Coastguard Worker allocation_records->DisallowNewAllocationRecords();
4404*795d594fSAndroid Build Coastguard Worker }
4405*795d594fSAndroid Build Coastguard Worker }
4406*795d594fSAndroid Build Coastguard Worker
BroadcastForNewAllocationRecords() const4407*795d594fSAndroid Build Coastguard Worker void Heap::BroadcastForNewAllocationRecords() const {
4408*795d594fSAndroid Build Coastguard Worker // Always broadcast without checking IsAllocTrackingEnabled() because IsAllocTrackingEnabled() may
4409*795d594fSAndroid Build Coastguard Worker // be set to false while some threads are waiting for system weak access in
4410*795d594fSAndroid Build Coastguard Worker // AllocRecordObjectMap::RecordAllocation() and we may fail to wake them up. b/27467554.
4411*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4412*795d594fSAndroid Build Coastguard Worker AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4413*795d594fSAndroid Build Coastguard Worker if (allocation_records != nullptr) {
4414*795d594fSAndroid Build Coastguard Worker allocation_records->BroadcastForNewAllocationRecords();
4415*795d594fSAndroid Build Coastguard Worker }
4416*795d594fSAndroid Build Coastguard Worker }
4417*795d594fSAndroid Build Coastguard Worker
4418*795d594fSAndroid Build Coastguard Worker // Perfetto Java Heap Profiler Support.
4419*795d594fSAndroid Build Coastguard Worker
4420*795d594fSAndroid Build Coastguard Worker // Perfetto initialization.
InitPerfettoJavaHeapProf()4421*795d594fSAndroid Build Coastguard Worker void Heap::InitPerfettoJavaHeapProf() {
4422*795d594fSAndroid Build Coastguard Worker // Initialize Perfetto Heap info and Heap id.
4423*795d594fSAndroid Build Coastguard Worker uint32_t heap_id = 1; // Initialize to 1, to be overwritten by Perfetto heap id.
4424*795d594fSAndroid Build Coastguard Worker #ifdef ART_TARGET_ANDROID
4425*795d594fSAndroid Build Coastguard Worker // Register the heap and create the heapid.
4426*795d594fSAndroid Build Coastguard Worker // Use a Perfetto heap name = "com.android.art" for the Java Heap Profiler.
4427*795d594fSAndroid Build Coastguard Worker AHeapInfo* info = AHeapInfo_create("com.android.art");
4428*795d594fSAndroid Build Coastguard Worker // Set the Enable Callback, there is no callback data ("nullptr").
4429*795d594fSAndroid Build Coastguard Worker AHeapInfo_setEnabledCallback(info, &EnableHeapSamplerCallback, &heap_sampler_);
4430*795d594fSAndroid Build Coastguard Worker // Set the Disable Callback.
4431*795d594fSAndroid Build Coastguard Worker AHeapInfo_setDisabledCallback(info, &DisableHeapSamplerCallback, &heap_sampler_);
4432*795d594fSAndroid Build Coastguard Worker heap_id = AHeapProfile_registerHeap(info);
4433*795d594fSAndroid Build Coastguard Worker // Do not enable the Java Heap Profiler in this case, wait for Perfetto to enable it through
4434*795d594fSAndroid Build Coastguard Worker // the callback function.
4435*795d594fSAndroid Build Coastguard Worker #else
4436*795d594fSAndroid Build Coastguard Worker // This is the host case, enable the Java Heap Profiler for host testing.
4437*795d594fSAndroid Build Coastguard Worker // Perfetto API is currently not available on host.
4438*795d594fSAndroid Build Coastguard Worker heap_sampler_.EnableHeapSampler();
4439*795d594fSAndroid Build Coastguard Worker #endif
4440*795d594fSAndroid Build Coastguard Worker heap_sampler_.SetHeapID(heap_id);
4441*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Java Heap Profiler Initialized";
4442*795d594fSAndroid Build Coastguard Worker }
4443*795d594fSAndroid Build Coastguard Worker
JHPCheckNonTlabSampleAllocation(Thread * self,mirror::Object * obj,size_t alloc_size)4444*795d594fSAndroid Build Coastguard Worker void Heap::JHPCheckNonTlabSampleAllocation(Thread* self, mirror::Object* obj, size_t alloc_size) {
4445*795d594fSAndroid Build Coastguard Worker bool take_sample = false;
4446*795d594fSAndroid Build Coastguard Worker size_t bytes_until_sample = 0;
4447*795d594fSAndroid Build Coastguard Worker HeapSampler& prof_heap_sampler = GetHeapSampler();
4448*795d594fSAndroid Build Coastguard Worker // An allocation occurred, sample it, even if non-Tlab.
4449*795d594fSAndroid Build Coastguard Worker // In case take_sample is already set from the previous GetSampleOffset
4450*795d594fSAndroid Build Coastguard Worker // because we tried the Tlab allocation first, we will not use this value.
4451*795d594fSAndroid Build Coastguard Worker // A new value is generated below. Also bytes_until_sample will be updated.
4452*795d594fSAndroid Build Coastguard Worker // Note that we are not using the return value from the GetSampleOffset in
4453*795d594fSAndroid Build Coastguard Worker // the NonTlab case here.
4454*795d594fSAndroid Build Coastguard Worker prof_heap_sampler.GetSampleOffset(
4455*795d594fSAndroid Build Coastguard Worker alloc_size, self->GetTlabPosOffset(), &take_sample, &bytes_until_sample);
4456*795d594fSAndroid Build Coastguard Worker prof_heap_sampler.SetBytesUntilSample(bytes_until_sample);
4457*795d594fSAndroid Build Coastguard Worker if (take_sample) {
4458*795d594fSAndroid Build Coastguard Worker prof_heap_sampler.ReportSample(obj, alloc_size);
4459*795d594fSAndroid Build Coastguard Worker }
4460*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "JHP:NonTlab Non-moving or Large Allocation or RegisterNativeAllocation";
4461*795d594fSAndroid Build Coastguard Worker }
4462*795d594fSAndroid Build Coastguard Worker
JHPCalculateNextTlabSize(Thread * self,size_t jhp_def_tlab_size,size_t alloc_size,bool * take_sample,size_t * bytes_until_sample)4463*795d594fSAndroid Build Coastguard Worker size_t Heap::JHPCalculateNextTlabSize(Thread* self,
4464*795d594fSAndroid Build Coastguard Worker size_t jhp_def_tlab_size,
4465*795d594fSAndroid Build Coastguard Worker size_t alloc_size,
4466*795d594fSAndroid Build Coastguard Worker bool* take_sample,
4467*795d594fSAndroid Build Coastguard Worker size_t* bytes_until_sample) {
4468*795d594fSAndroid Build Coastguard Worker size_t next_sample_point = GetHeapSampler().GetSampleOffset(
4469*795d594fSAndroid Build Coastguard Worker alloc_size, self->GetTlabPosOffset(), take_sample, bytes_until_sample);
4470*795d594fSAndroid Build Coastguard Worker return std::min(next_sample_point, jhp_def_tlab_size);
4471*795d594fSAndroid Build Coastguard Worker }
4472*795d594fSAndroid Build Coastguard Worker
AdjustSampleOffset(size_t adjustment)4473*795d594fSAndroid Build Coastguard Worker void Heap::AdjustSampleOffset(size_t adjustment) {
4474*795d594fSAndroid Build Coastguard Worker GetHeapSampler().AdjustSampleOffset(adjustment);
4475*795d594fSAndroid Build Coastguard Worker }
4476*795d594fSAndroid Build Coastguard Worker
CheckGcStressMode(Thread * self,ObjPtr<mirror::Object> * obj)4477*795d594fSAndroid Build Coastguard Worker void Heap::CheckGcStressMode(Thread* self, ObjPtr<mirror::Object>* obj) {
4478*795d594fSAndroid Build Coastguard Worker DCHECK(gc_stress_mode_);
4479*795d594fSAndroid Build Coastguard Worker auto* const runtime = Runtime::Current();
4480*795d594fSAndroid Build Coastguard Worker if (runtime->GetClassLinker()->IsInitialized() && !runtime->IsActiveTransaction()) {
4481*795d594fSAndroid Build Coastguard Worker // Check if we should GC.
4482*795d594fSAndroid Build Coastguard Worker bool new_backtrace = false;
4483*795d594fSAndroid Build Coastguard Worker {
4484*795d594fSAndroid Build Coastguard Worker static constexpr size_t kMaxFrames = 16u;
4485*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *backtrace_lock_);
4486*795d594fSAndroid Build Coastguard Worker FixedSizeBacktrace<kMaxFrames> backtrace;
4487*795d594fSAndroid Build Coastguard Worker backtrace.Collect(/* skip_count= */ 2);
4488*795d594fSAndroid Build Coastguard Worker uint64_t hash = backtrace.Hash();
4489*795d594fSAndroid Build Coastguard Worker new_backtrace = seen_backtraces_.find(hash) == seen_backtraces_.end();
4490*795d594fSAndroid Build Coastguard Worker if (new_backtrace) {
4491*795d594fSAndroid Build Coastguard Worker seen_backtraces_.insert(hash);
4492*795d594fSAndroid Build Coastguard Worker }
4493*795d594fSAndroid Build Coastguard Worker }
4494*795d594fSAndroid Build Coastguard Worker if (new_backtrace) {
4495*795d594fSAndroid Build Coastguard Worker StackHandleScope<1> hs(self);
4496*795d594fSAndroid Build Coastguard Worker auto h = hs.NewHandleWrapper(obj);
4497*795d594fSAndroid Build Coastguard Worker CollectGarbage(/* clear_soft_references= */ false);
4498*795d594fSAndroid Build Coastguard Worker unique_backtrace_count_.fetch_add(1);
4499*795d594fSAndroid Build Coastguard Worker } else {
4500*795d594fSAndroid Build Coastguard Worker seen_backtrace_count_.fetch_add(1);
4501*795d594fSAndroid Build Coastguard Worker }
4502*795d594fSAndroid Build Coastguard Worker }
4503*795d594fSAndroid Build Coastguard Worker }
4504*795d594fSAndroid Build Coastguard Worker
DisableGCForShutdown()4505*795d594fSAndroid Build Coastguard Worker void Heap::DisableGCForShutdown() {
4506*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *gc_complete_lock_);
4507*795d594fSAndroid Build Coastguard Worker gc_disabled_for_shutdown_ = true;
4508*795d594fSAndroid Build Coastguard Worker }
4509*795d594fSAndroid Build Coastguard Worker
IsGCDisabledForShutdown() const4510*795d594fSAndroid Build Coastguard Worker bool Heap::IsGCDisabledForShutdown() const {
4511*795d594fSAndroid Build Coastguard Worker MutexLock mu(Thread::Current(), *gc_complete_lock_);
4512*795d594fSAndroid Build Coastguard Worker return gc_disabled_for_shutdown_;
4513*795d594fSAndroid Build Coastguard Worker }
4514*795d594fSAndroid Build Coastguard Worker
ObjectIsInBootImageSpace(ObjPtr<mirror::Object> obj) const4515*795d594fSAndroid Build Coastguard Worker bool Heap::ObjectIsInBootImageSpace(ObjPtr<mirror::Object> obj) const {
4516*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(IsBootImageAddress(obj.Ptr()),
4517*795d594fSAndroid Build Coastguard Worker any_of(boot_image_spaces_.begin(),
4518*795d594fSAndroid Build Coastguard Worker boot_image_spaces_.end(),
4519*795d594fSAndroid Build Coastguard Worker [obj](gc::space::ImageSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
4520*795d594fSAndroid Build Coastguard Worker return space->HasAddress(obj.Ptr());
4521*795d594fSAndroid Build Coastguard Worker }));
4522*795d594fSAndroid Build Coastguard Worker return IsBootImageAddress(obj.Ptr());
4523*795d594fSAndroid Build Coastguard Worker }
4524*795d594fSAndroid Build Coastguard Worker
IsInBootImageOatFile(const void * p) const4525*795d594fSAndroid Build Coastguard Worker bool Heap::IsInBootImageOatFile(const void* p) const {
4526*795d594fSAndroid Build Coastguard Worker DCHECK_EQ(IsBootImageAddress(p),
4527*795d594fSAndroid Build Coastguard Worker any_of(boot_image_spaces_.begin(),
4528*795d594fSAndroid Build Coastguard Worker boot_image_spaces_.end(),
4529*795d594fSAndroid Build Coastguard Worker [p](gc::space::ImageSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
4530*795d594fSAndroid Build Coastguard Worker return space->GetOatFile()->Contains(p);
4531*795d594fSAndroid Build Coastguard Worker }));
4532*795d594fSAndroid Build Coastguard Worker return IsBootImageAddress(p);
4533*795d594fSAndroid Build Coastguard Worker }
4534*795d594fSAndroid Build Coastguard Worker
SetAllocationListener(AllocationListener * l)4535*795d594fSAndroid Build Coastguard Worker void Heap::SetAllocationListener(AllocationListener* l) {
4536*795d594fSAndroid Build Coastguard Worker AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, l);
4537*795d594fSAndroid Build Coastguard Worker
4538*795d594fSAndroid Build Coastguard Worker if (old == nullptr) {
4539*795d594fSAndroid Build Coastguard Worker Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
4540*795d594fSAndroid Build Coastguard Worker }
4541*795d594fSAndroid Build Coastguard Worker }
4542*795d594fSAndroid Build Coastguard Worker
RemoveAllocationListener()4543*795d594fSAndroid Build Coastguard Worker void Heap::RemoveAllocationListener() {
4544*795d594fSAndroid Build Coastguard Worker AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, nullptr);
4545*795d594fSAndroid Build Coastguard Worker
4546*795d594fSAndroid Build Coastguard Worker if (old != nullptr) {
4547*795d594fSAndroid Build Coastguard Worker Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
4548*795d594fSAndroid Build Coastguard Worker }
4549*795d594fSAndroid Build Coastguard Worker }
4550*795d594fSAndroid Build Coastguard Worker
SetGcPauseListener(GcPauseListener * l)4551*795d594fSAndroid Build Coastguard Worker void Heap::SetGcPauseListener(GcPauseListener* l) {
4552*795d594fSAndroid Build Coastguard Worker gc_pause_listener_.store(l, std::memory_order_relaxed);
4553*795d594fSAndroid Build Coastguard Worker }
4554*795d594fSAndroid Build Coastguard Worker
RemoveGcPauseListener()4555*795d594fSAndroid Build Coastguard Worker void Heap::RemoveGcPauseListener() {
4556*795d594fSAndroid Build Coastguard Worker gc_pause_listener_.store(nullptr, std::memory_order_relaxed);
4557*795d594fSAndroid Build Coastguard Worker }
4558*795d594fSAndroid Build Coastguard Worker
AllocWithNewTLAB(Thread * self,AllocatorType allocator_type,size_t alloc_size,bool grow,size_t * bytes_allocated,size_t * usable_size,size_t * bytes_tl_bulk_allocated)4559*795d594fSAndroid Build Coastguard Worker mirror::Object* Heap::AllocWithNewTLAB(Thread* self,
4560*795d594fSAndroid Build Coastguard Worker AllocatorType allocator_type,
4561*795d594fSAndroid Build Coastguard Worker size_t alloc_size,
4562*795d594fSAndroid Build Coastguard Worker bool grow,
4563*795d594fSAndroid Build Coastguard Worker size_t* bytes_allocated,
4564*795d594fSAndroid Build Coastguard Worker size_t* usable_size,
4565*795d594fSAndroid Build Coastguard Worker size_t* bytes_tl_bulk_allocated) {
4566*795d594fSAndroid Build Coastguard Worker mirror::Object* ret = nullptr;
4567*795d594fSAndroid Build Coastguard Worker bool take_sample = false;
4568*795d594fSAndroid Build Coastguard Worker size_t bytes_until_sample = 0;
4569*795d594fSAndroid Build Coastguard Worker bool jhp_enabled = GetHeapSampler().IsEnabled();
4570*795d594fSAndroid Build Coastguard Worker
4571*795d594fSAndroid Build Coastguard Worker if (kUsePartialTlabs && alloc_size <= self->TlabRemainingCapacity()) {
4572*795d594fSAndroid Build Coastguard Worker DCHECK_GT(alloc_size, self->TlabSize());
4573*795d594fSAndroid Build Coastguard Worker // There is enough space if we grow the TLAB. Lets do that. This increases the
4574*795d594fSAndroid Build Coastguard Worker // TLAB bytes.
4575*795d594fSAndroid Build Coastguard Worker const size_t min_expand_size = alloc_size - self->TlabSize();
4576*795d594fSAndroid Build Coastguard Worker size_t next_tlab_size =
4577*795d594fSAndroid Build Coastguard Worker jhp_enabled ? JHPCalculateNextTlabSize(
4578*795d594fSAndroid Build Coastguard Worker self, kPartialTlabSize, alloc_size, &take_sample, &bytes_until_sample) :
4579*795d594fSAndroid Build Coastguard Worker kPartialTlabSize;
4580*795d594fSAndroid Build Coastguard Worker const size_t expand_bytes = std::max(
4581*795d594fSAndroid Build Coastguard Worker min_expand_size,
4582*795d594fSAndroid Build Coastguard Worker std::min(self->TlabRemainingCapacity() - self->TlabSize(), next_tlab_size));
4583*795d594fSAndroid Build Coastguard Worker if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, expand_bytes, grow))) {
4584*795d594fSAndroid Build Coastguard Worker return nullptr;
4585*795d594fSAndroid Build Coastguard Worker }
4586*795d594fSAndroid Build Coastguard Worker *bytes_tl_bulk_allocated = expand_bytes;
4587*795d594fSAndroid Build Coastguard Worker self->ExpandTlab(expand_bytes);
4588*795d594fSAndroid Build Coastguard Worker DCHECK_LE(alloc_size, self->TlabSize());
4589*795d594fSAndroid Build Coastguard Worker } else if (allocator_type == kAllocatorTypeTLAB) {
4590*795d594fSAndroid Build Coastguard Worker DCHECK(bump_pointer_space_ != nullptr);
4591*795d594fSAndroid Build Coastguard Worker // Try to allocate a page-aligned TLAB (not necessary though).
4592*795d594fSAndroid Build Coastguard Worker // TODO: for large allocations, which are rare, maybe we should allocate
4593*795d594fSAndroid Build Coastguard Worker // that object and return. There is no need to revoke the current TLAB,
4594*795d594fSAndroid Build Coastguard Worker // particularly if it's mostly unutilized.
4595*795d594fSAndroid Build Coastguard Worker size_t next_tlab_size = RoundDown(alloc_size + kDefaultTLABSize, gPageSize) - alloc_size;
4596*795d594fSAndroid Build Coastguard Worker if (jhp_enabled) {
4597*795d594fSAndroid Build Coastguard Worker next_tlab_size = JHPCalculateNextTlabSize(
4598*795d594fSAndroid Build Coastguard Worker self, next_tlab_size, alloc_size, &take_sample, &bytes_until_sample);
4599*795d594fSAndroid Build Coastguard Worker }
4600*795d594fSAndroid Build Coastguard Worker const size_t new_tlab_size = alloc_size + next_tlab_size;
4601*795d594fSAndroid Build Coastguard Worker if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, new_tlab_size, grow))) {
4602*795d594fSAndroid Build Coastguard Worker return nullptr;
4603*795d594fSAndroid Build Coastguard Worker }
4604*795d594fSAndroid Build Coastguard Worker // Try allocating a new thread local buffer, if the allocation fails the space must be
4605*795d594fSAndroid Build Coastguard Worker // full so return null.
4606*795d594fSAndroid Build Coastguard Worker if (!bump_pointer_space_->AllocNewTlab(self, new_tlab_size, bytes_tl_bulk_allocated)) {
4607*795d594fSAndroid Build Coastguard Worker return nullptr;
4608*795d594fSAndroid Build Coastguard Worker }
4609*795d594fSAndroid Build Coastguard Worker if (jhp_enabled) {
4610*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "JHP:kAllocatorTypeTLAB, New Tlab bytes allocated= " << new_tlab_size;
4611*795d594fSAndroid Build Coastguard Worker }
4612*795d594fSAndroid Build Coastguard Worker } else {
4613*795d594fSAndroid Build Coastguard Worker DCHECK(allocator_type == kAllocatorTypeRegionTLAB);
4614*795d594fSAndroid Build Coastguard Worker DCHECK(region_space_ != nullptr);
4615*795d594fSAndroid Build Coastguard Worker if (space::RegionSpace::kRegionSize >= alloc_size) {
4616*795d594fSAndroid Build Coastguard Worker // Non-large. Check OOME for a tlab.
4617*795d594fSAndroid Build Coastguard Worker if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type,
4618*795d594fSAndroid Build Coastguard Worker space::RegionSpace::kRegionSize,
4619*795d594fSAndroid Build Coastguard Worker grow))) {
4620*795d594fSAndroid Build Coastguard Worker size_t next_pr_tlab_size =
4621*795d594fSAndroid Build Coastguard Worker kUsePartialTlabs ? kPartialTlabSize : gc::space::RegionSpace::kRegionSize;
4622*795d594fSAndroid Build Coastguard Worker if (jhp_enabled) {
4623*795d594fSAndroid Build Coastguard Worker next_pr_tlab_size = JHPCalculateNextTlabSize(
4624*795d594fSAndroid Build Coastguard Worker self, next_pr_tlab_size, alloc_size, &take_sample, &bytes_until_sample);
4625*795d594fSAndroid Build Coastguard Worker }
4626*795d594fSAndroid Build Coastguard Worker const size_t new_tlab_size = kUsePartialTlabs
4627*795d594fSAndroid Build Coastguard Worker ? std::max(alloc_size, next_pr_tlab_size)
4628*795d594fSAndroid Build Coastguard Worker : next_pr_tlab_size;
4629*795d594fSAndroid Build Coastguard Worker // Try to allocate a tlab.
4630*795d594fSAndroid Build Coastguard Worker if (!region_space_->AllocNewTlab(self, new_tlab_size, bytes_tl_bulk_allocated)) {
4631*795d594fSAndroid Build Coastguard Worker // Failed to allocate a tlab. Try non-tlab.
4632*795d594fSAndroid Build Coastguard Worker ret = region_space_->AllocNonvirtual<false>(alloc_size,
4633*795d594fSAndroid Build Coastguard Worker bytes_allocated,
4634*795d594fSAndroid Build Coastguard Worker usable_size,
4635*795d594fSAndroid Build Coastguard Worker bytes_tl_bulk_allocated);
4636*795d594fSAndroid Build Coastguard Worker if (jhp_enabled) {
4637*795d594fSAndroid Build Coastguard Worker JHPCheckNonTlabSampleAllocation(self, ret, alloc_size);
4638*795d594fSAndroid Build Coastguard Worker }
4639*795d594fSAndroid Build Coastguard Worker return ret;
4640*795d594fSAndroid Build Coastguard Worker }
4641*795d594fSAndroid Build Coastguard Worker // Fall-through to using the TLAB below.
4642*795d594fSAndroid Build Coastguard Worker } else {
4643*795d594fSAndroid Build Coastguard Worker // Check OOME for a non-tlab allocation.
4644*795d594fSAndroid Build Coastguard Worker if (!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow)) {
4645*795d594fSAndroid Build Coastguard Worker ret = region_space_->AllocNonvirtual<false>(alloc_size,
4646*795d594fSAndroid Build Coastguard Worker bytes_allocated,
4647*795d594fSAndroid Build Coastguard Worker usable_size,
4648*795d594fSAndroid Build Coastguard Worker bytes_tl_bulk_allocated);
4649*795d594fSAndroid Build Coastguard Worker if (jhp_enabled) {
4650*795d594fSAndroid Build Coastguard Worker JHPCheckNonTlabSampleAllocation(self, ret, alloc_size);
4651*795d594fSAndroid Build Coastguard Worker }
4652*795d594fSAndroid Build Coastguard Worker return ret;
4653*795d594fSAndroid Build Coastguard Worker }
4654*795d594fSAndroid Build Coastguard Worker // Neither tlab or non-tlab works. Give up.
4655*795d594fSAndroid Build Coastguard Worker return nullptr;
4656*795d594fSAndroid Build Coastguard Worker }
4657*795d594fSAndroid Build Coastguard Worker } else {
4658*795d594fSAndroid Build Coastguard Worker // Large. Check OOME.
4659*795d594fSAndroid Build Coastguard Worker if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow))) {
4660*795d594fSAndroid Build Coastguard Worker ret = region_space_->AllocNonvirtual<false>(alloc_size,
4661*795d594fSAndroid Build Coastguard Worker bytes_allocated,
4662*795d594fSAndroid Build Coastguard Worker usable_size,
4663*795d594fSAndroid Build Coastguard Worker bytes_tl_bulk_allocated);
4664*795d594fSAndroid Build Coastguard Worker if (jhp_enabled) {
4665*795d594fSAndroid Build Coastguard Worker JHPCheckNonTlabSampleAllocation(self, ret, alloc_size);
4666*795d594fSAndroid Build Coastguard Worker }
4667*795d594fSAndroid Build Coastguard Worker return ret;
4668*795d594fSAndroid Build Coastguard Worker }
4669*795d594fSAndroid Build Coastguard Worker return nullptr;
4670*795d594fSAndroid Build Coastguard Worker }
4671*795d594fSAndroid Build Coastguard Worker }
4672*795d594fSAndroid Build Coastguard Worker // Refilled TLAB, return.
4673*795d594fSAndroid Build Coastguard Worker ret = self->AllocTlab(alloc_size);
4674*795d594fSAndroid Build Coastguard Worker DCHECK(ret != nullptr);
4675*795d594fSAndroid Build Coastguard Worker *bytes_allocated = alloc_size;
4676*795d594fSAndroid Build Coastguard Worker *usable_size = alloc_size;
4677*795d594fSAndroid Build Coastguard Worker
4678*795d594fSAndroid Build Coastguard Worker // JavaHeapProfiler: Send the thread information about this allocation in case a sample is
4679*795d594fSAndroid Build Coastguard Worker // requested.
4680*795d594fSAndroid Build Coastguard Worker // This is the fallthrough from both the if and else if above cases => Cases that use TLAB.
4681*795d594fSAndroid Build Coastguard Worker if (jhp_enabled) {
4682*795d594fSAndroid Build Coastguard Worker if (take_sample) {
4683*795d594fSAndroid Build Coastguard Worker GetHeapSampler().ReportSample(ret, alloc_size);
4684*795d594fSAndroid Build Coastguard Worker // Update the bytes_until_sample now that the allocation is already done.
4685*795d594fSAndroid Build Coastguard Worker GetHeapSampler().SetBytesUntilSample(bytes_until_sample);
4686*795d594fSAndroid Build Coastguard Worker }
4687*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "JHP:Fallthrough Tlab allocation";
4688*795d594fSAndroid Build Coastguard Worker }
4689*795d594fSAndroid Build Coastguard Worker
4690*795d594fSAndroid Build Coastguard Worker return ret;
4691*795d594fSAndroid Build Coastguard Worker }
4692*795d594fSAndroid Build Coastguard Worker
GetVerification() const4693*795d594fSAndroid Build Coastguard Worker const Verification* Heap::GetVerification() const {
4694*795d594fSAndroid Build Coastguard Worker return verification_.get();
4695*795d594fSAndroid Build Coastguard Worker }
4696*795d594fSAndroid Build Coastguard Worker
VlogHeapGrowth(size_t old_footprint,size_t new_footprint,size_t alloc_size)4697*795d594fSAndroid Build Coastguard Worker void Heap::VlogHeapGrowth(size_t old_footprint, size_t new_footprint, size_t alloc_size) {
4698*795d594fSAndroid Build Coastguard Worker VLOG(heap) << "Growing heap from " << PrettySize(old_footprint) << " to "
4699*795d594fSAndroid Build Coastguard Worker << PrettySize(new_footprint) << " for a " << PrettySize(alloc_size) << " allocation";
4700*795d594fSAndroid Build Coastguard Worker }
4701*795d594fSAndroid Build Coastguard Worker
4702*795d594fSAndroid Build Coastguard Worker // Run a gc if we haven't run one since initial_gc_num. This forces processes to
4703*795d594fSAndroid Build Coastguard Worker // reclaim memory allocated during startup, even if they don't do much
4704*795d594fSAndroid Build Coastguard Worker // allocation post startup. If the process is actively allocating and triggering
4705*795d594fSAndroid Build Coastguard Worker // GCs, or has moved to the background and hence forced a GC, this does nothing.
4706*795d594fSAndroid Build Coastguard Worker class Heap::TriggerPostForkCCGcTask : public HeapTask {
4707*795d594fSAndroid Build Coastguard Worker public:
TriggerPostForkCCGcTask(uint64_t target_time,uint32_t initial_gc_num)4708*795d594fSAndroid Build Coastguard Worker explicit TriggerPostForkCCGcTask(uint64_t target_time, uint32_t initial_gc_num) :
4709*795d594fSAndroid Build Coastguard Worker HeapTask(target_time), initial_gc_num_(initial_gc_num) {}
Run(Thread * self)4710*795d594fSAndroid Build Coastguard Worker void Run(Thread* self) override {
4711*795d594fSAndroid Build Coastguard Worker gc::Heap* heap = Runtime::Current()->GetHeap();
4712*795d594fSAndroid Build Coastguard Worker if (heap->GetCurrentGcNum() == initial_gc_num_) {
4713*795d594fSAndroid Build Coastguard Worker if (kLogAllGCs) {
4714*795d594fSAndroid Build Coastguard Worker LOG(INFO) << "Forcing GC for allocation-inactive process";
4715*795d594fSAndroid Build Coastguard Worker }
4716*795d594fSAndroid Build Coastguard Worker heap->RequestConcurrentGC(self, kGcCauseBackground, false, initial_gc_num_);
4717*795d594fSAndroid Build Coastguard Worker }
4718*795d594fSAndroid Build Coastguard Worker }
4719*795d594fSAndroid Build Coastguard Worker private:
4720*795d594fSAndroid Build Coastguard Worker uint32_t initial_gc_num_;
4721*795d594fSAndroid Build Coastguard Worker };
4722*795d594fSAndroid Build Coastguard Worker
4723*795d594fSAndroid Build Coastguard Worker // Reduce target footprint, if no GC has occurred since initial_gc_num.
4724*795d594fSAndroid Build Coastguard Worker // If a GC already occurred, it will have done this for us.
4725*795d594fSAndroid Build Coastguard Worker class Heap::ReduceTargetFootprintTask : public HeapTask {
4726*795d594fSAndroid Build Coastguard Worker public:
ReduceTargetFootprintTask(uint64_t target_time,size_t new_target_sz,uint32_t initial_gc_num)4727*795d594fSAndroid Build Coastguard Worker explicit ReduceTargetFootprintTask(uint64_t target_time, size_t new_target_sz,
4728*795d594fSAndroid Build Coastguard Worker uint32_t initial_gc_num) :
4729*795d594fSAndroid Build Coastguard Worker HeapTask(target_time), new_target_sz_(new_target_sz), initial_gc_num_(initial_gc_num) {}
Run(Thread * self)4730*795d594fSAndroid Build Coastguard Worker void Run(Thread* self) override {
4731*795d594fSAndroid Build Coastguard Worker gc::Heap* heap = Runtime::Current()->GetHeap();
4732*795d594fSAndroid Build Coastguard Worker MutexLock mu(self, *(heap->gc_complete_lock_));
4733*795d594fSAndroid Build Coastguard Worker if (heap->GetCurrentGcNum() == initial_gc_num_
4734*795d594fSAndroid Build Coastguard Worker && heap->collector_type_running_ == kCollectorTypeNone) {
4735*795d594fSAndroid Build Coastguard Worker size_t target_footprint = heap->target_footprint_.load(std::memory_order_relaxed);
4736*795d594fSAndroid Build Coastguard Worker if (target_footprint > new_target_sz_) {
4737*795d594fSAndroid Build Coastguard Worker if (heap->target_footprint_.CompareAndSetStrongRelaxed(target_footprint, new_target_sz_)) {
4738*795d594fSAndroid Build Coastguard Worker heap->SetDefaultConcurrentStartBytesLocked();
4739*795d594fSAndroid Build Coastguard Worker }
4740*795d594fSAndroid Build Coastguard Worker }
4741*795d594fSAndroid Build Coastguard Worker }
4742*795d594fSAndroid Build Coastguard Worker }
4743*795d594fSAndroid Build Coastguard Worker private:
4744*795d594fSAndroid Build Coastguard Worker size_t new_target_sz_;
4745*795d594fSAndroid Build Coastguard Worker uint32_t initial_gc_num_;
4746*795d594fSAndroid Build Coastguard Worker };
4747*795d594fSAndroid Build Coastguard Worker
4748*795d594fSAndroid Build Coastguard Worker // Return a pseudo-random integer between 0 and 19999, using the uid as a seed. We want this to
4749*795d594fSAndroid Build Coastguard Worker // be deterministic for a given process, but to vary randomly across processes. Empirically, the
4750*795d594fSAndroid Build Coastguard Worker // uids for processes for which this matters are distinct.
GetPseudoRandomFromUid()4751*795d594fSAndroid Build Coastguard Worker static uint32_t GetPseudoRandomFromUid() {
4752*795d594fSAndroid Build Coastguard Worker std::default_random_engine rng(getuid());
4753*795d594fSAndroid Build Coastguard Worker std::uniform_int_distribution<int> dist(0, 19999);
4754*795d594fSAndroid Build Coastguard Worker return dist(rng);
4755*795d594fSAndroid Build Coastguard Worker }
4756*795d594fSAndroid Build Coastguard Worker
PostForkChildAction(Thread * self)4757*795d594fSAndroid Build Coastguard Worker void Heap::PostForkChildAction(Thread* self) {
4758*795d594fSAndroid Build Coastguard Worker uint32_t starting_gc_num = GetCurrentGcNum();
4759*795d594fSAndroid Build Coastguard Worker uint64_t last_adj_time = NanoTime();
4760*795d594fSAndroid Build Coastguard Worker next_gc_type_ = NonStickyGcType(); // Always start with a full gc.
4761*795d594fSAndroid Build Coastguard Worker
4762*795d594fSAndroid Build Coastguard Worker LOG(INFO) << "Using " << foreground_collector_type_ << " GC.";
4763*795d594fSAndroid Build Coastguard Worker if (gUseUserfaultfd) {
4764*795d594fSAndroid Build Coastguard Worker DCHECK_NE(mark_compact_, nullptr);
4765*795d594fSAndroid Build Coastguard Worker mark_compact_->CreateUserfaultfd(/*post_fork*/true);
4766*795d594fSAndroid Build Coastguard Worker }
4767*795d594fSAndroid Build Coastguard Worker
4768*795d594fSAndroid Build Coastguard Worker // Temporarily increase target_footprint_ and concurrent_start_bytes_ to
4769*795d594fSAndroid Build Coastguard Worker // max values to avoid GC during app launch.
4770*795d594fSAndroid Build Coastguard Worker // Set target_footprint_ to the largest allowed value.
4771*795d594fSAndroid Build Coastguard Worker SetIdealFootprint(growth_limit_);
4772*795d594fSAndroid Build Coastguard Worker SetDefaultConcurrentStartBytes();
4773*795d594fSAndroid Build Coastguard Worker
4774*795d594fSAndroid Build Coastguard Worker // Shrink heap after kPostForkMaxHeapDurationMS, to force a memory hog process to GC.
4775*795d594fSAndroid Build Coastguard Worker // This remains high enough that many processes will continue without a GC.
4776*795d594fSAndroid Build Coastguard Worker if (initial_heap_size_ < growth_limit_) {
4777*795d594fSAndroid Build Coastguard Worker size_t first_shrink_size = std::max(growth_limit_ / 4, initial_heap_size_);
4778*795d594fSAndroid Build Coastguard Worker last_adj_time += MsToNs(kPostForkMaxHeapDurationMS);
4779*795d594fSAndroid Build Coastguard Worker GetTaskProcessor()->AddTask(
4780*795d594fSAndroid Build Coastguard Worker self, new ReduceTargetFootprintTask(last_adj_time, first_shrink_size, starting_gc_num));
4781*795d594fSAndroid Build Coastguard Worker // Shrink to a small value after a substantial time period. This will typically force a
4782*795d594fSAndroid Build Coastguard Worker // GC if none has occurred yet. Has no effect if there was a GC before this anyway, which
4783*795d594fSAndroid Build Coastguard Worker // is commonly the case, e.g. because of a process transition.
4784*795d594fSAndroid Build Coastguard Worker if (initial_heap_size_ < first_shrink_size) {
4785*795d594fSAndroid Build Coastguard Worker last_adj_time += MsToNs(4 * kPostForkMaxHeapDurationMS);
4786*795d594fSAndroid Build Coastguard Worker GetTaskProcessor()->AddTask(
4787*795d594fSAndroid Build Coastguard Worker self,
4788*795d594fSAndroid Build Coastguard Worker new ReduceTargetFootprintTask(last_adj_time, initial_heap_size_, starting_gc_num));
4789*795d594fSAndroid Build Coastguard Worker }
4790*795d594fSAndroid Build Coastguard Worker }
4791*795d594fSAndroid Build Coastguard Worker // Schedule a GC after a substantial period of time. This will become a no-op if another GC is
4792*795d594fSAndroid Build Coastguard Worker // scheduled in the interim. If not, we want to avoid holding onto start-up garbage.
4793*795d594fSAndroid Build Coastguard Worker uint64_t post_fork_gc_time = last_adj_time
4794*795d594fSAndroid Build Coastguard Worker + MsToNs(4 * kPostForkMaxHeapDurationMS + GetPseudoRandomFromUid());
4795*795d594fSAndroid Build Coastguard Worker GetTaskProcessor()->AddTask(self,
4796*795d594fSAndroid Build Coastguard Worker new TriggerPostForkCCGcTask(post_fork_gc_time, starting_gc_num));
4797*795d594fSAndroid Build Coastguard Worker }
4798*795d594fSAndroid Build Coastguard Worker
VisitReflectiveTargets(ReflectiveValueVisitor * visit)4799*795d594fSAndroid Build Coastguard Worker void Heap::VisitReflectiveTargets(ReflectiveValueVisitor *visit) {
4800*795d594fSAndroid Build Coastguard Worker VisitObjectsPaused([&visit](mirror::Object* ref) NO_THREAD_SAFETY_ANALYSIS {
4801*795d594fSAndroid Build Coastguard Worker art::ObjPtr<mirror::Class> klass(ref->GetClass());
4802*795d594fSAndroid Build Coastguard Worker // All these classes are in the BootstrapClassLoader.
4803*795d594fSAndroid Build Coastguard Worker if (!klass->IsBootStrapClassLoaded()) {
4804*795d594fSAndroid Build Coastguard Worker return;
4805*795d594fSAndroid Build Coastguard Worker }
4806*795d594fSAndroid Build Coastguard Worker if (GetClassRoot<mirror::Method>()->IsAssignableFrom(klass) ||
4807*795d594fSAndroid Build Coastguard Worker GetClassRoot<mirror::Constructor>()->IsAssignableFrom(klass)) {
4808*795d594fSAndroid Build Coastguard Worker down_cast<mirror::Executable*>(ref)->VisitTarget(visit);
4809*795d594fSAndroid Build Coastguard Worker } else if (art::GetClassRoot<art::mirror::Field>() == klass) {
4810*795d594fSAndroid Build Coastguard Worker down_cast<mirror::Field*>(ref)->VisitTarget(visit);
4811*795d594fSAndroid Build Coastguard Worker } else if (art::GetClassRoot<art::mirror::MethodHandle>()->IsAssignableFrom(klass)) {
4812*795d594fSAndroid Build Coastguard Worker down_cast<mirror::MethodHandle*>(ref)->VisitTarget(visit);
4813*795d594fSAndroid Build Coastguard Worker } else if (art::GetClassRoot<art::mirror::StaticFieldVarHandle>()->IsAssignableFrom(klass)) {
4814*795d594fSAndroid Build Coastguard Worker down_cast<mirror::StaticFieldVarHandle*>(ref)->VisitTarget(visit);
4815*795d594fSAndroid Build Coastguard Worker } else if (art::GetClassRoot<art::mirror::FieldVarHandle>()->IsAssignableFrom(klass)) {
4816*795d594fSAndroid Build Coastguard Worker down_cast<mirror::FieldVarHandle*>(ref)->VisitTarget(visit);
4817*795d594fSAndroid Build Coastguard Worker } else if (art::GetClassRoot<art::mirror::DexCache>()->IsAssignableFrom(klass)) {
4818*795d594fSAndroid Build Coastguard Worker down_cast<mirror::DexCache*>(ref)->VisitReflectiveTargets(visit);
4819*795d594fSAndroid Build Coastguard Worker }
4820*795d594fSAndroid Build Coastguard Worker });
4821*795d594fSAndroid Build Coastguard Worker }
4822*795d594fSAndroid Build Coastguard Worker
AddHeapTask(gc::HeapTask * task)4823*795d594fSAndroid Build Coastguard Worker bool Heap::AddHeapTask(gc::HeapTask* task) {
4824*795d594fSAndroid Build Coastguard Worker Thread* const self = Thread::Current();
4825*795d594fSAndroid Build Coastguard Worker if (!CanAddHeapTask(self)) {
4826*795d594fSAndroid Build Coastguard Worker return false;
4827*795d594fSAndroid Build Coastguard Worker }
4828*795d594fSAndroid Build Coastguard Worker GetTaskProcessor()->AddTask(self, task);
4829*795d594fSAndroid Build Coastguard Worker return true;
4830*795d594fSAndroid Build Coastguard Worker }
4831*795d594fSAndroid Build Coastguard Worker
GetForegroundCollectorName()4832*795d594fSAndroid Build Coastguard Worker std::string Heap::GetForegroundCollectorName() {
4833*795d594fSAndroid Build Coastguard Worker std::ostringstream oss;
4834*795d594fSAndroid Build Coastguard Worker oss << foreground_collector_type_;
4835*795d594fSAndroid Build Coastguard Worker return oss.str();
4836*795d594fSAndroid Build Coastguard Worker }
4837*795d594fSAndroid Build Coastguard Worker
HasAppImageSpaceFor(const std::string & dex_location) const4838*795d594fSAndroid Build Coastguard Worker bool Heap::HasAppImageSpaceFor(const std::string& dex_location) const {
4839*795d594fSAndroid Build Coastguard Worker ScopedObjectAccess soa(Thread::Current());
4840*795d594fSAndroid Build Coastguard Worker for (space::ContinuousSpace* space : continuous_spaces_) {
4841*795d594fSAndroid Build Coastguard Worker // An image space is either a boot image space or an app image space.
4842*795d594fSAndroid Build Coastguard Worker if (space->IsImageSpace() &&
4843*795d594fSAndroid Build Coastguard Worker !IsBootImageAddress(space->Begin()) &&
4844*795d594fSAndroid Build Coastguard Worker (space->AsImageSpace()->GetOatFile()->GetOatDexFiles()[0]->GetDexFileLocation() ==
4845*795d594fSAndroid Build Coastguard Worker dex_location)) {
4846*795d594fSAndroid Build Coastguard Worker return true;
4847*795d594fSAndroid Build Coastguard Worker }
4848*795d594fSAndroid Build Coastguard Worker }
4849*795d594fSAndroid Build Coastguard Worker return false;
4850*795d594fSAndroid Build Coastguard Worker }
4851*795d594fSAndroid Build Coastguard Worker
4852*795d594fSAndroid Build Coastguard Worker } // namespace gc
4853*795d594fSAndroid Build Coastguard Worker } // namespace art
4854