• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 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 BASE_MEMORY_DISCARDABLE_SHARED_MEMORY_H_
6 #define BASE_MEMORY_DISCARDABLE_SHARED_MEMORY_H_
7 
8 #include <stddef.h>
9 
10 #include "base/base_export.h"
11 #include "base/dcheck_is_on.h"
12 #include "base/memory/shared_memory_mapping.h"
13 #include "base/memory/unsafe_shared_memory_region.h"
14 #include "base/threading/thread_collision_warner.h"
15 #include "base/time/time.h"
16 #include "build/build_config.h"
17 
18 #if DCHECK_IS_ON()
19 #include <set>
20 #endif
21 
22 // Linux (including Android) support the MADV_REMOVE argument with madvise()
23 // which has the behavior of reliably causing zero-fill-on-demand pages to
24 // be returned after a call. Here we define
25 // DISCARDABLE_SHARED_MEMORY_ZERO_FILL_ON_DEMAND_PAGES_AFTER_PURGE on Linux
26 // and Android to indicate that this type of behavior can be expected on
27 // those platforms. Note that madvise() will still be used on other POSIX
28 // platforms but doesn't provide the zero-fill-on-demand pages guarantee.
29 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
30 #define DISCARDABLE_SHARED_MEMORY_ZERO_FILL_ON_DEMAND_PAGES_AFTER_PURGE
31 #endif
32 
33 namespace base {
34 
35 namespace trace_event {
36 class MemoryAllocatorDump;
37 class ProcessMemoryDump;
38 }  // namespace trace_event
39 
40 // Platform abstraction for discardable shared memory.
41 //
42 // This class is not thread-safe. Clients are responsible for synchronizing
43 // access to an instance of this class.
44 class BASE_EXPORT DiscardableSharedMemory {
45  public:
46   enum LockResult { SUCCESS, PURGED, FAILED };
47 
48   DiscardableSharedMemory();
49 
50   // Create a new DiscardableSharedMemory object from an existing, open shared
51   // memory file. Memory must be locked.
52   explicit DiscardableSharedMemory(UnsafeSharedMemoryRegion region);
53 
54   DiscardableSharedMemory(const DiscardableSharedMemory&) = delete;
55   DiscardableSharedMemory& operator=(const DiscardableSharedMemory&) = delete;
56 
57   // Closes any open files.
58   virtual ~DiscardableSharedMemory();
59 
60   // Creates and maps a locked DiscardableSharedMemory object with |size|.
61   // Returns true on success and false on failure.
62   bool CreateAndMap(size_t size);
63 
64   // Maps the locked discardable memory into the caller's address space.
65   // Returns true on success, false otherwise.
66   bool Map(size_t size);
67 
68   // Unmaps the discardable shared memory from the caller's address space.
69   // Unmapping won't unlock previously locked range.
70   // Returns true if successful; returns false on error or if the memory is
71   // not mapped.
72   bool Unmap();
73 
74   // The actual size of the mapped memory (may be larger than requested).
mapped_size()75   size_t mapped_size() const { return mapped_size_; }
76 
77   // Returns a duplicated shared memory region for this DiscardableSharedMemory
78   // object.
DuplicateRegion()79   UnsafeSharedMemoryRegion DuplicateRegion() const {
80     return shared_memory_region_.Duplicate();
81   }
82 
83   // Returns an ID for the shared memory region. This is ID of the mapped region
84   // consistent across all processes and is valid as long as the region is not
85   // unmapped.
mapped_id()86   const UnguessableToken& mapped_id() const {
87     return shared_memory_mapping_.guid();
88   }
89 
90   // Locks a range of memory so that it will not be purged by the system.
91   // The range of memory must be unlocked. The result of trying to lock an
92   // already locked range is undefined. |offset| and |length| must both be
93   // a multiple of the page size as returned by GetPageSize().
94   // Passing 0 for |length| means "everything onward".
95   // Returns SUCCESS if range was successfully locked and the memory is still
96   // resident, PURGED if range was successfully locked but has been purged
97   // since last time it was locked and FAILED if range could not be locked.
98   // Locking can fail for two reasons; object might have been purged, our
99   // last known usage timestamp might be out of date. Last known usage time
100   // is updated to the actual last usage timestamp if memory is still resident
101   // or 0 if not.
102   LockResult Lock(size_t offset, size_t length);
103 
104   // Unlock a previously successfully locked range of memory. The range of
105   // memory must be locked. The result of trying to unlock a not
106   // previously locked range is undefined.
107   // |offset| and |length| must both be a multiple of the page size as returned
108   // by GetPageSize().
109   // Passing 0 for |length| means "everything onward".
110   void Unlock(size_t offset, size_t length);
111 
112   // Gets a pointer to the opened discardable memory space. Discardable memory
113   // must have been mapped via Map().
114   void* memory() const;
115 
116   // Returns the last known usage time for DiscardableSharedMemory object. This
117   // may be earlier than the "true" usage time when memory has been used by a
118   // different process. Returns NULL time if purged.
last_known_usage()119   Time last_known_usage() const { return last_known_usage_; }
120 
121   // Releases any allocated pages in the specified range, if supported by the
122   // platform. Address space in the specified range continues to be reserved.
123   // The memory is not guaranteed to be released immediately.
124   // |offset| and |length| are both in bytes. |offset| and |length| must both be
125   // page aligned.
126   void ReleaseMemoryIfPossible(size_t offset, size_t length);
127 
128   // This returns true and sets |last_known_usage_| to 0 if
129   // DiscardableSharedMemory object was successfully purged. Purging can fail
130   // for two reasons; object might be locked or our last known usage timestamp
131   // might be out of date. Last known usage time is updated to |current_time|
132   // if locked or the actual last usage timestamp if unlocked. It is often
133   // necessary to call this function twice for the object to successfully be
134   // purged. First call, updates |last_known_usage_|. Second call, successfully
135   // purges the object using the updated |last_known_usage_|.
136   // Note: there is no guarantee that multiple calls to this function will
137   // successfully purge object. DiscardableSharedMemory object might be locked
138   // or another thread/process might be able to lock and unlock it in between
139   // each call.
140   bool Purge(Time current_time);
141 
142   // Returns true if memory is still resident.
143   bool IsMemoryResident() const;
144 
145   // Returns true if memory is locked.
146   bool IsMemoryLocked() const;
147 
148   // Closes the open discardable memory segment.
149   // It is safe to call Close repeatedly.
150   void Close();
151 
152   // For tracing: Creates ownership edge to the underlying shared memory dump
153   // which is cross process in the given |pmd|. |local_segment_dump| is the dump
154   // associated with the local discardable shared memory segment and |is_owned|
155   // is true when the current process owns the segment and the effective memory
156   // is assigned to the current process.
157   void CreateSharedMemoryOwnershipEdge(
158       trace_event::MemoryAllocatorDump* local_segment_dump,
159       trace_event::ProcessMemoryDump* pmd,
160       bool is_owned) const;
161 
162 #if BUILDFLAG(IS_ANDROID)
163   // Returns true if the Ashmem device is supported on this system.
164   // Only use this for unit-testing.
165   static bool IsAshmemDeviceSupportedForTesting();
166 #endif
167 
168  private:
169   // LockPages/UnlockPages are platform-native discardable page management
170   // helper functions. Both expect |offset| to be specified relative to the
171   // base address at which |memory| is mapped, and that |offset| and |length|
172   // are page-aligned by the caller.
173   // Returns SUCCESS on platforms which do not support discardable pages.
174   static LockResult LockPages(const UnsafeSharedMemoryRegion& region,
175                               size_t offset,
176                               size_t length);
177   // UnlockPages() is a no-op on platforms not supporting discardable pages.
178   static void UnlockPages(const UnsafeSharedMemoryRegion& region,
179                           size_t offset,
180                           size_t length);
181 
182   // Virtual for tests.
183   virtual Time Now() const;
184 
185   UnsafeSharedMemoryRegion shared_memory_region_;
186   WritableSharedMemoryMapping shared_memory_mapping_;
187   size_t mapped_size_;
188   size_t locked_page_count_;
189 #if DCHECK_IS_ON()
190   std::set<size_t> locked_pages_;
191 #endif
192   // Implementation is not thread-safe but still usable if clients are
193   // synchronized somehow. Use a collision warner to detect incorrect usage.
194   DFAKE_MUTEX(thread_collision_warner_);
195   Time last_known_usage_;
196 };
197 
198 }  // namespace base
199 
200 #endif  // BASE_MEMORY_DISCARDABLE_SHARED_MEMORY_H_
201