1 // Copyright 2016 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef V8_ZONE_ACCOUNTING_ALLOCATOR_H_ 6 #define V8_ZONE_ACCOUNTING_ALLOCATOR_H_ 7 8 #include <atomic> 9 #include <memory> 10 11 #include "include/v8-platform.h" 12 #include "src/base/macros.h" 13 #include "src/logging/tracing-flags.h" 14 15 namespace v8 { 16 17 namespace base { 18 class BoundedPageAllocator; 19 } // namespace base 20 21 namespace internal { 22 23 class Segment; 24 class VirtualMemory; 25 class Zone; 26 27 class V8_EXPORT_PRIVATE AccountingAllocator { 28 public: 29 AccountingAllocator(); 30 AccountingAllocator(const AccountingAllocator&) = delete; 31 AccountingAllocator& operator=(const AccountingAllocator&) = delete; 32 virtual ~AccountingAllocator(); 33 34 // Allocates a new segment. Returns nullptr on failed allocation. 35 Segment* AllocateSegment(size_t bytes, bool supports_compression); 36 37 // Return unneeded segments to either insert them into the pool or release 38 // them if the pool is already full or memory pressure is high. 39 void ReturnSegment(Segment* memory, bool supports_compression); 40 GetCurrentMemoryUsage()41 size_t GetCurrentMemoryUsage() const { 42 return current_memory_usage_.load(std::memory_order_relaxed); 43 } 44 GetMaxMemoryUsage()45 size_t GetMaxMemoryUsage() const { 46 return max_memory_usage_.load(std::memory_order_relaxed); 47 } 48 TraceZoneCreation(const Zone * zone)49 void TraceZoneCreation(const Zone* zone) { 50 if (V8_LIKELY(!TracingFlags::is_zone_stats_enabled())) return; 51 TraceZoneCreationImpl(zone); 52 } 53 TraceZoneDestruction(const Zone * zone)54 void TraceZoneDestruction(const Zone* zone) { 55 if (V8_LIKELY(!TracingFlags::is_zone_stats_enabled())) return; 56 TraceZoneDestructionImpl(zone); 57 } 58 TraceAllocateSegment(Segment * segment)59 void TraceAllocateSegment(Segment* segment) { 60 if (V8_LIKELY(!TracingFlags::is_zone_stats_enabled())) return; 61 TraceAllocateSegmentImpl(segment); 62 } 63 64 protected: TraceZoneCreationImpl(const Zone * zone)65 virtual void TraceZoneCreationImpl(const Zone* zone) {} TraceZoneDestructionImpl(const Zone * zone)66 virtual void TraceZoneDestructionImpl(const Zone* zone) {} TraceAllocateSegmentImpl(Segment * segment)67 virtual void TraceAllocateSegmentImpl(Segment* segment) {} 68 69 private: 70 std::atomic<size_t> current_memory_usage_{0}; 71 std::atomic<size_t> max_memory_usage_{0}; 72 73 std::unique_ptr<VirtualMemory> reserved_area_; 74 std::unique_ptr<base::BoundedPageAllocator> bounded_page_allocator_; 75 76 ZoneBackingAllocator::MallocFn zone_backing_malloc_ = nullptr; 77 ZoneBackingAllocator::FreeFn zone_backing_free_ = nullptr; 78 }; 79 80 } // namespace internal 81 } // namespace v8 82 83 #endif // V8_ZONE_ACCOUNTING_ALLOCATOR_H_ 84