1 /* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef ART_RUNTIME_GC_HEAP_H_ 18 #define ART_RUNTIME_GC_HEAP_H_ 19 20 #include <android-base/logging.h> 21 22 #include <iosfwd> 23 #include <string> 24 #include <unordered_set> 25 #include <vector> 26 27 #include "allocator_type.h" 28 #include "base/atomic.h" 29 #include "base/histogram.h" 30 #include "base/macros.h" 31 #include "base/mutex.h" 32 #include "base/os.h" 33 #include "base/runtime_debug.h" 34 #include "base/safe_map.h" 35 #include "base/time_utils.h" 36 #include "gc/collector/gc_type.h" 37 #include "gc/collector/iteration.h" 38 #include "gc/collector/mark_compact.h" 39 #include "gc/collector_type.h" 40 #include "gc/gc_cause.h" 41 #include "gc/space/large_object_space.h" 42 #include "gc/space/space.h" 43 #include "handle.h" 44 #include "obj_ptr.h" 45 #include "offsets.h" 46 #include "process_state.h" 47 #include "read_barrier_config.h" 48 #include "runtime_globals.h" 49 #include "scoped_thread_state_change.h" 50 #include "verify_object.h" 51 52 namespace art HIDDEN { 53 54 class ConditionVariable; 55 enum class InstructionSet; 56 class IsMarkedVisitor; 57 class Mutex; 58 class ReflectiveValueVisitor; 59 class RootVisitor; 60 class StackVisitor; 61 class Thread; 62 class ThreadPool; 63 class TimingLogger; 64 class VariableSizedHandleScope; 65 66 namespace mirror { 67 class Class; 68 class Object; 69 } // namespace mirror 70 71 namespace gc { 72 73 class AllocationListener; 74 class AllocRecordObjectMap; 75 class GcPauseListener; 76 class HeapTask; 77 class ReferenceProcessor; 78 class TaskProcessor; 79 class Verification; 80 81 namespace accounting { 82 template <typename T> class AtomicStack; 83 using ObjectStack = AtomicStack<mirror::Object>; 84 class CardTable; 85 class HeapBitmap; 86 class ModUnionTable; 87 class ReadBarrierTable; 88 class RememberedSet; 89 } // namespace accounting 90 91 namespace collector { 92 class ConcurrentCopying; 93 class GarbageCollector; 94 class MarkSweep; 95 class SemiSpace; 96 } // namespace collector 97 98 namespace allocator { 99 class RosAlloc; 100 } // namespace allocator 101 102 namespace space { 103 class AllocSpace; 104 class BumpPointerSpace; 105 class ContinuousMemMapAllocSpace; 106 class DiscontinuousSpace; 107 class DlMallocSpace; 108 class ImageSpace; 109 class LargeObjectSpace; 110 class MallocSpace; 111 class RegionSpace; 112 class RosAllocSpace; 113 class Space; 114 class ZygoteSpace; 115 } // namespace space 116 117 enum HomogeneousSpaceCompactResult { 118 // Success. 119 kSuccess, 120 // Reject due to disabled moving GC. 121 kErrorReject, 122 // Unsupported due to the current configuration. 123 kErrorUnsupported, 124 // System is shutting down. 125 kErrorVMShuttingDown, 126 }; 127 128 // If true, use rosalloc/RosAllocSpace instead of dlmalloc/DlMallocSpace 129 static constexpr bool kUseRosAlloc = true; 130 131 // If true, use thread-local allocation stack. 132 static constexpr bool kUseThreadLocalAllocationStack = false; 133 134 class Heap { 135 public: 136 // How much we grow the TLAB if we can do it. 137 static constexpr size_t kPartialTlabSize = 16 * KB; 138 static constexpr bool kUsePartialTlabs = true; 139 140 static constexpr size_t kDefaultInitialSize = 2 * MB; 141 static constexpr size_t kDefaultMaximumSize = 256 * MB; 142 static constexpr size_t kDefaultNonMovingSpaceCapacity = 64 * MB; 143 static constexpr size_t kDefaultMaxFree = 32 * MB; 144 static constexpr size_t kDefaultMinFree = kDefaultMaxFree / 4; 145 static constexpr size_t kDefaultLongPauseLogThreshold = MsToNs(5); 146 static constexpr size_t kDefaultLongPauseLogThresholdGcStress = MsToNs(50); 147 static constexpr size_t kDefaultLongGCLogThreshold = MsToNs(100); 148 static constexpr size_t kDefaultLongGCLogThresholdGcStress = MsToNs(1000); 149 static constexpr size_t kDefaultTLABSize = 32 * KB; 150 static constexpr double kDefaultTargetUtilization = 0.6; 151 static constexpr double kDefaultHeapGrowthMultiplier = 2.0; 152 // Primitive arrays larger than this size are put in the large object space. 153 // TODO: Preliminary experiments suggest this value might be not optimal. 154 // This might benefit from further investigation. 155 static constexpr size_t kMinLargeObjectThreshold = 12 * KB; 156 static constexpr size_t kDefaultLargeObjectThreshold = kMinLargeObjectThreshold; 157 // Whether or not parallel GC is enabled. If not, then we never create the thread pool. 158 static constexpr bool kDefaultEnableParallelGC = true; 159 static uint8_t* const kPreferredAllocSpaceBegin; 160 161 // Whether or not we use the free list large object space. Only use it if USE_ART_LOW_4G_ALLOCATOR 162 // since this means that we have to use the slow msync loop in MemMap::MapAnonymous. 163 static constexpr space::LargeObjectSpaceType kDefaultLargeObjectSpaceType = 164 USE_ART_LOW_4G_ALLOCATOR ? 165 space::LargeObjectSpaceType::kFreeList 166 : space::LargeObjectSpaceType::kMap; 167 168 // Used so that we don't overflow the allocation time atomic integer. 169 static constexpr size_t kTimeAdjust = 1024; 170 171 // Client should call NotifyNativeAllocation every kNotifyNativeInterval allocations. 172 // Should be chosen so that time_to_call_mallinfo / kNotifyNativeInterval is on the same order 173 // as object allocation time. time_to_call_mallinfo seems to be on the order of 1 usec 174 // on Android. 175 #ifdef __ANDROID__ 176 static constexpr uint32_t kNotifyNativeInterval = 64; 177 #else 178 // Some host mallinfo() implementations are slow. And memory is less scarce. 179 static constexpr uint32_t kNotifyNativeInterval = 384; 180 #endif 181 182 // RegisterNativeAllocation checks immediately whether GC is needed if size exceeds the 183 // following. kCheckImmediatelyThreshold * kNotifyNativeInterval should be small enough to 184 // make it safe to allocate that many bytes between checks. 185 static constexpr size_t kCheckImmediatelyThreshold = (10'000'000 / kNotifyNativeInterval); 186 187 // How often we allow heap trimming to happen (nanoseconds). 188 static constexpr uint64_t kHeapTrimWait = MsToNs(5000); 189 190 // Starting size of DlMalloc/RosAlloc spaces. GetDefaultStartingSize()191 static size_t GetDefaultStartingSize() { 192 return gPageSize; 193 } 194 195 // Whether the transition-GC heap threshold condition applies or not for non-low memory devices. 196 // Stressing GC will bypass the heap threshold condition. 197 DECLARE_RUNTIME_DEBUG_FLAG(kStressCollectorTransition); 198 199 // Create a heap with the requested sizes. The possible empty 200 // image_file_names names specify Spaces to load based on 201 // ImageWriter output. 202 Heap(size_t initial_size, 203 size_t growth_limit, 204 size_t min_free, 205 size_t max_free, 206 double target_utilization, 207 double foreground_heap_growth_multiplier, 208 size_t stop_for_native_allocs, 209 size_t capacity, 210 size_t non_moving_space_capacity, 211 const std::vector<std::string>& boot_class_path, 212 const std::vector<std::string>& boot_class_path_locations, 213 ArrayRef<File> boot_class_path_files, 214 ArrayRef<File> boot_class_path_image_files, 215 ArrayRef<File> boot_class_path_vdex_files, 216 ArrayRef<File> boot_class_path_oat_files, 217 const std::vector<std::string>& image_file_names, 218 InstructionSet image_instruction_set, 219 CollectorType foreground_collector_type, 220 CollectorType background_collector_type, 221 space::LargeObjectSpaceType large_object_space_type, 222 size_t large_object_threshold, 223 size_t parallel_gc_threads, 224 size_t conc_gc_threads, 225 bool low_memory_mode, 226 size_t long_pause_threshold, 227 size_t long_gc_threshold, 228 bool ignore_target_footprint, 229 bool always_log_explicit_gcs, 230 bool use_tlab, 231 bool verify_pre_gc_heap, 232 bool verify_pre_sweeping_heap, 233 bool verify_post_gc_heap, 234 bool verify_pre_gc_rosalloc, 235 bool verify_pre_sweeping_rosalloc, 236 bool verify_post_gc_rosalloc, 237 bool gc_stress_mode, 238 bool measure_gc_performance, 239 bool use_homogeneous_space_compaction, 240 bool use_generational_cc, 241 uint64_t min_interval_homogeneous_space_compaction_by_oom, 242 bool dump_region_info_before_gc, 243 bool dump_region_info_after_gc); 244 245 ~Heap(); 246 247 // Allocates and initializes storage for an object instance. 248 template <bool kInstrumented = true, typename PreFenceVisitor> AllocObject(Thread * self,ObjPtr<mirror::Class> klass,size_t num_bytes,const PreFenceVisitor & pre_fence_visitor)249 mirror::Object* AllocObject(Thread* self, 250 ObjPtr<mirror::Class> klass, 251 size_t num_bytes, 252 const PreFenceVisitor& pre_fence_visitor) 253 REQUIRES_SHARED(Locks::mutator_lock_) 254 REQUIRES(!*gc_complete_lock_, 255 !*pending_task_lock_, 256 !*backtrace_lock_, 257 !process_state_update_lock_, 258 !Roles::uninterruptible_) { 259 return AllocObjectWithAllocator<kInstrumented>(self, 260 klass, 261 num_bytes, 262 GetCurrentAllocator(), 263 pre_fence_visitor); 264 } 265 266 template <bool kInstrumented = true, typename PreFenceVisitor> AllocNonMovableObject(Thread * self,ObjPtr<mirror::Class> klass,size_t num_bytes,const PreFenceVisitor & pre_fence_visitor)267 mirror::Object* AllocNonMovableObject(Thread* self, 268 ObjPtr<mirror::Class> klass, 269 size_t num_bytes, 270 const PreFenceVisitor& pre_fence_visitor) 271 REQUIRES_SHARED(Locks::mutator_lock_) 272 REQUIRES(!*gc_complete_lock_, 273 !*pending_task_lock_, 274 !*backtrace_lock_, 275 !process_state_update_lock_, 276 !Roles::uninterruptible_) { 277 mirror::Object* obj = AllocObjectWithAllocator<kInstrumented>(self, 278 klass, 279 num_bytes, 280 GetCurrentNonMovingAllocator(), 281 pre_fence_visitor); 282 // Java Heap Profiler check and sample allocation. 283 if (GetHeapSampler().IsEnabled()) { 284 JHPCheckNonTlabSampleAllocation(self, obj, num_bytes); 285 } 286 return obj; 287 } 288 289 template <bool kInstrumented = true, bool kCheckLargeObject = true, typename PreFenceVisitor> 290 ALWAYS_INLINE mirror::Object* AllocObjectWithAllocator(Thread* self, 291 ObjPtr<mirror::Class> klass, 292 size_t byte_count, 293 AllocatorType allocator, 294 const PreFenceVisitor& pre_fence_visitor) 295 REQUIRES_SHARED(Locks::mutator_lock_) 296 REQUIRES(!*gc_complete_lock_, 297 !*pending_task_lock_, 298 !*backtrace_lock_, 299 !process_state_update_lock_, 300 !Roles::uninterruptible_); 301 GetCurrentAllocator()302 AllocatorType GetCurrentAllocator() const { 303 return current_allocator_; 304 } 305 GetCurrentNonMovingAllocator()306 AllocatorType GetCurrentNonMovingAllocator() const { 307 return current_non_moving_allocator_; 308 } 309 GetUpdatedAllocator(AllocatorType old_allocator)310 AllocatorType GetUpdatedAllocator(AllocatorType old_allocator) { 311 return (old_allocator == kAllocatorTypeNonMoving) ? 312 GetCurrentNonMovingAllocator() : GetCurrentAllocator(); 313 } 314 315 // Visit all of the live objects in the heap. 316 template <typename Visitor> 317 ALWAYS_INLINE void VisitObjects(Visitor&& visitor) 318 REQUIRES_SHARED(Locks::mutator_lock_) 319 REQUIRES(!Locks::heap_bitmap_lock_, !*gc_complete_lock_); 320 template <typename Visitor> 321 ALWAYS_INLINE void VisitObjectsPaused(Visitor&& visitor) 322 REQUIRES(Locks::mutator_lock_, !Locks::heap_bitmap_lock_, !*gc_complete_lock_); 323 324 void VisitReflectiveTargets(ReflectiveValueVisitor* visitor) 325 REQUIRES(Locks::mutator_lock_, !Locks::heap_bitmap_lock_, !*gc_complete_lock_); 326 327 void CheckPreconditionsForAllocObject(ObjPtr<mirror::Class> c, size_t byte_count) 328 REQUIRES_SHARED(Locks::mutator_lock_); 329 330 // Inform the garbage collector of a non-malloc allocated native memory that might become 331 // reclaimable in the future as a result of Java garbage collection. 332 void RegisterNativeAllocation(JNIEnv* env, size_t bytes) 333 REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_); 334 void RegisterNativeFree(JNIEnv* env, size_t bytes); 335 336 // Notify the garbage collector of malloc allocations that might be reclaimable 337 // as a result of Java garbage collection. Each such call represents approximately 338 // kNotifyNativeInterval such allocations. 339 void NotifyNativeAllocations(JNIEnv* env) 340 REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_); 341 GetNotifyNativeInterval()342 uint32_t GetNotifyNativeInterval() { 343 return kNotifyNativeInterval; 344 } 345 346 // Change the allocator, updates entrypoints. 347 void ChangeAllocator(AllocatorType allocator) 348 REQUIRES(Locks::mutator_lock_, !Locks::runtime_shutdown_lock_); 349 350 // Change the collector to be one of the possible options (MS, CMS, SS). Only safe when no 351 // concurrent accesses to the heap are possible. 352 void ChangeCollector(CollectorType collector_type) 353 REQUIRES(Locks::mutator_lock_, !*gc_complete_lock_); 354 355 // The given reference is believed to be to an object in the Java heap, check the soundness of it. 356 // TODO: NO_THREAD_SAFETY_ANALYSIS since we call this everywhere and it is impossible to find a 357 // proper lock ordering for it. 358 void VerifyObjectBody(ObjPtr<mirror::Object> o) NO_THREAD_SAFETY_ANALYSIS; 359 360 // Consistency check of all live references. 361 void VerifyHeap() REQUIRES(!Locks::heap_bitmap_lock_); 362 // Returns how many failures occured. 363 size_t VerifyHeapReferences(bool verify_referents = true) 364 REQUIRES(Locks::mutator_lock_, !*gc_complete_lock_); 365 bool VerifyMissingCardMarks() 366 REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_); 367 368 // A weaker test than IsLiveObject or VerifyObject that doesn't require the heap lock, 369 // and doesn't abort on error, allowing the caller to report more 370 // meaningful diagnostics. 371 bool IsValidObjectAddress(const void* obj) const REQUIRES_SHARED(Locks::mutator_lock_); 372 373 // Faster alternative to IsHeapAddress since finding if an object is in the large object space is 374 // very slow. 375 bool IsNonDiscontinuousSpaceHeapAddress(const void* addr) const 376 REQUIRES_SHARED(Locks::mutator_lock_); 377 378 // Returns true if 'obj' is a live heap object, false otherwise (including for invalid addresses). 379 // Requires the heap lock to be held. 380 bool IsLiveObjectLocked(ObjPtr<mirror::Object> obj, 381 bool search_allocation_stack = true, 382 bool search_live_stack = true, 383 bool sorted = false) 384 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_); 385 386 // Returns true if there is any chance that the object (obj) will move. 387 bool IsMovableObject(ObjPtr<mirror::Object> obj) const REQUIRES_SHARED(Locks::mutator_lock_); 388 389 // Enables us to compacting GC until objects are released. 390 EXPORT void IncrementDisableMovingGC(Thread* self) REQUIRES(!*gc_complete_lock_); 391 EXPORT void DecrementDisableMovingGC(Thread* self) REQUIRES(!*gc_complete_lock_); 392 393 // Temporarily disable thread flip for JNI critical calls. 394 void IncrementDisableThreadFlip(Thread* self) REQUIRES(!*thread_flip_lock_); 395 void DecrementDisableThreadFlip(Thread* self) REQUIRES(!*thread_flip_lock_); 396 void ThreadFlipBegin(Thread* self) REQUIRES(!*thread_flip_lock_); 397 void ThreadFlipEnd(Thread* self) REQUIRES(!*thread_flip_lock_); 398 399 // Ensures that the obj doesn't cause userfaultfd in JNI critical calls. 400 void EnsureObjectUserfaulted(ObjPtr<mirror::Object> obj) REQUIRES_SHARED(Locks::mutator_lock_); 401 402 // Clear all of the mark bits, doesn't clear bitmaps which have the same live bits as mark bits. 403 // Mutator lock is required for GetContinuousSpaces. 404 void ClearMarkedObjects(bool release_eagerly = true) 405 REQUIRES(Locks::heap_bitmap_lock_) 406 REQUIRES_SHARED(Locks::mutator_lock_); 407 408 // Initiates an explicit garbage collection. Guarantees that a GC started after this call has 409 // completed. 410 EXPORT void CollectGarbage(bool clear_soft_references, GcCause cause = kGcCauseExplicit) 411 REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_); 412 413 // Does a concurrent GC, provided the GC numbered requested_gc_num has not already been 414 // completed. Should only be called by the GC daemon thread through runtime. 415 void ConcurrentGC(Thread* self, GcCause cause, bool force_full, uint32_t requested_gc_num) 416 REQUIRES(!Locks::runtime_shutdown_lock_, !*gc_complete_lock_, 417 !*pending_task_lock_, !process_state_update_lock_); 418 419 // Implements VMDebug.countInstancesOfClass and JDWP VM_InstanceCount. 420 // The boolean decides whether to use IsAssignableFrom or == when comparing classes. 421 void CountInstances(const std::vector<Handle<mirror::Class>>& classes, 422 bool use_is_assignable_from, 423 uint64_t* counts) 424 REQUIRES(!Locks::heap_bitmap_lock_, !*gc_complete_lock_) 425 REQUIRES_SHARED(Locks::mutator_lock_); 426 427 // Removes the growth limit on the alloc space so it may grow to its maximum capacity. Used to 428 // implement dalvik.system.VMRuntime.clearGrowthLimit. 429 void ClearGrowthLimit() REQUIRES(!*gc_complete_lock_); 430 431 // Make the current growth limit the new maximum capacity, unmaps pages at the end of spaces 432 // which will never be used. Used to implement dalvik.system.VMRuntime.clampGrowthLimit. 433 void ClampGrowthLimit() REQUIRES(!Locks::heap_bitmap_lock_); 434 435 // Target ideal heap utilization ratio, implements 436 // dalvik.system.VMRuntime.getTargetHeapUtilization. GetTargetHeapUtilization()437 double GetTargetHeapUtilization() const { 438 return target_utilization_; 439 } 440 441 // Data structure memory usage tracking. 442 void RegisterGCAllocation(size_t bytes); 443 void RegisterGCDeAllocation(size_t bytes); 444 445 // Set the heap's private space pointers to be the same as the space based on it's type. Public 446 // due to usage by tests. 447 void SetSpaceAsDefault(space::ContinuousSpace* continuous_space) 448 REQUIRES(!Locks::heap_bitmap_lock_); 449 void AddSpace(space::Space* space) 450 REQUIRES(!Locks::heap_bitmap_lock_) 451 REQUIRES(Locks::mutator_lock_); 452 void RemoveSpace(space::Space* space) 453 REQUIRES(!Locks::heap_bitmap_lock_) 454 REQUIRES(Locks::mutator_lock_); 455 GetPreGcWeightedAllocatedBytes()456 double GetPreGcWeightedAllocatedBytes() const { 457 return pre_gc_weighted_allocated_bytes_; 458 } 459 GetPostGcWeightedAllocatedBytes()460 double GetPostGcWeightedAllocatedBytes() const { 461 return post_gc_weighted_allocated_bytes_; 462 } 463 464 void CalculatePreGcWeightedAllocatedBytes(); 465 void CalculatePostGcWeightedAllocatedBytes(); 466 uint64_t GetTotalGcCpuTime(); 467 GetProcessCpuStartTime()468 uint64_t GetProcessCpuStartTime() const { 469 return process_cpu_start_time_ns_; 470 } 471 GetPostGCLastProcessCpuTime()472 uint64_t GetPostGCLastProcessCpuTime() const { 473 return post_gc_last_process_cpu_time_ns_; 474 } 475 476 // Set target ideal heap utilization ratio, implements 477 // dalvik.system.VMRuntime.setTargetHeapUtilization. 478 void SetTargetHeapUtilization(float target); 479 480 // For the alloc space, sets the maximum number of bytes that the heap is allowed to allocate 481 // from the system. Doesn't allow the space to exceed its growth limit. 482 // Set while we hold gc_complete_lock or collector_type_running_ != kCollectorTypeNone. 483 void SetIdealFootprint(size_t max_allowed_footprint); 484 485 // Blocks the caller until the garbage collector becomes idle and returns the type of GC we 486 // waited for. Only waits for running collections, ignoring a requested but unstarted GC. Only 487 // heuristic, since a new GC may have started by the time we return. However, if we hold the 488 // mutator lock, even in shared mode, a new GC can't get very far, so long as we keep it. 489 EXPORT collector::GcType WaitForGcToComplete(GcCause cause, Thread* self) 490 REQUIRES(!*gc_complete_lock_); 491 492 // Update the heap's process state to a new value, may cause compaction to occur. 493 void UpdateProcessState(ProcessState old_process_state, ProcessState new_process_state) 494 REQUIRES(!*pending_task_lock_, !*gc_complete_lock_, !process_state_update_lock_); 495 HaveContinuousSpaces()496 bool HaveContinuousSpaces() const NO_THREAD_SAFETY_ANALYSIS { 497 // No lock since vector empty is thread safe. 498 return !continuous_spaces_.empty(); 499 } 500 GetContinuousSpaces()501 const std::vector<space::ContinuousSpace*>& GetContinuousSpaces() const 502 REQUIRES_SHARED(Locks::mutator_lock_) { 503 return continuous_spaces_; 504 } 505 GetDiscontinuousSpaces()506 const std::vector<space::DiscontinuousSpace*>& GetDiscontinuousSpaces() const 507 REQUIRES_SHARED(Locks::mutator_lock_) { 508 return discontinuous_spaces_; 509 } 510 GetCurrentGcIteration()511 const collector::Iteration* GetCurrentGcIteration() const { 512 return ¤t_gc_iteration_; 513 } GetCurrentGcIteration()514 collector::Iteration* GetCurrentGcIteration() { 515 return ¤t_gc_iteration_; 516 } 517 518 // Enable verification of object references when the runtime is sufficiently initialized. EnableObjectValidation()519 void EnableObjectValidation() { 520 verify_object_mode_ = kVerifyObjectSupport; 521 if (verify_object_mode_ > kVerifyObjectModeDisabled) { 522 VerifyHeap(); 523 } 524 } 525 526 // Disable object reference verification for image writing. DisableObjectValidation()527 void DisableObjectValidation() { 528 verify_object_mode_ = kVerifyObjectModeDisabled; 529 } 530 531 // Other checks may be performed if we know the heap should be in a healthy state. IsObjectValidationEnabled()532 bool IsObjectValidationEnabled() const { 533 return verify_object_mode_ > kVerifyObjectModeDisabled; 534 } 535 536 // Returns true if low memory mode is enabled. IsLowMemoryMode()537 bool IsLowMemoryMode() const { 538 return low_memory_mode_; 539 } 540 541 // Returns the heap growth multiplier, this affects how much we grow the heap after a GC. 542 // Scales heap growth, min free, and max free. 543 double HeapGrowthMultiplier() const; 544 545 // Freed bytes can be negative in cases where we copy objects from a compacted space to a 546 // free-list backed space. 547 void RecordFree(uint64_t freed_objects, int64_t freed_bytes); 548 549 // Record the bytes freed by thread-local buffer revoke. 550 void RecordFreeRevoke(); 551 GetCardTable()552 accounting::CardTable* GetCardTable() const { 553 return card_table_.get(); 554 } 555 GetReadBarrierTable()556 accounting::ReadBarrierTable* GetReadBarrierTable() const { 557 return rb_table_.get(); 558 } 559 560 EXPORT void AddFinalizerReference(Thread* self, ObjPtr<mirror::Object>* object); 561 562 // Returns the number of bytes currently allocated. 563 // The result should be treated as an approximation, if it is being concurrently updated. GetBytesAllocated()564 size_t GetBytesAllocated() const { 565 return num_bytes_allocated_.load(std::memory_order_relaxed); 566 } 567 568 // Returns bytes_allocated before adding 'bytes' to it. AddBytesAllocated(size_t bytes)569 size_t AddBytesAllocated(size_t bytes) { 570 return num_bytes_allocated_.fetch_add(bytes, std::memory_order_relaxed); 571 } 572 GetUseGenerationalCC()573 bool GetUseGenerationalCC() const { 574 return use_generational_cc_; 575 } 576 577 // Returns the number of objects currently allocated. 578 size_t GetObjectsAllocated() const 579 REQUIRES(!Locks::heap_bitmap_lock_); 580 581 // Returns the total number of bytes allocated since the heap was created. 582 uint64_t GetBytesAllocatedEver() const; 583 584 // Returns the total number of bytes freed since the heap was created. 585 // Can decrease over time, and may even be negative, since moving an object to 586 // a space in which it occupies more memory results in negative "freed bytes". 587 // With default memory order, this should be viewed only as a hint. 588 int64_t GetBytesFreedEver(std::memory_order mo = std::memory_order_relaxed) const { 589 return total_bytes_freed_ever_.load(mo); 590 } 591 GetRegionSpace()592 space::RegionSpace* GetRegionSpace() const { 593 return region_space_; 594 } 595 GetBumpPointerSpace()596 space::BumpPointerSpace* GetBumpPointerSpace() const { 597 return bump_pointer_space_; 598 } 599 // Implements java.lang.Runtime.maxMemory, returning the maximum amount of memory a program can 600 // consume. For a regular VM this would relate to the -Xmx option and would return -1 if no Xmx 601 // were specified. Android apps start with a growth limit (small heap size) which is 602 // cleared/extended for large apps. GetMaxMemory()603 size_t GetMaxMemory() const { 604 // There are some race conditions in the allocation code that can cause bytes allocated to 605 // become larger than growth_limit_ in rare cases. 606 return std::max(GetBytesAllocated(), growth_limit_); 607 } 608 609 // Implements java.lang.Runtime.totalMemory, returning approximate amount of memory currently 610 // consumed by an application. 611 EXPORT size_t GetTotalMemory() const; 612 613 // Returns approximately how much free memory we have until the next GC happens. GetFreeMemoryUntilGC()614 size_t GetFreeMemoryUntilGC() const { 615 return UnsignedDifference(target_footprint_.load(std::memory_order_relaxed), 616 GetBytesAllocated()); 617 } 618 619 // Returns approximately how much free memory we have until the next OOME happens. GetFreeMemoryUntilOOME()620 size_t GetFreeMemoryUntilOOME() const { 621 return UnsignedDifference(growth_limit_, GetBytesAllocated()); 622 } 623 624 // Returns how much free memory we have until we need to grow the heap to perform an allocation. 625 // Similar to GetFreeMemoryUntilGC. Implements java.lang.Runtime.freeMemory. GetFreeMemory()626 size_t GetFreeMemory() const { 627 return UnsignedDifference(GetTotalMemory(), 628 num_bytes_allocated_.load(std::memory_order_relaxed)); 629 } 630 631 // Get the space that corresponds to an object's address. Current implementation searches all 632 // spaces in turn. If fail_ok is false then failing to find a space will cause an abort. 633 // TODO: consider using faster data structure like binary tree. 634 EXPORT space::ContinuousSpace* FindContinuousSpaceFromObject(ObjPtr<mirror::Object>, 635 bool fail_ok) const 636 REQUIRES_SHARED(Locks::mutator_lock_); 637 638 space::ContinuousSpace* FindContinuousSpaceFromAddress(const mirror::Object* addr) const 639 REQUIRES_SHARED(Locks::mutator_lock_); 640 641 space::DiscontinuousSpace* FindDiscontinuousSpaceFromObject(ObjPtr<mirror::Object>, 642 bool fail_ok) const 643 REQUIRES_SHARED(Locks::mutator_lock_); 644 645 EXPORT space::Space* FindSpaceFromObject(ObjPtr<mirror::Object> obj, bool fail_ok) const 646 REQUIRES_SHARED(Locks::mutator_lock_); 647 648 space::Space* FindSpaceFromAddress(const void* ptr) const 649 REQUIRES_SHARED(Locks::mutator_lock_); 650 651 std::string DumpSpaceNameFromAddress(const void* addr) const 652 REQUIRES_SHARED(Locks::mutator_lock_); 653 654 void DumpForSigQuit(std::ostream& os) REQUIRES(!*gc_complete_lock_); 655 656 // Do a pending collector transition. 657 void DoPendingCollectorTransition() 658 REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_); 659 660 // Deflate monitors, ... and trim the spaces. 661 EXPORT void Trim(Thread* self) REQUIRES(!*gc_complete_lock_); 662 663 void RevokeThreadLocalBuffers(Thread* thread); 664 void RevokeRosAllocThreadLocalBuffers(Thread* thread); 665 void RevokeAllThreadLocalBuffers(); 666 void AssertThreadLocalBuffersAreRevoked(Thread* thread); 667 void AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked(); 668 void RosAllocVerification(TimingLogger* timings, const char* name) 669 REQUIRES(Locks::mutator_lock_); 670 GetLiveBitmap()671 accounting::HeapBitmap* GetLiveBitmap() REQUIRES_SHARED(Locks::heap_bitmap_lock_) { 672 return live_bitmap_.get(); 673 } 674 GetMarkBitmap()675 accounting::HeapBitmap* GetMarkBitmap() REQUIRES_SHARED(Locks::heap_bitmap_lock_) { 676 return mark_bitmap_.get(); 677 } 678 GetLiveStack()679 accounting::ObjectStack* GetLiveStack() REQUIRES_SHARED(Locks::heap_bitmap_lock_) { 680 return live_stack_.get(); 681 } 682 GetAllocationStack()683 accounting::ObjectStack* GetAllocationStack() REQUIRES_SHARED(Locks::heap_bitmap_lock_) { 684 return allocation_stack_.get(); 685 } 686 687 void PreZygoteFork() NO_THREAD_SAFETY_ANALYSIS; 688 689 // Mark and empty stack. 690 EXPORT void FlushAllocStack() REQUIRES_SHARED(Locks::mutator_lock_) 691 REQUIRES(Locks::heap_bitmap_lock_); 692 693 // Revoke all the thread-local allocation stacks. 694 EXPORT void RevokeAllThreadLocalAllocationStacks(Thread* self) 695 REQUIRES(Locks::mutator_lock_, !Locks::runtime_shutdown_lock_, !Locks::thread_list_lock_); 696 697 // Mark all the objects in the allocation stack in the specified bitmap. 698 // TODO: Refactor? 699 void MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1, 700 accounting::ContinuousSpaceBitmap* bitmap2, 701 accounting::LargeObjectBitmap* large_objects, 702 accounting::ObjectStack* stack) 703 REQUIRES_SHARED(Locks::mutator_lock_) 704 REQUIRES(Locks::heap_bitmap_lock_); 705 706 // Mark the specified allocation stack as live. 707 void MarkAllocStackAsLive(accounting::ObjectStack* stack) 708 REQUIRES_SHARED(Locks::mutator_lock_) 709 REQUIRES(Locks::heap_bitmap_lock_); 710 711 // Unbind any bound bitmaps. 712 void UnBindBitmaps() 713 REQUIRES(Locks::heap_bitmap_lock_) 714 REQUIRES_SHARED(Locks::mutator_lock_); 715 716 // Returns the boot image spaces. There may be multiple boot image spaces. GetBootImageSpaces()717 const std::vector<space::ImageSpace*>& GetBootImageSpaces() const { 718 return boot_image_spaces_; 719 } 720 721 // TODO(b/260881207): refactor to only use this function in debug builds and 722 // remove EXPORT. 723 EXPORT bool ObjectIsInBootImageSpace(ObjPtr<mirror::Object> obj) const 724 REQUIRES_SHARED(Locks::mutator_lock_); 725 726 bool IsInBootImageOatFile(const void* p) const 727 REQUIRES_SHARED(Locks::mutator_lock_); 728 729 // Get the start address of the boot images if any; otherwise returns 0. GetBootImagesStartAddress()730 uint32_t GetBootImagesStartAddress() const { 731 return boot_images_start_address_; 732 } 733 734 // Get the size of all boot images, including the heap and oat areas. GetBootImagesSize()735 uint32_t GetBootImagesSize() const { 736 return boot_images_size_; 737 } 738 739 // Check if a pointer points to a boot image. IsBootImageAddress(const void * p)740 bool IsBootImageAddress(const void* p) const { 741 return reinterpret_cast<uintptr_t>(p) - boot_images_start_address_ < boot_images_size_; 742 } 743 GetDlMallocSpace()744 space::DlMallocSpace* GetDlMallocSpace() const { 745 return dlmalloc_space_; 746 } 747 GetRosAllocSpace()748 space::RosAllocSpace* GetRosAllocSpace() const { 749 return rosalloc_space_; 750 } 751 752 // Return the corresponding rosalloc space. 753 space::RosAllocSpace* GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const 754 REQUIRES_SHARED(Locks::mutator_lock_); 755 GetNonMovingSpace()756 space::MallocSpace* GetNonMovingSpace() const { 757 return non_moving_space_; 758 } 759 GetLargeObjectsSpace()760 space::LargeObjectSpace* GetLargeObjectsSpace() const { 761 return large_object_space_; 762 } 763 764 // Returns the free list space that may contain movable objects (the 765 // one that's not the non-moving space), either rosalloc_space_ or 766 // dlmalloc_space_. GetPrimaryFreeListSpace()767 space::MallocSpace* GetPrimaryFreeListSpace() { 768 if (kUseRosAlloc) { 769 DCHECK(rosalloc_space_ != nullptr); 770 // reinterpret_cast is necessary as the space class hierarchy 771 // isn't known (#included) yet here. 772 return reinterpret_cast<space::MallocSpace*>(rosalloc_space_); 773 } else { 774 DCHECK(dlmalloc_space_ != nullptr); 775 return reinterpret_cast<space::MallocSpace*>(dlmalloc_space_); 776 } 777 } 778 779 void DumpSpaces(std::ostream& stream) const REQUIRES_SHARED(Locks::mutator_lock_); 780 EXPORT std::string DumpSpaces() const REQUIRES_SHARED(Locks::mutator_lock_); 781 782 // GC performance measuring 783 void DumpGcPerformanceInfo(std::ostream& os) 784 REQUIRES(!*gc_complete_lock_); 785 void ResetGcPerformanceInfo() REQUIRES(!*gc_complete_lock_); 786 787 // Thread pool. Create either the given number of threads, or as per the 788 // values of conc_gc_threads_ and parallel_gc_threads_. 789 void CreateThreadPool(size_t num_threads = 0); 790 void WaitForWorkersToBeCreated(); 791 void DeleteThreadPool(); GetThreadPool()792 ThreadPool* GetThreadPool() { 793 return thread_pool_.get(); 794 } GetParallelGCThreadCount()795 size_t GetParallelGCThreadCount() const { 796 return parallel_gc_threads_; 797 } GetConcGCThreadCount()798 size_t GetConcGCThreadCount() const { 799 return conc_gc_threads_; 800 } 801 accounting::ModUnionTable* FindModUnionTableFromSpace(space::Space* space); 802 void AddModUnionTable(accounting::ModUnionTable* mod_union_table); 803 804 accounting::RememberedSet* FindRememberedSetFromSpace(space::Space* space); 805 void AddRememberedSet(accounting::RememberedSet* remembered_set); 806 // Also deletes the remebered set. 807 void RemoveRememberedSet(space::Space* space); 808 809 bool IsCompilingBoot() const; HasBootImageSpace()810 bool HasBootImageSpace() const { 811 return !boot_image_spaces_.empty(); 812 } 813 bool HasAppImageSpaceFor(const std::string& dex_location) const; 814 GetReferenceProcessor()815 ReferenceProcessor* GetReferenceProcessor() { 816 return reference_processor_.get(); 817 } GetTaskProcessor()818 TaskProcessor* GetTaskProcessor() { 819 return task_processor_.get(); 820 } 821 HasZygoteSpace()822 bool HasZygoteSpace() const { 823 return zygote_space_ != nullptr; 824 } 825 826 // Returns the active concurrent copying collector. ConcurrentCopyingCollector()827 collector::ConcurrentCopying* ConcurrentCopyingCollector() { 828 collector::ConcurrentCopying* active_collector = 829 active_concurrent_copying_collector_.load(std::memory_order_relaxed); 830 if (use_generational_cc_) { 831 DCHECK((active_collector == concurrent_copying_collector_) || 832 (active_collector == young_concurrent_copying_collector_)) 833 << "active_concurrent_copying_collector: " << active_collector 834 << " young_concurrent_copying_collector: " << young_concurrent_copying_collector_ 835 << " concurrent_copying_collector: " << concurrent_copying_collector_; 836 } else { 837 DCHECK_EQ(active_collector, concurrent_copying_collector_); 838 } 839 return active_collector; 840 } 841 MarkCompactCollector()842 collector::MarkCompact* MarkCompactCollector() { 843 DCHECK(!gUseUserfaultfd || mark_compact_ != nullptr); 844 return mark_compact_; 845 } 846 IsPerformingUffdCompaction()847 bool IsPerformingUffdCompaction() { return gUseUserfaultfd && mark_compact_->IsCompacting(); } 848 CurrentCollectorType()849 CollectorType CurrentCollectorType() const { 850 DCHECK(!gUseUserfaultfd || collector_type_ == kCollectorTypeCMC); 851 return collector_type_; 852 } 853 IsMovingGc()854 bool IsMovingGc() const { return IsMovingGc(CurrentCollectorType()); } 855 GetForegroundCollectorType()856 CollectorType GetForegroundCollectorType() const { return foreground_collector_type_; } 857 // EXPORT is needed to make this method visible for libartservice. 858 EXPORT std::string GetForegroundCollectorName(); 859 IsGcConcurrentAndMoving()860 bool IsGcConcurrentAndMoving() const { 861 if (IsGcConcurrent() && IsMovingGc(collector_type_)) { 862 // Assume no transition when a concurrent moving collector is used. 863 DCHECK_EQ(collector_type_, foreground_collector_type_); 864 return true; 865 } 866 return false; 867 } 868 IsMovingGCDisabled(Thread * self)869 bool IsMovingGCDisabled(Thread* self) REQUIRES(!*gc_complete_lock_) { 870 MutexLock mu(self, *gc_complete_lock_); 871 return disable_moving_gc_count_ > 0; 872 } 873 874 // Request an asynchronous trim. 875 void RequestTrim(Thread* self) REQUIRES(!*pending_task_lock_); 876 877 // Retrieve the current GC number, i.e. the number n such that we completed n GCs so far. 878 // Provides acquire ordering, so that if we read this first, and then check whether a GC is 879 // required, we know that the GC number read actually preceded the test. GetCurrentGcNum()880 uint32_t GetCurrentGcNum() { 881 return gcs_completed_.load(std::memory_order_acquire); 882 } 883 884 // Request asynchronous GC. Observed_gc_num is the value of GetCurrentGcNum() when we started to 885 // evaluate the GC triggering condition. If a GC has been completed since then, we consider our 886 // job done. If we return true, then we ensured that gcs_completed_ will eventually be 887 // incremented beyond observed_gc_num. We return false only in corner cases in which we cannot 888 // ensure that. 889 bool RequestConcurrentGC(Thread* self, GcCause cause, bool force_full, uint32_t observed_gc_num) 890 REQUIRES(!*pending_task_lock_); 891 892 // Whether or not we may use a garbage collector, used so that we only create collectors we need. 893 bool MayUseCollector(CollectorType type) const; 894 895 // Used by tests to reduce timinig-dependent flakiness in OOME behavior. SetMinIntervalHomogeneousSpaceCompactionByOom(uint64_t interval)896 void SetMinIntervalHomogeneousSpaceCompactionByOom(uint64_t interval) { 897 min_interval_homogeneous_space_compaction_by_oom_ = interval; 898 } 899 900 // Helpers for android.os.Debug.getRuntimeStat(). 901 uint64_t GetGcCount() const; 902 uint64_t GetGcTime() const; 903 uint64_t GetBlockingGcCount() const; 904 uint64_t GetBlockingGcTime() const; 905 void DumpGcCountRateHistogram(std::ostream& os) const REQUIRES(!*gc_complete_lock_); 906 void DumpBlockingGcCountRateHistogram(std::ostream& os) const REQUIRES(!*gc_complete_lock_); GetTotalTimeWaitingForGC()907 uint64_t GetTotalTimeWaitingForGC() const { 908 return total_wait_time_; 909 } 910 uint64_t GetPreOomeGcCount() const; 911 912 // Perfetto Art Heap Profiler Support. GetHeapSampler()913 HeapSampler& GetHeapSampler() { 914 return heap_sampler_; 915 } 916 917 void InitPerfettoJavaHeapProf(); 918 // In NonTlab case: Check whether we should report a sample allocation and if so report it. 919 // Also update state (bytes_until_sample). 920 // By calling JHPCheckNonTlabSampleAllocation from different functions for Large allocations and 921 // non-moving allocations we are able to use the stack to identify these allocations separately. 922 EXPORT void JHPCheckNonTlabSampleAllocation(Thread* self, mirror::Object* ret, size_t alloc_size); 923 // In Tlab case: Calculate the next tlab size (location of next sample point) and whether 924 // a sample should be taken. 925 size_t JHPCalculateNextTlabSize(Thread* self, 926 size_t jhp_def_tlab_size, 927 size_t alloc_size, 928 bool* take_sample, 929 size_t* bytes_until_sample); 930 // Reduce the number of bytes to the next sample position by this adjustment. 931 void AdjustSampleOffset(size_t adjustment); 932 933 // Allocation tracking support 934 // Callers to this function use double-checked locking to ensure safety on allocation_records_ IsAllocTrackingEnabled()935 bool IsAllocTrackingEnabled() const { 936 return alloc_tracking_enabled_.load(std::memory_order_relaxed); 937 } 938 SetAllocTrackingEnabled(bool enabled)939 void SetAllocTrackingEnabled(bool enabled) REQUIRES(Locks::alloc_tracker_lock_) { 940 alloc_tracking_enabled_.store(enabled, std::memory_order_relaxed); 941 } 942 943 // Return the current stack depth of allocation records. GetAllocTrackerStackDepth()944 size_t GetAllocTrackerStackDepth() const { 945 return alloc_record_depth_; 946 } 947 948 // Return the current stack depth of allocation records. SetAllocTrackerStackDepth(size_t alloc_record_depth)949 void SetAllocTrackerStackDepth(size_t alloc_record_depth) { 950 alloc_record_depth_ = alloc_record_depth; 951 } 952 GetAllocationRecords()953 AllocRecordObjectMap* GetAllocationRecords() const REQUIRES(Locks::alloc_tracker_lock_) { 954 return allocation_records_.get(); 955 } 956 957 void SetAllocationRecords(AllocRecordObjectMap* records) 958 REQUIRES(Locks::alloc_tracker_lock_); 959 960 void VisitAllocationRecords(RootVisitor* visitor) const 961 REQUIRES_SHARED(Locks::mutator_lock_) 962 REQUIRES(!Locks::alloc_tracker_lock_); 963 964 void SweepAllocationRecords(IsMarkedVisitor* visitor) const 965 REQUIRES_SHARED(Locks::mutator_lock_) 966 REQUIRES(!Locks::alloc_tracker_lock_); 967 968 void DisallowNewAllocationRecords() const 969 REQUIRES_SHARED(Locks::mutator_lock_) 970 REQUIRES(!Locks::alloc_tracker_lock_); 971 972 void AllowNewAllocationRecords() const 973 REQUIRES_SHARED(Locks::mutator_lock_) 974 REQUIRES(!Locks::alloc_tracker_lock_); 975 976 void BroadcastForNewAllocationRecords() const 977 REQUIRES(!Locks::alloc_tracker_lock_); 978 979 void DisableGCForShutdown() REQUIRES(!*gc_complete_lock_); 980 bool IsGCDisabledForShutdown() const REQUIRES(!*gc_complete_lock_); 981 982 // Create a new alloc space and compact default alloc space to it. 983 EXPORT HomogeneousSpaceCompactResult PerformHomogeneousSpaceCompact() 984 REQUIRES(!*gc_complete_lock_, !process_state_update_lock_); 985 EXPORT bool SupportHomogeneousSpaceCompactAndCollectorTransitions() const; 986 987 // Install an allocation listener. 988 EXPORT void SetAllocationListener(AllocationListener* l); 989 // Remove an allocation listener. Note: the listener must not be deleted, as for performance 990 // reasons, we assume it stays valid when we read it (so that we don't require a lock). 991 EXPORT void RemoveAllocationListener(); 992 993 // Install a gc pause listener. 994 EXPORT void SetGcPauseListener(GcPauseListener* l); 995 // Get the currently installed gc pause listener, or null. GetGcPauseListener()996 GcPauseListener* GetGcPauseListener() { 997 return gc_pause_listener_.load(std::memory_order_acquire); 998 } 999 // Remove a gc pause listener. Note: the listener must not be deleted, as for performance 1000 // reasons, we assume it stays valid when we read it (so that we don't require a lock). 1001 EXPORT void RemoveGcPauseListener(); 1002 1003 EXPORT const Verification* GetVerification() const; 1004 1005 void PostForkChildAction(Thread* self) REQUIRES(!*gc_complete_lock_); 1006 1007 EXPORT void TraceHeapSize(size_t heap_size); 1008 1009 bool AddHeapTask(gc::HeapTask* task); 1010 1011 // TODO: Kernels for arm and x86 in both, 32-bit and 64-bit modes use 512 entries per page-table 1012 // page. Find a way to confirm that in userspace. 1013 // Address range covered by 1 Page Middle Directory (PMD) entry in the page table GetPMDSize()1014 static inline ALWAYS_INLINE size_t GetPMDSize() { 1015 return (gPageSize / sizeof(uint64_t)) * gPageSize; 1016 } 1017 // Address range covered by 1 Page Upper Directory (PUD) entry in the page table GetPUDSize()1018 static inline ALWAYS_INLINE size_t GetPUDSize() { 1019 return (gPageSize / sizeof(uint64_t)) * GetPMDSize(); 1020 } 1021 1022 // Returns the ideal alignment corresponding to page-table levels for the 1023 // given size. BestPageTableAlignment(size_t size)1024 static inline size_t BestPageTableAlignment(size_t size) { 1025 const size_t pud_size = GetPUDSize(); 1026 const size_t pmd_size = GetPMDSize(); 1027 return size < pud_size ? pmd_size : pud_size; 1028 } 1029 1030 private: 1031 class ConcurrentGCTask; 1032 class CollectorTransitionTask; 1033 class HeapTrimTask; 1034 class TriggerPostForkCCGcTask; 1035 class ReduceTargetFootprintTask; 1036 1037 // Compact source space to target space. Returns the collector used. 1038 collector::GarbageCollector* Compact(space::ContinuousMemMapAllocSpace* target_space, 1039 space::ContinuousMemMapAllocSpace* source_space, 1040 GcCause gc_cause) 1041 REQUIRES(Locks::mutator_lock_); 1042 1043 void LogGC(GcCause gc_cause, collector::GarbageCollector* collector); 1044 void StartGC(Thread* self, GcCause cause, CollectorType collector_type) 1045 REQUIRES(!*gc_complete_lock_); 1046 void StartGCRunnable(Thread* self, GcCause cause, CollectorType collector_type) 1047 REQUIRES(!*gc_complete_lock_) REQUIRES_SHARED(Locks::mutator_lock_); 1048 void FinishGC(Thread* self, collector::GcType gc_type) REQUIRES(!*gc_complete_lock_); 1049 1050 double CalculateGcWeightedAllocatedBytes(uint64_t gc_last_process_cpu_time_ns, 1051 uint64_t current_process_cpu_time) const; 1052 1053 // Create a mem map with a preferred base address. 1054 static MemMap MapAnonymousPreferredAddress(const char* name, 1055 uint8_t* request_begin, 1056 size_t capacity, 1057 std::string* out_error_str); 1058 SupportHSpaceCompaction()1059 bool SupportHSpaceCompaction() const { 1060 // Returns true if we can do hspace compaction 1061 return main_space_backup_ != nullptr; 1062 } 1063 1064 // Size_t saturating arithmetic UnsignedDifference(size_t x,size_t y)1065 static ALWAYS_INLINE size_t UnsignedDifference(size_t x, size_t y) { 1066 return x > y ? x - y : 0; 1067 } UnsignedSum(size_t x,size_t y)1068 static ALWAYS_INLINE size_t UnsignedSum(size_t x, size_t y) { 1069 return x + y >= x ? x + y : std::numeric_limits<size_t>::max(); 1070 } 1071 AllocatorHasAllocationStack(AllocatorType allocator_type)1072 static ALWAYS_INLINE bool AllocatorHasAllocationStack(AllocatorType allocator_type) { 1073 return 1074 allocator_type != kAllocatorTypeRegionTLAB && 1075 allocator_type != kAllocatorTypeBumpPointer && 1076 allocator_type != kAllocatorTypeTLAB && 1077 allocator_type != kAllocatorTypeRegion; 1078 } IsMovingGc(CollectorType collector_type)1079 static bool IsMovingGc(CollectorType collector_type) { 1080 return 1081 collector_type == kCollectorTypeCC || 1082 collector_type == kCollectorTypeSS || 1083 collector_type == kCollectorTypeCMC || 1084 collector_type == kCollectorTypeCCBackground || 1085 collector_type == kCollectorTypeCMCBackground || 1086 collector_type == kCollectorTypeHomogeneousSpaceCompact; 1087 } 1088 bool ShouldAllocLargeObject(ObjPtr<mirror::Class> c, size_t byte_count) const 1089 REQUIRES_SHARED(Locks::mutator_lock_); 1090 1091 // Checks whether we should garbage collect: 1092 ALWAYS_INLINE bool ShouldConcurrentGCForJava(size_t new_num_bytes_allocated); 1093 float NativeMemoryOverTarget(size_t current_native_bytes, bool is_gc_concurrent); 1094 void CheckGCForNative(Thread* self) 1095 REQUIRES(!*pending_task_lock_, !*gc_complete_lock_, !process_state_update_lock_); 1096 GetMarkStack()1097 accounting::ObjectStack* GetMarkStack() { 1098 return mark_stack_.get(); 1099 } 1100 1101 // We don't force this to be inlined since it is a slow path. 1102 template <bool kInstrumented, typename PreFenceVisitor> 1103 mirror::Object* AllocLargeObject(Thread* self, 1104 ObjPtr<mirror::Class>* klass, 1105 size_t byte_count, 1106 const PreFenceVisitor& pre_fence_visitor) 1107 REQUIRES_SHARED(Locks::mutator_lock_) 1108 REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, 1109 !*backtrace_lock_, !process_state_update_lock_); 1110 1111 // Handles Allocate()'s slow allocation path with GC involved after an initial allocation 1112 // attempt failed. 1113 // Called with thread suspension disallowed, but re-enables it, and may suspend, internally. 1114 // Returns null if instrumentation or the allocator changed. 1115 EXPORT mirror::Object* AllocateInternalWithGc(Thread* self, 1116 AllocatorType allocator, 1117 bool instrumented, 1118 size_t num_bytes, 1119 size_t* bytes_allocated, 1120 size_t* usable_size, 1121 size_t* bytes_tl_bulk_allocated, 1122 ObjPtr<mirror::Class>* klass) 1123 REQUIRES(!Locks::thread_suspend_count_lock_, !*gc_complete_lock_, !*pending_task_lock_) 1124 REQUIRES(Roles::uninterruptible_) REQUIRES_SHARED(Locks::mutator_lock_); 1125 1126 // Allocate into a specific space. 1127 mirror::Object* AllocateInto(Thread* self, 1128 space::AllocSpace* space, 1129 ObjPtr<mirror::Class> c, 1130 size_t bytes) 1131 REQUIRES_SHARED(Locks::mutator_lock_); 1132 1133 // Need to do this with mutators paused so that somebody doesn't accidentally allocate into the 1134 // wrong space. 1135 void SwapSemiSpaces() REQUIRES(Locks::mutator_lock_); 1136 1137 // Try to allocate a number of bytes, this function never does any GCs. Needs to be inlined so 1138 // that the switch statement is constant optimized in the entrypoints. 1139 template <const bool kInstrumented, const bool kGrow> 1140 ALWAYS_INLINE mirror::Object* TryToAllocate(Thread* self, 1141 AllocatorType allocator_type, 1142 size_t alloc_size, 1143 size_t* bytes_allocated, 1144 size_t* usable_size, 1145 size_t* bytes_tl_bulk_allocated) 1146 REQUIRES_SHARED(Locks::mutator_lock_); 1147 1148 EXPORT mirror::Object* AllocWithNewTLAB(Thread* self, 1149 AllocatorType allocator_type, 1150 size_t alloc_size, 1151 bool grow, 1152 size_t* bytes_allocated, 1153 size_t* usable_size, 1154 size_t* bytes_tl_bulk_allocated) 1155 REQUIRES_SHARED(Locks::mutator_lock_); 1156 1157 void ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) 1158 REQUIRES_SHARED(Locks::mutator_lock_); 1159 1160 // Are we out of memory, and thus should force a GC or fail? 1161 // For concurrent collectors, out of memory is defined by growth_limit_. 1162 // For nonconcurrent collectors it is defined by target_footprint_ unless grow is 1163 // set. If grow is set, the limit is growth_limit_ and we adjust target_footprint_ 1164 // to accomodate the allocation. 1165 ALWAYS_INLINE bool IsOutOfMemoryOnAllocation(AllocatorType allocator_type, 1166 size_t alloc_size, 1167 bool grow); 1168 1169 // Blocks the caller until the garbage collector becomes idle and returns the type of GC we 1170 // waited for. If only_one is true, we only wait for the currently running GC, and may return 1171 // while a new GC is again running. 1172 collector::GcType WaitForGcToCompleteLocked(GcCause cause, Thread* self, bool only_one = false) 1173 REQUIRES(gc_complete_lock_); 1174 1175 void RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) 1176 REQUIRES(!*pending_task_lock_); 1177 1178 EXPORT void RequestConcurrentGCAndSaveObject(Thread* self, 1179 bool force_full, 1180 uint32_t observed_gc_num, 1181 ObjPtr<mirror::Object>* obj) 1182 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*pending_task_lock_); 1183 1184 static constexpr uint32_t GC_NUM_ANY = std::numeric_limits<uint32_t>::max(); 1185 1186 // Sometimes CollectGarbageInternal decides to run a different Gc than you requested. Returns 1187 // which type of Gc was actually run. 1188 // We pass in the intended GC sequence number to ensure that multiple approximately concurrent 1189 // requests result in a single GC; clearly redundant request will be pruned. A requested_gc_num 1190 // of GC_NUM_ANY indicates that we should not prune redundant requests. (In the unlikely case 1191 // that gcs_completed_ gets this big, we just accept a potential extra GC or two.) 1192 collector::GcType CollectGarbageInternal(collector::GcType gc_plan, 1193 GcCause gc_cause, 1194 bool clear_soft_references, 1195 uint32_t requested_gc_num) 1196 REQUIRES(!*gc_complete_lock_, !Locks::heap_bitmap_lock_, !Locks::thread_suspend_count_lock_, 1197 !*pending_task_lock_, !process_state_update_lock_); 1198 1199 void PreGcVerification(collector::GarbageCollector* gc) 1200 REQUIRES(!Locks::mutator_lock_, !*gc_complete_lock_); 1201 void PreGcVerificationPaused(collector::GarbageCollector* gc) 1202 REQUIRES(Locks::mutator_lock_, !*gc_complete_lock_); 1203 void PrePauseRosAllocVerification(collector::GarbageCollector* gc) 1204 REQUIRES(Locks::mutator_lock_); 1205 void PreSweepingGcVerification(collector::GarbageCollector* gc) 1206 REQUIRES(Locks::mutator_lock_, !Locks::heap_bitmap_lock_, !*gc_complete_lock_); 1207 void PostGcVerification(collector::GarbageCollector* gc) 1208 REQUIRES(!Locks::mutator_lock_, !*gc_complete_lock_); 1209 void PostGcVerificationPaused(collector::GarbageCollector* gc) 1210 REQUIRES(Locks::mutator_lock_, !*gc_complete_lock_); 1211 1212 // Find a collector based on GC type. 1213 collector::GarbageCollector* FindCollectorByGcType(collector::GcType gc_type); 1214 1215 // Create the main free list malloc space, either a RosAlloc space or DlMalloc space. 1216 void CreateMainMallocSpace(MemMap&& mem_map, 1217 size_t initial_size, 1218 size_t growth_limit, 1219 size_t capacity); 1220 1221 // Create a malloc space based on a mem map. Does not set the space as default. 1222 space::MallocSpace* CreateMallocSpaceFromMemMap(MemMap&& mem_map, 1223 size_t initial_size, 1224 size_t growth_limit, 1225 size_t capacity, 1226 const char* name, 1227 bool can_move_objects); 1228 1229 // Given the current contents of the alloc space, increase the allowed heap footprint to match 1230 // the target utilization ratio. This should only be called immediately after a full garbage 1231 // collection. bytes_allocated_before_gc is used to measure bytes / second for the period which 1232 // the GC was run. 1233 // This is only called by the thread that set collector_type_running_ to a value other than 1234 // kCollectorTypeNone, or while holding gc_complete_lock, and ensuring that 1235 // collector_type_running_ is kCollectorTypeNone. 1236 void GrowForUtilization(collector::GarbageCollector* collector_ran, 1237 size_t bytes_allocated_before_gc = 0) 1238 REQUIRES(!process_state_update_lock_); 1239 1240 size_t GetPercentFree(); 1241 1242 // Swap the allocation stack with the live stack. 1243 void SwapStacks() REQUIRES_SHARED(Locks::mutator_lock_); 1244 1245 // Clear cards and update the mod union table. When process_alloc_space_cards is true, 1246 // if clear_alloc_space_cards is true, then we clear cards instead of ageing them. We do 1247 // not process the alloc space if process_alloc_space_cards is false. 1248 void ProcessCards(TimingLogger* timings, 1249 bool use_rem_sets, 1250 bool process_alloc_space_cards, 1251 bool clear_alloc_space_cards) 1252 REQUIRES_SHARED(Locks::mutator_lock_); 1253 1254 // Push an object onto the allocation stack. 1255 void PushOnAllocationStack(Thread* self, ObjPtr<mirror::Object>* obj) 1256 REQUIRES_SHARED(Locks::mutator_lock_) 1257 REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_); 1258 EXPORT void PushOnAllocationStackWithInternalGC(Thread* self, ObjPtr<mirror::Object>* obj) 1259 REQUIRES_SHARED(Locks::mutator_lock_) 1260 REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_); 1261 EXPORT void PushOnThreadLocalAllocationStackWithInternalGC(Thread* thread, 1262 ObjPtr<mirror::Object>* obj) 1263 REQUIRES_SHARED(Locks::mutator_lock_) 1264 REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_); 1265 1266 void ClearPendingTrim(Thread* self) REQUIRES(!*pending_task_lock_); 1267 void ClearPendingCollectorTransition(Thread* self) REQUIRES(!*pending_task_lock_); 1268 1269 // What kind of concurrency behavior is the runtime after? IsGcConcurrent()1270 bool IsGcConcurrent() const ALWAYS_INLINE { 1271 return collector_type_ == kCollectorTypeCC || 1272 collector_type_ == kCollectorTypeCMC || 1273 collector_type_ == kCollectorTypeCMS || 1274 collector_type_ == kCollectorTypeCCBackground || 1275 collector_type_ == kCollectorTypeCMCBackground; 1276 } 1277 1278 // Trim the managed and native spaces by releasing unused memory back to the OS. 1279 void TrimSpaces(Thread* self) REQUIRES(!*gc_complete_lock_); 1280 1281 // Trim 0 pages at the end of reference tables. 1282 void TrimIndirectReferenceTables(Thread* self); 1283 1284 template <typename Visitor> 1285 ALWAYS_INLINE void VisitObjectsInternal(Visitor&& visitor) 1286 REQUIRES_SHARED(Locks::mutator_lock_) 1287 REQUIRES(!Locks::heap_bitmap_lock_, !*gc_complete_lock_); 1288 template <typename Visitor> 1289 ALWAYS_INLINE void VisitObjectsInternalRegionSpace(Visitor&& visitor) 1290 REQUIRES(Locks::mutator_lock_, !Locks::heap_bitmap_lock_, !*gc_complete_lock_); 1291 1292 void UpdateGcCountRateHistograms() REQUIRES(gc_complete_lock_); 1293 1294 // GC stress mode attempts to do one GC per unique backtrace. 1295 EXPORT void CheckGcStressMode(Thread* self, ObjPtr<mirror::Object>* obj) 1296 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*gc_complete_lock_, 1297 !*pending_task_lock_, 1298 !*backtrace_lock_, 1299 !process_state_update_lock_); 1300 NonStickyGcType()1301 collector::GcType NonStickyGcType() const { 1302 return HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull; 1303 } 1304 1305 // Return the amount of space we allow for native memory when deciding whether to 1306 // collect. We collect when a weighted sum of Java memory plus native memory exceeds 1307 // the similarly weighted sum of the Java heap size target and this value. NativeAllocationGcWatermark()1308 ALWAYS_INLINE size_t NativeAllocationGcWatermark() const { 1309 // We keep the traditional limit of max_free_ in place for small heaps, 1310 // but allow it to be adjusted upward for large heaps to limit GC overhead. 1311 return target_footprint_.load(std::memory_order_relaxed) / 8 + max_free_; 1312 } 1313 1314 ALWAYS_INLINE void IncrementNumberOfBytesFreedRevoke(size_t freed_bytes_revoke); 1315 1316 // On switching app from background to foreground, grow the heap size 1317 // to incorporate foreground heap growth multiplier. 1318 void GrowHeapOnJankPerceptibleSwitch() REQUIRES(!process_state_update_lock_); 1319 1320 // Update *_freed_ever_ counters to reflect current GC values. 1321 void IncrementFreedEver(); 1322 1323 // Remove a vlog code from heap-inl.h which is transitively included in half the world. 1324 EXPORT static void VlogHeapGrowth(size_t max_allowed_footprint, 1325 size_t new_footprint, 1326 size_t alloc_size); 1327 1328 // Return our best approximation of the number of bytes of native memory that 1329 // are currently in use, and could possibly be reclaimed as an indirect result 1330 // of a garbage collection. 1331 size_t GetNativeBytes(); 1332 1333 // Set concurrent_start_bytes_ to a reasonable guess, given target_footprint_ . 1334 void SetDefaultConcurrentStartBytes() REQUIRES(!*gc_complete_lock_); 1335 // This version assumes no concurrent updaters. 1336 void SetDefaultConcurrentStartBytesLocked(); 1337 1338 // All-known continuous spaces, where objects lie within fixed bounds. 1339 std::vector<space::ContinuousSpace*> continuous_spaces_ GUARDED_BY(Locks::mutator_lock_); 1340 1341 // All-known discontinuous spaces, where objects may be placed throughout virtual memory. 1342 std::vector<space::DiscontinuousSpace*> discontinuous_spaces_ GUARDED_BY(Locks::mutator_lock_); 1343 1344 // All-known alloc spaces, where objects may be or have been allocated. 1345 std::vector<space::AllocSpace*> alloc_spaces_; 1346 1347 // A space where non-movable objects are allocated, when compaction is enabled it contains 1348 // Classes, ArtMethods, ArtFields, and non moving objects. 1349 space::MallocSpace* non_moving_space_; 1350 1351 // Space which we use for the kAllocatorTypeROSAlloc. 1352 space::RosAllocSpace* rosalloc_space_; 1353 1354 // Space which we use for the kAllocatorTypeDlMalloc. 1355 space::DlMallocSpace* dlmalloc_space_; 1356 1357 // The main space is the space which the GC copies to and from on process state updates. This 1358 // space is typically either the dlmalloc_space_ or the rosalloc_space_. 1359 space::MallocSpace* main_space_; 1360 1361 // The large object space we are currently allocating into. 1362 space::LargeObjectSpace* large_object_space_; 1363 1364 // The card table, dirtied by the write barrier. 1365 std::unique_ptr<accounting::CardTable> card_table_; 1366 1367 std::unique_ptr<accounting::ReadBarrierTable> rb_table_; 1368 1369 // A mod-union table remembers all of the references from the it's space to other spaces. 1370 AllocationTrackingSafeMap<space::Space*, accounting::ModUnionTable*, kAllocatorTagHeap> 1371 mod_union_tables_; 1372 1373 // A remembered set remembers all of the references from the it's space to the target space. 1374 AllocationTrackingSafeMap<space::Space*, accounting::RememberedSet*, kAllocatorTagHeap> 1375 remembered_sets_; 1376 1377 // The current collector type. 1378 CollectorType collector_type_; 1379 // Which collector we use when the app is in the foreground. 1380 const CollectorType foreground_collector_type_; 1381 // Which collector we will use when the app is notified of a transition to background. 1382 CollectorType background_collector_type_; 1383 // Desired collector type, heap trimming daemon transitions the heap if it is != collector_type_. 1384 CollectorType desired_collector_type_; 1385 1386 // Lock which guards pending tasks. 1387 Mutex* pending_task_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; 1388 1389 // How many GC threads we may use for paused parts of garbage collection. 1390 const size_t parallel_gc_threads_; 1391 1392 // How many GC threads we may use for unpaused parts of garbage collection. 1393 const size_t conc_gc_threads_; 1394 1395 // Boolean for if we are in low memory mode. 1396 const bool low_memory_mode_; 1397 1398 // If we get a pause longer than long pause log threshold, then we print out the GC after it 1399 // finishes. 1400 const size_t long_pause_log_threshold_; 1401 1402 // If we get a GC longer than long GC log threshold, then we print out the GC after it finishes. 1403 const size_t long_gc_log_threshold_; 1404 1405 // Starting time of the new process; meant to be used for measuring total process CPU time. 1406 uint64_t process_cpu_start_time_ns_; 1407 1408 // Last time (before and after) GC started; meant to be used to measure the 1409 // duration between two GCs. 1410 uint64_t pre_gc_last_process_cpu_time_ns_; 1411 uint64_t post_gc_last_process_cpu_time_ns_; 1412 1413 // allocated_bytes * (current_process_cpu_time - [pre|post]_gc_last_process_cpu_time) 1414 double pre_gc_weighted_allocated_bytes_; 1415 double post_gc_weighted_allocated_bytes_; 1416 1417 // If we ignore the target footprint it lets the heap grow until it hits the heap capacity, this 1418 // is useful for benchmarking since it reduces time spent in GC to a low %. 1419 const bool ignore_target_footprint_; 1420 1421 // If we are running tests or some other configurations we might not actually 1422 // want logs for explicit gcs since they can get spammy. 1423 const bool always_log_explicit_gcs_; 1424 1425 // Lock which guards zygote space creation. 1426 Mutex zygote_creation_lock_; 1427 1428 // Non-null iff we have a zygote space. Doesn't contain the large objects allocated before 1429 // zygote space creation. 1430 space::ZygoteSpace* zygote_space_; 1431 1432 // Minimum allocation size of large object. 1433 size_t large_object_threshold_; 1434 1435 // Guards access to the state of GC, associated conditional variable is used to signal when a GC 1436 // completes. 1437 Mutex* gc_complete_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; 1438 std::unique_ptr<ConditionVariable> gc_complete_cond_ GUARDED_BY(gc_complete_lock_); 1439 1440 // Used to synchronize between JNI critical calls and the thread flip of the CC collector. 1441 Mutex* thread_flip_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; 1442 std::unique_ptr<ConditionVariable> thread_flip_cond_ GUARDED_BY(thread_flip_lock_); 1443 // This counter keeps track of how many threads are currently in a JNI critical section. This is 1444 // incremented once per thread even with nested enters. 1445 size_t disable_thread_flip_count_ GUARDED_BY(thread_flip_lock_); 1446 bool thread_flip_running_ GUARDED_BY(thread_flip_lock_); 1447 1448 // Reference processor; 1449 std::unique_ptr<ReferenceProcessor> reference_processor_; 1450 1451 // Task processor, proxies heap trim requests to the daemon threads. 1452 std::unique_ptr<TaskProcessor> task_processor_; 1453 1454 // The following are declared volatile only for debugging purposes; it shouldn't otherwise 1455 // matter. 1456 1457 // Collector type of the running GC. 1458 CollectorType collector_type_running_ GUARDED_BY(gc_complete_lock_); 1459 1460 // Cause of the last running or attempted GC or GC-like action. 1461 GcCause last_gc_cause_ GUARDED_BY(gc_complete_lock_); 1462 1463 // The thread currently running the GC. 1464 Thread* thread_running_gc_ GUARDED_BY(gc_complete_lock_); 1465 1466 // Last Gc type we ran. Used by WaitForConcurrentGc to know which Gc was waited on. 1467 collector::GcType last_gc_type_ GUARDED_BY(gc_complete_lock_); 1468 collector::GcType next_gc_type_; 1469 1470 // Maximum size that the heap can reach. 1471 size_t capacity_; 1472 1473 // The size the heap is limited to. This is initially smaller than capacity, but for largeHeap 1474 // programs it is "cleared" making it the same as capacity. 1475 // Only weakly enforced for simultaneous allocations. 1476 size_t growth_limit_; 1477 1478 // Requested initial heap size. Temporarily ignored after a fork, but then reestablished after 1479 // a while to usually trigger the initial GC. 1480 size_t initial_heap_size_; 1481 1482 // Target size (as in maximum allocatable bytes) for the heap. Weakly enforced as a limit for 1483 // non-concurrent GC. Used as a guideline for computing concurrent_start_bytes_ in the 1484 // concurrent GC case. Updates normally occur while collector_type_running_ is not none. 1485 Atomic<size_t> target_footprint_; 1486 1487 Mutex process_state_update_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; 1488 1489 // Computed with foreground-multiplier in GrowForUtilization() when run in 1490 // jank non-perceptible state. On update to process state from background to 1491 // foreground we set target_footprint_ and concurrent_start_bytes_ to the corresponding value. 1492 size_t min_foreground_target_footprint_ GUARDED_BY(process_state_update_lock_); 1493 size_t min_foreground_concurrent_start_bytes_ GUARDED_BY(process_state_update_lock_); 1494 1495 // When num_bytes_allocated_ exceeds this amount then a concurrent GC should be requested so that 1496 // it completes ahead of an allocation failing. 1497 // A multiple of this is also used to determine when to trigger a GC in response to native 1498 // allocation. 1499 // After initialization, this is only updated by the thread that set collector_type_running_ to 1500 // a value other than kCollectorTypeNone, or while holding gc_complete_lock, and ensuring that 1501 // collector_type_running_ is kCollectorTypeNone. 1502 size_t concurrent_start_bytes_; 1503 1504 // Since the heap was created, how many bytes have been freed. 1505 std::atomic<int64_t> total_bytes_freed_ever_; 1506 1507 // Since the heap was created, how many objects have been freed. 1508 std::atomic<uint64_t> total_objects_freed_ever_; 1509 1510 // Number of bytes currently allocated and not yet reclaimed. Includes active 1511 // TLABS in their entirety, even if they have not yet been parceled out. 1512 Atomic<size_t> num_bytes_allocated_; 1513 1514 // Number of registered native bytes allocated. Adjusted after each RegisterNativeAllocation and 1515 // RegisterNativeFree. Used to help determine when to trigger GC for native allocations. Should 1516 // not include bytes allocated through the system malloc, since those are implicitly included. 1517 Atomic<size_t> native_bytes_registered_; 1518 1519 // Approximately the smallest value of GetNativeBytes() we've seen since the last GC. 1520 Atomic<size_t> old_native_bytes_allocated_; 1521 1522 // Total number of native objects of which we were notified since the beginning of time, mod 2^32. 1523 // Allows us to check for GC only roughly every kNotifyNativeInterval allocations. 1524 Atomic<uint32_t> native_objects_notified_; 1525 1526 // Number of bytes freed by thread local buffer revokes. This will 1527 // cancel out the ahead-of-time bulk counting of bytes allocated in 1528 // rosalloc thread-local buffers. It is temporarily accumulated 1529 // here to be subtracted from num_bytes_allocated_ later at the next 1530 // GC. 1531 Atomic<size_t> num_bytes_freed_revoke_; 1532 1533 // Records the number of bytes allocated at the time of GC, which is used later to calculate 1534 // how many bytes have been allocated since the last GC 1535 size_t num_bytes_alive_after_gc_; 1536 1537 // Info related to the current or previous GC iteration. 1538 collector::Iteration current_gc_iteration_; 1539 1540 // Heap verification flags. 1541 const bool verify_missing_card_marks_; 1542 const bool verify_system_weaks_; 1543 const bool verify_pre_gc_heap_; 1544 const bool verify_pre_sweeping_heap_; 1545 const bool verify_post_gc_heap_; 1546 const bool verify_mod_union_table_; 1547 bool verify_pre_gc_rosalloc_; 1548 bool verify_pre_sweeping_rosalloc_; 1549 bool verify_post_gc_rosalloc_; 1550 const bool gc_stress_mode_; 1551 1552 // RAII that temporarily disables the rosalloc verification during 1553 // the zygote fork. 1554 class ScopedDisableRosAllocVerification { 1555 private: 1556 Heap* const heap_; 1557 const bool orig_verify_pre_gc_; 1558 const bool orig_verify_pre_sweeping_; 1559 const bool orig_verify_post_gc_; 1560 1561 public: ScopedDisableRosAllocVerification(Heap * heap)1562 explicit ScopedDisableRosAllocVerification(Heap* heap) 1563 : heap_(heap), 1564 orig_verify_pre_gc_(heap_->verify_pre_gc_rosalloc_), 1565 orig_verify_pre_sweeping_(heap_->verify_pre_sweeping_rosalloc_), 1566 orig_verify_post_gc_(heap_->verify_post_gc_rosalloc_) { 1567 heap_->verify_pre_gc_rosalloc_ = false; 1568 heap_->verify_pre_sweeping_rosalloc_ = false; 1569 heap_->verify_post_gc_rosalloc_ = false; 1570 } ~ScopedDisableRosAllocVerification()1571 ~ScopedDisableRosAllocVerification() { 1572 heap_->verify_pre_gc_rosalloc_ = orig_verify_pre_gc_; 1573 heap_->verify_pre_sweeping_rosalloc_ = orig_verify_pre_sweeping_; 1574 heap_->verify_post_gc_rosalloc_ = orig_verify_post_gc_; 1575 } 1576 }; 1577 1578 // Parallel GC data structures. 1579 std::unique_ptr<ThreadPool> thread_pool_; 1580 1581 // A bitmap that is set corresponding to the known live objects since the last GC cycle. 1582 std::unique_ptr<accounting::HeapBitmap> live_bitmap_ GUARDED_BY(Locks::heap_bitmap_lock_); 1583 // A bitmap that is set corresponding to the marked objects in the current GC cycle. 1584 std::unique_ptr<accounting::HeapBitmap> mark_bitmap_ GUARDED_BY(Locks::heap_bitmap_lock_); 1585 1586 // Mark stack that we reuse to avoid re-allocating the mark stack. 1587 std::unique_ptr<accounting::ObjectStack> mark_stack_; 1588 1589 // Allocation stack, new allocations go here so that we can do sticky mark bits. This enables us 1590 // to use the live bitmap as the old mark bitmap. 1591 const size_t max_allocation_stack_size_; 1592 std::unique_ptr<accounting::ObjectStack> allocation_stack_; 1593 1594 // Second allocation stack so that we can process allocation with the heap unlocked. 1595 std::unique_ptr<accounting::ObjectStack> live_stack_; 1596 1597 // Allocator type. 1598 AllocatorType current_allocator_; 1599 const AllocatorType current_non_moving_allocator_; 1600 1601 // Which GCs we run in order when an allocation fails. 1602 std::vector<collector::GcType> gc_plan_; 1603 1604 // Bump pointer spaces. 1605 space::BumpPointerSpace* bump_pointer_space_; 1606 // Temp space is the space which the semispace collector copies to. 1607 space::BumpPointerSpace* temp_space_; 1608 1609 // Region space, used by the concurrent collector. 1610 space::RegionSpace* region_space_; 1611 1612 // Minimum free guarantees that you always have at least min_free_ free bytes after growing for 1613 // utilization, regardless of target utilization ratio. 1614 const size_t min_free_; 1615 1616 // The ideal maximum free size, when we grow the heap for utilization. 1617 const size_t max_free_; 1618 1619 // Target ideal heap utilization ratio. 1620 double target_utilization_; 1621 1622 // How much more we grow the heap when we are a foreground app instead of background. 1623 double foreground_heap_growth_multiplier_; 1624 1625 // The amount of native memory allocation since the last GC required to cause us to wait for a 1626 // collection as a result of native allocation. Very large values can cause the device to run 1627 // out of memory, due to lack of finalization to reclaim native memory. Making it too small can 1628 // cause jank in apps like launcher that intentionally allocate large amounts of memory in rapid 1629 // succession. (b/122099093) 1/4 to 1/3 of physical memory seems to be a good number. 1630 const size_t stop_for_native_allocs_; 1631 1632 // Total time which mutators are paused or waiting for GC to complete. 1633 uint64_t total_wait_time_; 1634 1635 // The current state of heap verification, may be enabled or disabled. 1636 VerifyObjectMode verify_object_mode_; 1637 1638 // Compacting GC disable count, prevents compacting GC from running iff > 0. 1639 size_t disable_moving_gc_count_ GUARDED_BY(gc_complete_lock_); 1640 1641 std::vector<collector::GarbageCollector*> garbage_collectors_; 1642 collector::SemiSpace* semi_space_collector_; 1643 collector::MarkCompact* mark_compact_; 1644 Atomic<collector::ConcurrentCopying*> active_concurrent_copying_collector_; 1645 collector::ConcurrentCopying* young_concurrent_copying_collector_; 1646 collector::ConcurrentCopying* concurrent_copying_collector_; 1647 1648 const bool is_running_on_memory_tool_; 1649 const bool use_tlab_; 1650 1651 // Pointer to the space which becomes the new main space when we do homogeneous space compaction. 1652 // Use unique_ptr since the space is only added during the homogeneous compaction phase. 1653 std::unique_ptr<space::MallocSpace> main_space_backup_; 1654 1655 // Minimal interval allowed between two homogeneous space compactions caused by OOM. 1656 uint64_t min_interval_homogeneous_space_compaction_by_oom_; 1657 1658 // Times of the last homogeneous space compaction caused by OOM. 1659 uint64_t last_time_homogeneous_space_compaction_by_oom_; 1660 1661 // Saved OOMs by homogeneous space compaction. 1662 Atomic<size_t> count_delayed_oom_; 1663 1664 // Count for requested homogeneous space compaction. 1665 Atomic<size_t> count_requested_homogeneous_space_compaction_; 1666 1667 // Count for ignored homogeneous space compaction. 1668 Atomic<size_t> count_ignored_homogeneous_space_compaction_; 1669 1670 // Count for performed homogeneous space compaction. 1671 Atomic<size_t> count_performed_homogeneous_space_compaction_; 1672 1673 // The number of garbage collections (either young or full, not trims or the like) we have 1674 // completed since heap creation. We include requests that turned out to be impossible 1675 // because they were disabled. We guard against wrapping, though that's unlikely. 1676 // Increment is guarded by gc_complete_lock_. 1677 Atomic<uint32_t> gcs_completed_; 1678 1679 // The number of the last garbage collection that has been requested. A value of gcs_completed 1680 // + 1 indicates that another collection is needed or in progress. A value of gcs_completed_ or 1681 // (logically) less means that no new GC has been requested. 1682 Atomic<uint32_t> max_gc_requested_; 1683 1684 // Active tasks which we can modify (change target time, desired collector type, etc..). 1685 CollectorTransitionTask* pending_collector_transition_ GUARDED_BY(pending_task_lock_); 1686 HeapTrimTask* pending_heap_trim_ GUARDED_BY(pending_task_lock_); 1687 1688 // Whether or not we use homogeneous space compaction to avoid OOM errors. 1689 bool use_homogeneous_space_compaction_for_oom_; 1690 1691 // If true, enable generational collection when using the Concurrent Copying 1692 // (CC) collector, i.e. use sticky-bit CC for minor collections and (full) CC 1693 // for major collections. Set in Heap constructor. 1694 const bool use_generational_cc_; 1695 1696 // True if the currently running collection has made some thread wait. 1697 bool running_collection_is_blocking_ GUARDED_BY(gc_complete_lock_); 1698 // The number of blocking GC runs. 1699 uint64_t blocking_gc_count_; 1700 // The total duration of blocking GC runs. 1701 uint64_t blocking_gc_time_; 1702 // The duration of the window for the GC count rate histograms. 1703 static constexpr uint64_t kGcCountRateHistogramWindowDuration = MsToNs(10 * 1000); // 10s. 1704 // Maximum number of missed histogram windows for which statistics will be collected. 1705 static constexpr uint64_t kGcCountRateHistogramMaxNumMissedWindows = 100; 1706 // The last time when the GC count rate histograms were updated. 1707 // This is rounded by kGcCountRateHistogramWindowDuration (a multiple of 10s). 1708 uint64_t last_update_time_gc_count_rate_histograms_; 1709 // The running count of GC runs in the last window. 1710 uint64_t gc_count_last_window_; 1711 // The running count of blocking GC runs in the last window. 1712 uint64_t blocking_gc_count_last_window_; 1713 // The maximum number of buckets in the GC count rate histograms. 1714 static constexpr size_t kGcCountRateMaxBucketCount = 200; 1715 // The histogram of the number of GC invocations per window duration. 1716 Histogram<uint64_t> gc_count_rate_histogram_ GUARDED_BY(gc_complete_lock_); 1717 // The histogram of the number of blocking GC invocations per window duration. 1718 Histogram<uint64_t> blocking_gc_count_rate_histogram_ GUARDED_BY(gc_complete_lock_); 1719 1720 // Allocation tracking support 1721 Atomic<bool> alloc_tracking_enabled_; 1722 std::unique_ptr<AllocRecordObjectMap> allocation_records_; 1723 size_t alloc_record_depth_; 1724 1725 // Perfetto Java Heap Profiler support. 1726 HeapSampler heap_sampler_; 1727 1728 // GC stress related data structures. 1729 Mutex* backtrace_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; 1730 // Debugging variables, seen backtraces vs unique backtraces. 1731 Atomic<uint64_t> seen_backtrace_count_; 1732 Atomic<uint64_t> unique_backtrace_count_; 1733 // Stack trace hashes that we already saw, 1734 std::unordered_set<uint64_t> seen_backtraces_ GUARDED_BY(backtrace_lock_); 1735 1736 // We disable GC when we are shutting down the runtime in case there are daemon threads still 1737 // allocating. 1738 bool gc_disabled_for_shutdown_ GUARDED_BY(gc_complete_lock_); 1739 1740 // Turned on by -XX:DumpRegionInfoBeforeGC and -XX:DumpRegionInfoAfterGC to 1741 // emit region info before and after each GC cycle. 1742 bool dump_region_info_before_gc_; 1743 bool dump_region_info_after_gc_; 1744 1745 // Boot image spaces. 1746 std::vector<space::ImageSpace*> boot_image_spaces_; 1747 1748 // Boot image address range. Includes images and oat files. 1749 uint32_t boot_images_start_address_; 1750 uint32_t boot_images_size_; 1751 1752 // The number of times we initiated a GC of last resort to try to avoid an OOME. 1753 Atomic<uint64_t> pre_oome_gc_count_; 1754 1755 // An installed allocation listener. 1756 Atomic<AllocationListener*> alloc_listener_; 1757 // An installed GC Pause listener. 1758 Atomic<GcPauseListener*> gc_pause_listener_; 1759 1760 std::unique_ptr<Verification> verification_; 1761 1762 friend class CollectorTransitionTask; 1763 friend class collector::GarbageCollector; 1764 friend class collector::ConcurrentCopying; 1765 friend class collector::MarkCompact; 1766 friend class collector::MarkSweep; 1767 friend class collector::SemiSpace; 1768 friend class GCCriticalSection; 1769 friend class ReferenceQueue; 1770 friend class ScopedGCCriticalSection; 1771 friend class ScopedInterruptibleGCCriticalSection; 1772 friend class VerifyReferenceCardVisitor; 1773 friend class VerifyReferenceVisitor; 1774 friend class VerifyObjectVisitor; 1775 1776 DISALLOW_IMPLICIT_CONSTRUCTORS(Heap); 1777 }; 1778 1779 } // namespace gc 1780 } // namespace art 1781 1782 #endif // ART_RUNTIME_GC_HEAP_H_ 1783