1 // Copyright 2019 The Chromium Authors 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 PARTITION_ALLOC_MEMORY_RECLAIMER_H_ 6 #define PARTITION_ALLOC_MEMORY_RECLAIMER_H_ 7 8 #include <memory> 9 #include <set> 10 11 #include "partition_alloc/partition_alloc_base/component_export.h" 12 #include "partition_alloc/partition_alloc_base/no_destructor.h" 13 #include "partition_alloc/partition_alloc_base/thread_annotations.h" 14 #include "partition_alloc/partition_alloc_base/time/time.h" 15 #include "partition_alloc/partition_alloc_forward.h" 16 #include "partition_alloc/partition_lock.h" 17 18 namespace partition_alloc { 19 20 // Posts and handles memory reclaim tasks for PartitionAlloc. 21 // 22 // PartitionAlloc users are responsible for scheduling and calling the 23 // reclamation methods with their own timers / event loops. 24 // 25 // Singleton as this runs as long as the process is alive, and 26 // having multiple instances would be wasteful. PA_COMPONENT_EXPORT(PARTITION_ALLOC)27class PA_COMPONENT_EXPORT(PARTITION_ALLOC) MemoryReclaimer { 28 public: 29 static MemoryReclaimer* Instance(); 30 31 MemoryReclaimer(const MemoryReclaimer&) = delete; 32 MemoryReclaimer& operator=(const MemoryReclaimer&) = delete; 33 34 // Internal. Do not use. 35 // Registers a partition to be tracked by the reclaimer. 36 void RegisterPartition(PartitionRoot* partition); 37 // Internal. Do not use. 38 // Unregisters a partition to be tracked by the reclaimer. 39 void UnregisterPartition(PartitionRoot* partition); 40 41 // Triggers an explicit reclaim now to reclaim as much free memory as 42 // possible. The API callers need to invoke this method periodically 43 // if they want to use memory reclaimer. 44 // See also GetRecommendedReclaimIntervalInMicroseconds()'s comment. 45 void ReclaimNormal(); 46 47 // Returns a recommended interval to invoke ReclaimNormal. 48 int64_t GetRecommendedReclaimIntervalInMicroseconds() { 49 return internal::base::Seconds(4).InMicroseconds(); 50 } 51 52 // Triggers an explicit reclaim now reclaiming all free memory 53 void ReclaimAll(); 54 55 private: 56 MemoryReclaimer(); 57 ~MemoryReclaimer(); 58 // |flags| is an OR of base::PartitionPurgeFlags 59 void Reclaim(int flags); 60 void ResetForTesting(); 61 62 internal::Lock lock_; 63 std::set<PartitionRoot*> partitions_ PA_GUARDED_BY(lock_); 64 65 friend class internal::base::NoDestructor<MemoryReclaimer>; 66 friend class MemoryReclaimerTest; 67 }; 68 69 } // namespace partition_alloc 70 71 #endif // PARTITION_ALLOC_MEMORY_RECLAIMER_H_ 72