TLA Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : // Copyright (c) 2026 Michael Vandeberg
4 : //
5 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
6 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 : //
8 : // Official repository: https://github.com/cppalliance/capy
9 : //
10 :
11 : #ifndef BOOST_CAPY_RECYCLING_MEMORY_RESOURCE_HPP
12 : #define BOOST_CAPY_RECYCLING_MEMORY_RESOURCE_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 :
16 : #include <bit>
17 : #include <cstddef>
18 : #include <memory_resource>
19 : #include <mutex>
20 : #include <new>
21 :
22 : namespace boost {
23 : namespace capy {
24 :
25 : /** Recycles freed blocks through per-thread pools, with a shared pool for cross-thread reuse.
26 :
27 : This memory resource recycles memory blocks using power-of-two
28 : size classes for O(1) allocation lookup. It maintains a thread-local
29 : pool for fast lock-free access and a global pool for cross-thread
30 : block sharing.
31 :
32 : Size classes: 64, 128, 256, 512, 1024, 2048 bytes.
33 : Allocations larger than 2048 bytes bypass the pools entirely.
34 :
35 : Each pool caches at most 256 KiB of blocks per size class:
36 : 4096 blocks of the smallest class, 128 of the largest. A freed
37 : block that fits in neither the thread's pool nor the global pool
38 : goes back to `::operator delete`.
39 :
40 : Blocks a thread caches but stops using drain back to the global
41 : pool. The drain runs as the thread goes on freeing blocks or
42 : refilling from the global pool. Other threads can then reuse what a
43 : burst leaves behind. Blocks the global pool has no room for go back
44 : to `::operator delete`.
45 :
46 : This is the default frame allocator of an @ref execution_context.
47 : @ref run_async uses the execution context's frame allocator when no
48 : allocator is given. Some execution contexts, such as
49 : @ref thread_pool, replace that default.
50 :
51 : @par Thread Safety
52 : Thread-safe. The thread-local pool requires no synchronization.
53 : The global pool uses a mutex for cross-thread access.
54 :
55 : @par Example
56 : @par !example example
57 :
58 :
59 : @see @ref get_recycling_memory_resource
60 : @see @ref run_async
61 : */
62 : BOOST_CAPY_MSVC_WARNING_PUSH
63 : BOOST_CAPY_MSVC_WARNING_DISABLE(4275) // non dll-interface base class
64 : class BOOST_CAPY_DECL recycling_memory_resource : public std::pmr::memory_resource
65 : {
66 : static constexpr std::size_t num_classes = 6;
67 : static constexpr std::size_t min_class_size = 64; // 2^6
68 : static constexpr std::size_t max_class_size = 2048; // 2^11
69 : static constexpr int min_class_shift = std::countr_zero(min_class_size);
70 : static constexpr std::size_t max_cached_bytes = 256 * 1024;
71 :
72 : // Frees on one thread, plus blocks it refills from the global pool,
73 : // between decay passes. Allocations served from the thread's pool
74 : // aren't counted, which keeps the counter off that path.
75 : static constexpr std::size_t decay_period = 4096;
76 :
77 : static std::size_t
78 HIT 2288238 : round_up_pow2(std::size_t n) noexcept
79 : {
80 2288238 : return n <= min_class_size ? min_class_size : std::bit_ceil(n);
81 : }
82 :
83 : static std::size_t
84 2288238 : get_class_index(std::size_t rounded) noexcept
85 : {
86 : auto const idx = static_cast<std::size_t>(
87 2288238 : std::countr_zero(rounded) - min_class_shift);
88 2288238 : return idx < num_classes ? idx : num_classes;
89 : }
90 :
91 : static constexpr std::size_t
92 1410621 : bucket_capacity(std::size_t idx) noexcept
93 : {
94 1410621 : return max_cached_bytes >> (idx + min_class_shift);
95 : }
96 :
97 : // Cached blocks are linked through their own storage, so a bucket
98 : // holds any number of them without a side array.
99 : struct node
100 : {
101 : node* next;
102 : };
103 :
104 : struct bucket
105 : {
106 : node* head = nullptr;
107 : std::size_t count = 0;
108 :
109 : // Fewest blocks cached since the last decay pass: that many sat
110 : // unused through the whole period.
111 : std::size_t low = 0;
112 :
113 1199578 : void* pop() noexcept
114 : {
115 1199578 : node* n = head;
116 1199578 : if(n == nullptr)
117 302445 : return nullptr;
118 897133 : head = n->next;
119 897133 : --count;
120 897133 : if(count < low)
121 53349 : low = count;
122 897133 : return n;
123 : }
124 :
125 : // Peter Dimov's idea
126 : // `b` must be empty: its chain is overwritten.
127 302443 : void* pop(bucket& b) noexcept
128 : {
129 302443 : if(head == nullptr)
130 302414 : return nullptr;
131 29 : b.head = head;
132 29 : b.count = count;
133 29 : head = nullptr;
134 29 : count = 0;
135 29 : low = 0;
136 29 : return b.pop();
137 : }
138 :
139 1410499 : bool push(void* p, std::size_t capacity) noexcept
140 : {
141 1410499 : if(count >= capacity)
142 473705 : return false;
143 936794 : head = ::new(p) node{head};
144 936794 : ++count;
145 936794 : return true;
146 : }
147 : };
148 :
149 : struct pool
150 : {
151 : bucket buckets[num_classes];
152 : std::size_t arrivals = 0;
153 :
154 : // No destructor: a non-trivial dtor forces a guard variable on the
155 : // thread_local in local(), checked on every alloc/free. Constant
156 : // initialization plus a trivial dtor makes that access a bare TLS
157 : // load. Cached blocks are instead reclaimed explicitly: per-thread
158 : // by arm_thread_cleanup() at thread exit, and the global pool by
159 : // global()'s holder destructor at process exit.
160 : };
161 :
162 : #if (defined(BOOST_CAPY_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)) && \
163 : !defined(BOOST_CAPY_STATIC_LINK)
164 : // A shared build defines this thread's pool, and the flag below, in
165 : // the library: inline, each module would cache in a pool of its own,
166 : // which the library's thread-exit cleanup never drains.
167 : static pool& local() noexcept;
168 : #else
169 : static pool& local() noexcept
170 : {
171 : static thread_local pool p;
172 : return p;
173 : }
174 : #endif
175 :
176 : static pool& global() noexcept;
177 : static std::mutex& global_mutex() noexcept;
178 :
179 : void* allocate_slow(std::size_t rounded, std::size_t idx);
180 : void deallocate_slow(void* p, std::size_t idx);
181 :
182 : // Move half of each bucket's idle blocks to the global pool, or
183 : // release them when it has no room. Halving, rather than emptying,
184 : // leaves a burst that skips one period half its blocks.
185 : static void decay(pool& lp) noexcept;
186 :
187 : // Register a thread-exit callback that drains this thread's local
188 : // pool back to the OS. Called only off the hot path: unconditionally
189 : // from the slow paths, and from deallocate_fast while the flag below
190 : // is clear. Returns false once that callback has run: nothing drains
191 : // the local pool after it, so frees must bypass it.
192 : static bool arm_thread_cleanup() noexcept;
193 :
194 : // Guard-free flag (constinit bool, trivial dtor): set once cleanup is
195 : // armed, and cleared again when the cleanup has run.
196 : #if (defined(BOOST_CAPY_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)) && \
197 : !defined(BOOST_CAPY_STATIC_LINK)
198 : static bool& thread_armed() noexcept;
199 : #else
200 : static bool& thread_armed() noexcept
201 : {
202 : static thread_local bool armed = false;
203 : return armed;
204 : }
205 : #endif
206 :
207 : public:
208 : /** Destroy the resource.
209 :
210 : No cached block is released here. Every pool is static, so an
211 : instance holds no state of its own. The thread-local pool is
212 : drained at thread exit, and the global pool at process exit.
213 : */
214 : ~recycling_memory_resource();
215 :
216 : /** Allocate without virtual dispatch.
217 :
218 : A request larger than the largest size class (2048 bytes)
219 : bypasses the pools and goes straight to `::operator new`.
220 :
221 : The second parameter is the requested alignment, and it is ignored.
222 : Every block comes from `::operator new`, so blocks carry the
223 : implementation's default new alignment and no more.
224 :
225 : @par Complexity
226 : Amortized constant. Now and then a call also hands this thread's
227 : idle cached blocks to the global pool, or releases them when it
228 : has no room.
229 :
230 : A pooled block is rounded up to its size class, so it may be
231 : larger than requested.
232 :
233 : @throws std::bad_alloc If the underlying `::operator new` fails.
234 :
235 : @param bytes The number of bytes to allocate.
236 :
237 : @return A pointer to a block of at least `bytes` bytes.
238 : */
239 : void*
240 1144119 : allocate_fast(std::size_t bytes, std::size_t)
241 : {
242 1144119 : std::size_t rounded = round_up_pow2(bytes);
243 1144119 : std::size_t idx = get_class_index(rounded);
244 1144119 : if(idx >= num_classes)
245 MIS 0 : return ::operator new(bytes);
246 HIT 1144119 : if(auto* p = local().buckets[idx].pop())
247 841675 : return p;
248 302444 : return allocate_slow(rounded, idx);
249 : }
250 :
251 : /** Deallocate without virtual dispatch.
252 :
253 : The block is cached in the pool of the thread that frees it, not
254 : the thread that allocated it.
255 :
256 : The third parameter is the alignment the block was allocated with,
257 : and it is ignored, as it is on allocation.
258 :
259 : @par Complexity
260 : Amortized constant. Now and then a call also hands this thread's
261 : idle cached blocks to the global pool, or releases them when it
262 : has no room.
263 :
264 : @param p The block to return. It must have come from
265 : @ref allocate_fast or @ref do_allocate on this resource.
266 :
267 : @param bytes The size the block was allocated with. The size class
268 : is recomputed from it, so passing a different value puts the block
269 : in the wrong bucket.
270 : */
271 : void
272 1144119 : deallocate_fast(void* p, std::size_t bytes, std::size_t)
273 : {
274 1144119 : std::size_t rounded = round_up_pow2(bytes);
275 1144119 : std::size_t idx = get_class_index(rounded);
276 1144119 : if(idx >= num_classes)
277 : {
278 MIS 0 : ::operator delete(p);
279 0 : return;
280 : }
281 : // Arms thread-exit cleanup for any thread that caches via
282 : // deallocate, including consumer threads that never hit a slow
283 : // path; after that cleanup, the block bypasses the local pool.
284 HIT 1144119 : auto& armed = thread_armed();
285 1144119 : if(!armed)
286 : {
287 375 : if(!arm_thread_cleanup())
288 : {
289 4 : deallocate_slow(p, idx);
290 4 : return;
291 : }
292 371 : armed = true;
293 : }
294 1144115 : auto& lp = local();
295 1144115 : if(++lp.arrivals == decay_period)
296 272 : decay(lp);
297 1144115 : if(lp.buckets[idx].push(p, bucket_capacity(idx)))
298 877735 : return;
299 266380 : deallocate_slow(p, idx);
300 : }
301 :
302 : protected:
303 : /** Allocate through the `std::pmr::memory_resource` interface.
304 :
305 : Forwards to @ref allocate_fast, so it has that function's contract.
306 : Call `allocate_fast` directly to skip the virtual dispatch.
307 :
308 : @throws std::bad_alloc If the underlying `::operator new` fails.
309 :
310 : @param bytes The number of bytes to allocate.
311 :
312 : @param alignment The requested alignment. It is ignored.
313 :
314 : @return A pointer to a block of at least `bytes` bytes.
315 : */
316 : void*
317 : do_allocate(std::size_t bytes, std::size_t alignment) override;
318 :
319 : /** Deallocate through the `std::pmr::memory_resource` interface.
320 :
321 : Forwards to @ref deallocate_fast, so it has that function's
322 : contract.
323 :
324 : @param p The block to return, as obtained from this resource.
325 :
326 : @param bytes The size the block was allocated with.
327 :
328 : @param alignment The alignment the block was allocated with. It is
329 : ignored.
330 : */
331 : void
332 : do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override;
333 :
334 : /** Compare this resource with another for equality.
335 :
336 : Equality is object identity: two distinct
337 : `recycling_memory_resource` objects compare unequal, even though the
338 : pools they draw from are static and therefore shared.
339 :
340 : @param other The resource to compare against.
341 :
342 : @return `true` if `other` is the same object as `*this`; otherwise
343 : `false`.
344 : */
345 : bool
346 2 : do_is_equal(const memory_resource& other) const noexcept override
347 : {
348 2 : return this == &other;
349 : }
350 : };
351 : BOOST_CAPY_MSVC_WARNING_POP
352 :
353 : /** Return a pointer to the process-wide recycling memory resource.
354 :
355 : The returned pointer is valid for the lifetime of the program.
356 : This is the default frame allocator of an @ref execution_context.
357 :
358 : @return Pointer to the recycling memory resource.
359 :
360 : @see @ref recycling_memory_resource
361 : @see @ref run_async
362 : */
363 : BOOST_CAPY_DECL
364 : std::pmr::memory_resource*
365 : get_recycling_memory_resource() noexcept;
366 :
367 : } // namespace capy
368 : } // namespace boost
369 :
370 : #endif
|