Debian Codegraph @

libstdc++-v3/src/c++17/memory_resource.cc

raw
1 // <memory_resource> implementation -*- C++ -*-
2
3 // Copyright (C) 2018-2025 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
10
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
19
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
24
25 #include <memory_resource>
26 #include <algorithm> // lower_bound, rotate
27 #include <atomic>
28 #include <bit> // has_single_bit, bit_ceil, bit_width
29 #include <new>
30 #include <bits/move.h> // std::__exchange
31 #if ATOMIC_POINTER_LOCK_FREE != 2
32 # include <bits/std_mutex.h> // std::mutex, std::lock_guard
33 #endif
34
35 #if __has_cpp_attribute(clang::require_constant_initialization)
36 # define __constinit [[clang::require_constant_initialization]]
37 #endif
38
39 namespace std _GLIBCXX_VISIBILITY(default)
40 {
41 _GLIBCXX_BEGIN_NAMESPACE_VERSION
42 namespace pmr
43 {
44 // This was defined inline in 9.1 and 9.2 so code compiled by those
45 // versions will not use this symbol.
46 memory_resource::~memory_resource() = default;
47
48 namespace
49 {
50 class newdel_res_t final : public memory_resource
51 {
52 void*
53 do_allocate(size_t __bytes, size_t __alignment) override
54 { return ::operator new(__bytes, std::align_val_t(__alignment)); }
55
56 void
57 do_deallocate(void* __p, size_t __bytes, size_t __alignment) noexcept
58 override
59 { ::operator delete(__p, __bytes, std::align_val_t(__alignment)); }
60
61 bool
62 do_is_equal(const memory_resource& __other) const noexcept override
63 { return &__other == this; }
64 };
65
66 class null_res_t final : public memory_resource
67 {
68 void*
69 do_allocate(size_t, size_t) override
70 { std::__throw_bad_alloc(); }
71
72 void
73 do_deallocate(void*, size_t, size_t) noexcept override
74 { }
75
76 bool
77 do_is_equal(const memory_resource& __other) const noexcept override
78 { return &__other == this; }
79 };
80
81 template<typename T>
82 struct constant_init
83 {
84 union {
85 T obj;
86 };
87 constexpr constant_init() : obj() { }
88
89 template<typename U>
90 explicit constexpr constant_init(U arg) : obj(arg) { }
91
92 ~constant_init() { /* do nothing, union member is not destroyed */ }
93 };
94
95 __constinit constant_init<newdel_res_t> newdel_res{};
96 __constinit constant_init<null_res_t> null_res{};
97
98 #ifndef _GLIBCXX_HAS_GTHREADS
99 # define _GLIBCXX_ATOMIC_MEM_RES_CAN_BE_CONSTANT_INITIALIZED
100 // Single-threaded, no need for synchronization
101 struct atomic_mem_res
102 {
103 constexpr
104 atomic_mem_res(memory_resource* r) : val(r) { }
105
106 memory_resource* val;
107
108 memory_resource* load(std::memory_order) const
109 {
110 return val;
111 }
112
113 memory_resource* exchange(memory_resource* r, std::memory_order)
114 {
115 return std::__exchange(val, r);
116 }
117 };
118 #elif ATOMIC_POINTER_LOCK_FREE == 2
119 using atomic_mem_res = atomic<memory_resource*>;
120 # define _GLIBCXX_ATOMIC_MEM_RES_CAN_BE_CONSTANT_INITIALIZED
121 #else
122 // Can't use pointer-width atomics, define a type using a mutex instead:
123 struct atomic_mem_res
124 {
125 # ifdef __GTHREAD_MUTEX_INIT
126 # define _GLIBCXX_ATOMIC_MEM_RES_CAN_BE_CONSTANT_INITIALIZED
127 // std::mutex has constexpr constructor
128 constexpr
129 # endif
130 atomic_mem_res(memory_resource* r) : val(r) { }
131
132 mutex mx;
133 memory_resource* val;
134
135 memory_resource* load(std::memory_order)
136 {
137 lock_guard<mutex> lock(mx);
138 return val;
139 }
140
141 memory_resource* exchange(memory_resource* r, std::memory_order)
142 {
143 lock_guard<mutex> lock(mx);
144 return std::__exchange(val, r);
145 }
146 };
147 #endif
148
149 #ifdef _GLIBCXX_ATOMIC_MEM_RES_CAN_BE_CONSTANT_INITIALIZED
150 __constinit constant_init<atomic_mem_res> default_res{&newdel_res.obj};
151 #else
152 # pragma GCC diagnostic ignored "-Wprio-ctor-dtor"
153 struct {
154 atomic_mem_res obj = &newdel_res.obj;
155 } default_res __attribute__ ((init_priority (100)));
156 #endif
157 } // namespace
158
159 memory_resource*
160 new_delete_resource() noexcept
161 { return &newdel_res.obj; }
162
163 memory_resource*
164 null_memory_resource() noexcept
165 { return &null_res.obj; }
166
167 memory_resource*
168 set_default_resource(memory_resource* r) noexcept
169 {
170 if (r == nullptr)
171 r = new_delete_resource();
172 return default_res.obj.exchange(r, std::memory_order_acq_rel);
173 }
174
175 memory_resource*
176 get_default_resource() noexcept
177 { return default_res.obj.load(std::memory_order_acquire); }
178
179 // Member functions for std::pmr::monotonic_buffer_resource
180
181 // This was defined inline in 9.1 and 9.2 so code compiled by those
182 // versions will not use this symbol.
183 monotonic_buffer_resource::~monotonic_buffer_resource() { release(); }
184
185 namespace
186 {
187 // aligned_size<N> stores the size and alignment of a memory allocation.
188 // The size must be a multiple of N, leaving the low log2(N) bits free
189 // to store the base-2 logarithm of the alignment.
190 // For example, allocate(1024, 32) is stored as 1024 + log2(32) = 1029.
191 template<unsigned N>
192 struct aligned_size
193 {
194 // N must be a power of two
195 static_assert( std::__popcount(N) == 1 );
196
197 static constexpr size_t _S_align_mask = N - 1;
198 static constexpr size_t _S_size_mask = ~_S_align_mask;
199
200 constexpr
201 aligned_size(size_t sz, size_t align) noexcept
202 : value(sz | (std::__bit_width(align) - 1u))
203 {
204 __glibcxx_assert(size() == sz); // sz must be a multiple of N
205 }
206
207 constexpr size_t
208 size() const noexcept
209 { return value & _S_size_mask; }
210
211 constexpr size_t
212 alignment() const noexcept
213 { return size_t(1) << (value & _S_align_mask); }
214
215 size_t value; // size | log2(alignment)
216 };
217
218 // Round n up to a multiple of alignment, which must be a power of two.
219 constexpr size_t aligned_ceil(size_t n, size_t alignment)
220 {
221 return (n + alignment - 1) & ~(alignment - 1);
222 }
223
224 } // namespace
225
226 // Memory allocated by the upstream resource is managed in a linked list
227 // of _Chunk objects. A _Chunk object recording the size and alignment of
228 // the allocated block and a pointer to the previous chunk is placed
229 // at end of the block.
230 class monotonic_buffer_resource::_Chunk
231 {
232 public:
233 // Return the address and size of a block of memory allocated from __r,
234 // of at least __size bytes and aligned to __align.
235 // Add a new _Chunk to the front of the linked list at __head.
236 static pair<void*, size_t>
237 allocate(memory_resource* __r, size_t __size, size_t __align,
238 _Chunk*& __head)
239 {
240 const size_t __orig_size = __size;
241
242 // Add space for the _Chunk object and round up to 64 bytes.
243 __size = aligned_ceil(__size + sizeof(_Chunk), 64);
244
245 // Check for unsigned wraparound
246 if (__size < __orig_size) [[unlikely]]
247 {
248 // monotonic_buffer_resource::do_allocate is not allowed to throw.
249 // If the required size is too large for size_t then ask the
250 // upstream resource for an impossibly large size and alignment.
251 __size = -1;
252 __align = ~(size_t(-1) >> 1);
253 }
254
255 void* __p = __r->allocate(__size, __align);
256
257 // Add a chunk defined by (__p, __size, __align) to linked list __head.
258 // We know the end of the buffer is suitably-aligned for a _Chunk
259 // because the caller ensured __align is at least alignof(max_align_t).
260 void* const __back = (char*)__p + __size - sizeof(_Chunk);
261 __head = ::new(__back) _Chunk(__size, __align, __head);
262 return { __p, __size - sizeof(_Chunk) };
263 }
264
265 // Return every chunk in linked list __head to resource __r.
266 static void
267 release(_Chunk*& __head, memory_resource* __r) noexcept
268 {
269 _Chunk* __next = __head;
270 __head = nullptr;
271 while (__next)
272 {
273 _Chunk* __ch = __next;
274 __next = __ch->_M_next;
275 size_t __size = __ch->_M_size.size();
276 size_t __align = __ch->_M_size.alignment();
277 void* __start = (char*)(__ch + 1) - __size;
278 __r->deallocate(__start, __size, __align);
279 }
280 }
281
282 private:
283 _Chunk(size_t __size, size_t __align, _Chunk* __next) noexcept
284 : _M_size(__size, __align), _M_next(__next)
285 { }
286
287 aligned_size<64> _M_size;
288 _Chunk* _M_next;
289 };
290
291 void
292 monotonic_buffer_resource::_M_new_buffer(size_t bytes, size_t alignment)
293 {
294 const size_t n = std::max(bytes, _M_next_bufsiz);
295 const size_t m = aligned_ceil(alignment, alignof(std::max_align_t));
296 auto [p, size] = _Chunk::allocate(_M_upstream, n, m, _M_head);
297 _M_current_buf = p;
298 _M_avail = size;
299 _M_next_bufsiz *= _S_growth_factor;
300 }
301
302 void
303 monotonic_buffer_resource::_M_release_buffers() noexcept
304 {
305 _Chunk::release(_M_head, _M_upstream);
306 }
307
308 // Helper types for synchronized_pool_resource & unsynchronized_pool_resource
309
310 namespace
311 {
312 // Simple bitset with runtime size.
313 // Tracks which blocks in a pool chunk are used/unused.
314 struct bitset
315 {
316 using word = uint64_t;
317 using size_type // unsigned integer type with no more than 32 bits
318 = conditional_t<numeric_limits<size_t>::digits <= 32, size_t, uint32_t>;
319
320 static constexpr unsigned bits_per_word = numeric_limits<word>::digits;
321
322 // The bitset does not own p
323 bitset(void* p, size_type num_blocks)
324 : _M_words(static_cast<word*>(p)), _M_size(num_blocks),
325 _M_next_word(0)
326 {
327 const size_type last_word = num_blocks / bits_per_word;
328 __builtin_memset(_M_words, 0, last_word * sizeof(*_M_words));
329 // Set bits beyond _M_size, so they are not treated as free blocks:
330 if (const size_type extra_bits = num_blocks % bits_per_word)
331 _M_words[last_word] = word(-1) << extra_bits;
332 __glibcxx_assert( empty() );
333 __glibcxx_assert( free() == num_blocks );
334 }
335
336 bitset() = default;
337 ~bitset() = default;
338
339 // Number of blocks
340 size_type size() const noexcept { return _M_size; }
341
342 // Number of free blocks (unset bits)
343 size_type free() const noexcept
344 {
345 size_type n = 0;
346 for (size_type i = _M_next_word; i < nwords(); ++i)
347 n += (bits_per_word - std::__popcount(_M_words[i]));
348 return n;
349 }
350
351 // True if there are no free blocks (all bits are set)
352 bool full() const noexcept
353 {
354 if (_M_next_word >= nwords())
355 return true;
356 // For a bitset with size() > (max_blocks_per_chunk() - 64) we will
357 // have nwords() == (max_word_index() + 1) and so _M_next_word will
358 // never be equal to nwords().
359 // In that case, check if the last word is full:
360 if (_M_next_word == max_word_index())
361 return _M_words[_M_next_word] == word(-1);
362 return false;
363 }
364
365 // True if size() != 0 and all blocks are free (no bits are set).
366 bool empty() const noexcept
367 {
368 if (nwords() == 0)
369 return false;
370 if (_M_next_word != 0)
371 return false;
372 for (size_type i = 0; i < nwords() - 1; ++i)
373 if (_M_words[i] != 0)
374 return false;
375 word last = _M_words[nwords() - 1];
376 if (const size_type extra_bits = size() % bits_per_word)
377 last <<= (bits_per_word - extra_bits);
378 return last == 0;
379 }
380
381 void reset() noexcept
382 {
383 _M_words = nullptr;
384 _M_size = _M_next_word = 0;
385 }
386
387 bool operator[](size_type n) const noexcept
388 {
389 __glibcxx_assert( n < _M_size );
390 const size_type wd = n / bits_per_word;
391 const word bit = word(1) << (n % bits_per_word);
392 return _M_words[wd] & bit;
393 }
394
395 size_type get_first_unset() noexcept
396 {
397 const size_type wd = _M_next_word;
398 if (wd < nwords())
399 {
400 const size_type n = std::__countr_one(_M_words[wd]);
401 if (n < bits_per_word)
402 {
403 const word bit = word(1) << n;
404 _M_words[wd] |= bit;
405 update_next_word();
406 return (wd * bits_per_word) + n;
407 }
408 }
409 return size_type(-1);
410 }
411
412 void set(size_type n) noexcept
413 {
414 __glibcxx_assert( n < _M_size );
415 const size_type wd = n / bits_per_word;
416 const word bit = word(1) << (n % bits_per_word);
417 _M_words[wd] |= bit;
418 if (wd == _M_next_word)
419 update_next_word();
420 }
421
422 void clear(size_type n) noexcept
423 {
424 __glibcxx_assert( n < _M_size );
425 const size_type wd = n / bits_per_word;
426 const word bit = word(1) << (n % bits_per_word);
427 _M_words[wd] &= ~bit;
428 if (wd < _M_next_word)
429 _M_next_word = wd;
430 }
431
432 // Update _M_next_word to refer to the next word with an unset bit.
433 // The size of the _M_next_word bit-field means it cannot represent
434 // the maximum possible nwords() value. To avoid wraparound to zero
435 // this function saturates _M_next_word at max_word_index().
436 void update_next_word() noexcept
437 {
438 size_type next = _M_next_word;
439 while (_M_words[next] == word(-1) && ++next < nwords())
440 { }
441 _M_next_word = std::min(next, max_word_index());
442 }
443
444 void swap(bitset& b) noexcept
445 {
446 std::swap(_M_words, b._M_words);
447 size_type tmp = _M_size;
448 _M_size = b._M_size;
449 b._M_size = tmp;
450 tmp = _M_next_word;
451 _M_next_word = b._M_next_word;
452 b._M_next_word = tmp;
453 }
454
455 size_type nwords() const noexcept
456 { return (_M_size + bits_per_word - 1) / bits_per_word; }
457
458 // Maximum value that can be stored in bitset::_M_size member (approx 500k)
459 static constexpr size_type max_blocks_per_chunk() noexcept
460 { return (size_type(1) << _S_size_digits) - 1; }
461
462 // Maximum value that can be stored in bitset::_M_next_word member (8191).
463 static constexpr size_type max_word_index() noexcept
464 { return (max_blocks_per_chunk() + bits_per_word - 1) / bits_per_word; }
465
466 word* data() const noexcept { return _M_words; }
467
468 private:
469 static constexpr unsigned _S_size_digits
470 = (numeric_limits<size_type>::digits
471 + std::__bit_width(bits_per_word) - 1) / 2;
472
473 word* _M_words = nullptr;
474 // Number of blocks represented by the bitset:
475 size_type _M_size : _S_size_digits;
476 // Index of the first word with unset bits:
477 size_type _M_next_word : numeric_limits<size_type>::digits - _S_size_digits;
478 };
479
480 // A "chunk" belonging to a pool.
481 // A chunk contains many blocks of the same size.
482 // Derived from bitset to reuse its tail-padding.
483 struct chunk : bitset
484 {
485 chunk() = default;
486
487 // p points to the start of a chunk of size bytes in length.
488 // The chunk has space for n blocks, followed by a bitset of size n
489 // that begins at address words.
490 // This object does not own p or words, the caller will free it.
491 chunk(void* p, uint32_t bytes, void* words, size_t n)
492 : bitset(words, n),
493 _M_bytes(bytes),
494 _M_p(static_cast<std::byte*>(p))
495 { __glibcxx_assert(bytes <= chunk::max_bytes_per_chunk()); }
496
497 chunk(chunk&& c) noexcept
498 : bitset(std::move(c)), _M_bytes(c._M_bytes), _M_p(c._M_p)
499 {
500 c._M_bytes = 0;
501 c._M_p = nullptr;
502 c.reset();
503 }
504
505 chunk& operator=(chunk&& c) noexcept
506 {
507 swap(c);
508 return *this;
509 }
510
511 // Allocated size of chunk:
512 bitset::size_type _M_bytes = 0;
513 // Start of allocated chunk:
514 std::byte* _M_p = nullptr;
515
516 // True if there are free blocks in this chunk
517 using bitset::full;
518 // Number of blocks in this chunk
519 using bitset::size;
520
521 static constexpr uint32_t max_bytes_per_chunk() noexcept
522 { return numeric_limits<decltype(_M_bytes)>::max(); }
523
524 // Determine if block with address p and size block_size
525 // is contained within this chunk.
526 bool owns(void* p, size_t block_size)
527 {
528 std::less_equal<uintptr_t> less_equal;
529 return less_equal(reinterpret_cast<uintptr_t>(_M_p),
530 reinterpret_cast<uintptr_t>(p))
531 && less_equal(reinterpret_cast<uintptr_t>(p) + block_size,
532 reinterpret_cast<uintptr_t>(bitset::data()));
533 }
534
535 // Allocate next available block of block_size bytes from this chunk.
536 void* reserve(size_t block_size) noexcept
537 {
538 const size_type n = get_first_unset();
539 if (n == size_type(-1))
540 return nullptr;
541 return _M_p + (n * block_size);
542 }
543
544 // Deallocate a single block of block_size bytes
545 void release(void* vp, size_t block_size)
546 {
547 __glibcxx_assert( owns(vp, block_size) );
548 const size_t offset = static_cast<std::byte*>(vp) - _M_p;
549 // Pointer is correctly aligned for a block in this chunk:
550 __glibcxx_assert( (offset % block_size) == 0 );
551 // Block has been allocated:
552 __glibcxx_assert( (*this)[offset / block_size] == true );
553 bitset::clear(offset / block_size);
554 }
555
556 // Deallocate a single block if it belongs to this chunk.
557 bool try_release(void* p, size_t block_size)
558 {
559 if (!owns(p, block_size))
560 return false;
561 release(p, block_size);
562 return true;
563 }
564
565 void swap(chunk& c) noexcept
566 {
567 std::swap(_M_bytes, c._M_bytes);
568 std::swap(_M_p, c._M_p);
569 bitset::swap(c);
570 }
571
572 bool operator<(const chunk& c) const noexcept
573 { return std::less<const void*>{}(_M_p, c._M_p); }
574
575 friend void swap(chunk& l, chunk& r) { l.swap(r); }
576
577 friend bool operator<(const void* p, const chunk& c) noexcept
578 { return std::less<const void*>{}(p, c._M_p); }
579 };
580
581 // For 64-bit pointers this is the size of three pointers i.e. 24 bytes.
582 // For 32-bit and 20-bit pointers it's four pointers (16 bytes).
583 // For 16-bit pointers it's five pointers (10 bytes).
584 // TODO pad 64-bit to 4*sizeof(void*) to avoid splitting across cache lines?
585 static_assert(sizeof(chunk)
586 == 2 * sizeof(bitset::size_type) + 2 * sizeof(void*));
587
588 // An oversized allocation that doesn't fit in a pool.
589 struct big_block
590 {
591 // The minimum size of a big block.
592 // All big_block allocations will be a multiple of this value.
593 // Use bit_ceil to get a power of two even for e.g. 20-bit size_t.
594 static constexpr size_t min
595 = __bit_ceil((unsigned)numeric_limits<size_t>::digits);
596
597 constexpr
598 big_block(size_t bytes, size_t alignment)
599 : _M_size(alloc_size(bytes), alignment)
600 {
601 // Check for unsigned wraparound
602 if (size() < bytes) [[unlikely]]
603 {
604 // (sync|unsync)_pool_resource::do_allocate is not allowed to throw.
605 // If the required size is too large for size_t then ask the
606 // upstream resource for an impossibly large size and alignment.
607 _M_size.value = -1;
608 }
609 }
610
611 void* pointer = nullptr;
612 aligned_size<min> _M_size;
613
614 constexpr size_t size() const noexcept
615 {
616 if (_M_size.value == size_t(-1)) [[unlikely]]
617 return size_t(-1);
618 return _M_size.size();
619 }
620
621 size_t align() const noexcept
622 { return _M_size.alignment(); }
623
624 // Calculate size to be allocated instead of requested number of bytes.
625 // The requested value will be rounded up to a multiple of big_block::min,
626 // so the low bits are all zero and can be used to hold the alignment.
627 static constexpr size_t alloc_size(size_t bytes) noexcept
628 { return aligned_ceil(bytes, min); }
629
630 friend bool operator<(void* p, const big_block& b) noexcept
631 { return less<void*>{}(p, b.pointer); }
632
633 friend bool operator<(const big_block& b, void* p) noexcept
634 { return less<void*>{}(b.pointer, p); }
635 };
636
637 static_assert(sizeof(big_block) == (2 * sizeof(void*)));
638
639 } // namespace
640
641 // A pool that serves blocks of a particular size.
642 // Each pool manages a number of chunks.
643 // When a pool is full it is replenished by allocating another chunk.
644 struct __pool_resource::_Pool
645 {
646 // Smallest supported block size
647 static constexpr unsigned _S_min_block
648 = std::max(sizeof(void*), alignof(bitset::word));
649
650 _Pool(size_t __block_size, size_t __blocks_per_chunk)
651 : _M_chunks(),
652 _M_block_sz(__block_size),
653 _M_blocks_per_chunk(__blocks_per_chunk)
654 { }
655
656 // Must call release(r) before destruction!
657 ~_Pool() { __glibcxx_assert(_M_chunks.empty()); }
658
659 _Pool(_Pool&&) noexcept = default;
660 _Pool& operator=(_Pool&&) noexcept = default;
661
662 // Size of blocks in this pool
663 size_t block_size() const noexcept
664 { return _M_block_sz; }
665
666 // Allocate a block if the pool is not full, otherwise return null.
667 void* try_allocate() noexcept
668 {
669 const size_t blocksz = block_size();
670 if (!_M_chunks.empty())
671 {
672 auto& last = _M_chunks.back();
673 if (void* p = last.reserve(blocksz))
674 return p;
675 // TODO last is full, so move another chunk to the back instead?
676 for (auto it = _M_chunks.begin(); it != &last; ++it)
677 if (void* p = it->reserve(blocksz))
678 return p;
679 }
680 return nullptr;
681 }
682
683 // Allocate a block from the pool, replenishing from upstream if needed.
684 void* allocate(memory_resource* r, const pool_options& opts)
685 {
686 if (void* p = try_allocate())
687 return p;
688 replenish(r, opts);
689 return _M_chunks.back().reserve(block_size());
690 }
691
692 // Return a block to the pool.
693 bool deallocate(memory_resource*, void* p)
694 {
695 const size_t blocksz = block_size();
696 if (__builtin_expect(!_M_chunks.empty(), true))
697 {
698 auto& last = _M_chunks.back();
699 if (last.try_release(p, blocksz))
700 return true;
701 auto it = std::upper_bound(_M_chunks.begin(), &last, p);
702 if (it != _M_chunks.begin())
703 {
704 it--;
705 if (it->try_release(p, blocksz))
706 // If chunk is empty could return to upstream, but we don't
707 // currently do that. Pools only increase in size.
708 return true;
709 }
710 }
711 return false;
712 }
713
714 void replenish(memory_resource* __r, const pool_options& __opts)
715 {
716 using word = chunk::word;
717 const size_t __blocks = _M_blocks_per_chunk;
718 const auto __bits = chunk::bits_per_word;
719 const size_t __words = (__blocks + __bits - 1) / __bits;
720 const size_t __block_size = block_size();
721 size_t __bytes = __blocks * __block_size + __words * sizeof(word);
722 size_t __alignment = std::__bit_ceil(__block_size);
723 void* __p = __r->allocate(__bytes, __alignment);
724 __try
725 {
726 size_t __n = __blocks * __block_size;
727 void* __pwords = static_cast<char*>(__p) + __n;
728 _M_chunks.insert(chunk(__p, __bytes, __pwords, __blocks), __r);
729 }
730 __catch (...)
731 {
732 __r->deallocate(__p, __bytes, __alignment);
733 }
734 if (_M_blocks_per_chunk < __opts.max_blocks_per_chunk)
735 {
736 const size_t max_blocks
737 = (chunk::max_bytes_per_chunk() - sizeof(word))
738 / (__block_size + 0.125);
739 _M_blocks_per_chunk = std::min({
740 max_blocks,
741 __opts.max_blocks_per_chunk,
742 size_t(_M_blocks_per_chunk * 2)
743 });
744 }
745 }
746
747 void release(memory_resource* __r)
748 {
749 const size_t __alignment = std::__bit_ceil(block_size());
750 for (auto& __c : _M_chunks)
751 if (__c._M_p)
752 __r->deallocate(__c._M_p, __c._M_bytes, __alignment);
753 _M_chunks.clear(__r);
754 }
755
756 // A "resourceless vector" instead of pmr::vector, to save space.
757 // All resize operations need to be passed a memory resource, which
758 // obviously needs to be the same one every time.
759 // Chunks are kept sorted by address of their first block, except for
760 // the most recently-allocated Chunk which is at the end of the vector.
761 struct vector
762 {
763 using value_type = chunk;
764 using size_type = unsigned;
765 using iterator = value_type*;
766
767 // A vector owns its data pointer but not memory held by its elements.
768 chunk* data = nullptr;
769 size_type size = 0;
770 size_type capacity = 0;
771
772 vector() = default;
773
774 vector(size_type __n, memory_resource* __r)
775 : data(polymorphic_allocator<value_type>(__r).allocate(__n)),
776 capacity(__n)
777 { }
778
779 // Must call clear(r) before destruction!
780 ~vector() { __glibcxx_assert(data == nullptr); }
781
782 vector(vector&& __rval) noexcept
783 : data(__rval.data), size(__rval.size), capacity(__rval.capacity)
784 {
785 __rval.data = nullptr;
786 __rval.capacity = __rval.size = 0;
787 }
788
789 vector& operator=(vector&& __rval) noexcept
790 {
791 __glibcxx_assert(data == nullptr);
792 data = __rval.data;
793 size = __rval.size;
794 capacity = __rval.capacity;
795 __rval.data = nullptr;
796 __rval.capacity = __rval.size = 0;
797 return *this;
798 }
799
800 // void resize(size_type __n, memory_resource* __r);
801 // void reserve(size_type __n, memory_resource* __r);
802
803 void clear(memory_resource* __r)
804 {
805 if (!data)
806 return;
807 // Chunks must be individually freed before clearing the vector.
808 std::destroy(begin(), end());
809 polymorphic_allocator<value_type>(__r).deallocate(data, capacity);
810 data = nullptr;
811 capacity = size = 0;
812 }
813
814 // Sort existing elements then insert new one at the end.
815 iterator insert(chunk&& c, memory_resource* r)
816 {
817 if (size < capacity)
818 {
819 if (size > 1)
820 {
821 auto mid = end() - 1;
822 std::rotate(std::lower_bound(begin(), mid, *mid), mid, end());
823 }
824 }
825 else if (size > 0)
826 {
827 polymorphic_allocator<value_type> __alloc(r);
828 auto __mid = std::lower_bound(begin(), end() - 1, back());
829 auto __p = __alloc.allocate(capacity * 1.5);
830 // move [begin,__mid) to new storage
831 auto __p2 = std::move(begin(), __mid, __p);
832 // move end-1 to new storage
833 *__p2 = std::move(back());
834 // move [__mid,end-1) to new storage
835 std::move(__mid, end() - 1, ++__p2);
836 std::destroy(begin(), end());
837 __alloc.deallocate(data, capacity);
838 data = __p;
839 capacity *= 1.5;
840 }
841 else
842 {
843 polymorphic_allocator<value_type> __alloc(r);
844 data = __alloc.allocate(capacity = 8);
845 }
846 auto back = ::new (data + size) chunk(std::move(c));
847 __glibcxx_assert(std::is_sorted(begin(), back));
848 ++size;
849 return back;
850 }
851
852 iterator begin() const { return data; }
853 iterator end() const { return data + size; }
854
855 bool empty() const noexcept { return size == 0; }
856
857 value_type& back() { return data[size - 1]; }
858 };
859
860 vector _M_chunks;
861 unsigned _M_block_sz; // size of blocks allocated from this pool
862 unsigned _M_blocks_per_chunk; // number of blocks to allocate next
863 };
864
865 // An oversized allocation that doesn't fit in a pool.
866 struct __pool_resource::_BigBlock : big_block
867 {
868 using big_block::big_block;
869 };
870
871 namespace
872 {
873 // N.B. it is important that we don't skip any power of two sizes if there
874 // is a non-power of two size between them, e.g. must not have pool sizes
875 // of 24 and 40 without having a pool size of 32. Otherwise an allocation
876 // of 32 bytes with alignment 16 would choose the 40-byte pool which is not
877 // correctly aligned for 16-byte alignment. It would be OK (but suboptimal)
878 // to have no pool of size 32 if we have pool sizes of 16 and 64 and no
879 // non-power of two sizes between those, because the example of (32, 16)
880 // would choose the 64-byte pool, which would be correctly aligned.
881
882 constexpr size_t pool_sizes[] = {
883 8, 16, 24,
884 32, 48,
885 64, 80, 96, 112,
886 128, 192,
887 256, 320, 384, 448,
888 512, 768,
889 #if __SIZE_WIDTH__ > 16
890 // Use bigger pools if size_t has at least 20 bits.
891 1024, 1536,
892 2048, 3072,
893 #if __INT_WIDTH__ >= 32
894 // Use even bigger pools if int has at least 32 bits.
895 1<<12, 1<<13, 1<<14,
896 1<<15, 1<<16, 1<<17,
897 1<<20, 1<<21, 1<<22 // 4MB should be enough for anybody
898 #endif
899 #endif
900 };
901
902 pool_options
903 munge_options(pool_options opts)
904 {
905 // The values in the returned struct may differ from those supplied
906 // to the pool resource constructor in that values of zero will be
907 // replaced with implementation-defined defaults, and sizes may be
908 // rounded to unspecified granularity.
909
910 // max_blocks_per_chunk sets the absolute maximum for the pool resource.
911 // Each pool might have a smaller maximum, because pools for very large
912 // objects might impose smaller limit.
913 if (opts.max_blocks_per_chunk == 0)
914 {
915 // Pick a default that depends on the number of bits in size_t.
916 opts.max_blocks_per_chunk = __SIZE_WIDTH__ << 8;
917 }
918 else
919 {
920 // Round to preferred granularity.
921 if (opts.max_blocks_per_chunk < size_t(-4))
922 {
923 // round up
924 opts.max_blocks_per_chunk
925 = aligned_ceil(opts.max_blocks_per_chunk, 4);
926 }
927 else
928 {
929 // round down
930 opts.max_blocks_per_chunk &= ~size_t(3);
931 }
932 }
933
934 if (opts.max_blocks_per_chunk > chunk::max_blocks_per_chunk())
935 {
936 opts.max_blocks_per_chunk = chunk::max_blocks_per_chunk();
937 }
938
939 // largest_required_pool_block specifies the largest block size that will
940 // be allocated from a pool. Larger allocations will come directly from
941 // the upstream resource and so will not be pooled.
942 if (opts.largest_required_pool_block == 0)
943 {
944 // Pick a sensible default that depends on the number of bits in size_t
945 // (pools with larger block sizes must be explicitly requested by
946 // using a non-zero value for largest_required_pool_block).
947 opts.largest_required_pool_block = __SIZE_WIDTH__ << 6;
948 }
949 else
950 {
951 // Round to preferred granularity
952 static_assert(std::__has_single_bit(pool_sizes[0]));
953 opts.largest_required_pool_block
954 = aligned_ceil(opts.largest_required_pool_block, pool_sizes[0]);
955 }
956
957 if (opts.largest_required_pool_block < big_block::min)
958 {
959 opts.largest_required_pool_block = big_block::min;
960 }
961 else if (opts.largest_required_pool_block > std::end(pool_sizes)[-1])
962 {
963 // Setting _M_opts to the largest pool allows users to query it:
964 opts.largest_required_pool_block = std::end(pool_sizes)[-1];
965 }
966 return opts;
967 }
968
969 inline int
970 pool_index(size_t block_size, int npools)
971 {
972 auto p = std::lower_bound(pool_sizes, pool_sizes + npools, block_size);
973 int n = p - pool_sizes;
974 if (n != npools)
975 return n;
976 return -1;
977 }
978
979 inline int
980 select_num_pools(const pool_options& opts)
981 {
982 auto p = std::lower_bound(std::begin(pool_sizes), std::end(pool_sizes),
983 opts.largest_required_pool_block);
984 const int n = p - std::begin(pool_sizes);
985 if (p == std::end(pool_sizes))
986 return n;
987 return n + 1;
988 }
989
990 #ifdef _GLIBCXX_HAS_GTHREADS
991 using shared_lock = std::shared_lock<shared_mutex>;
992 using exclusive_lock = lock_guard<shared_mutex>;
993 #endif
994
995 } // namespace
996
997 __pool_resource::
998 __pool_resource(const pool_options& opts, memory_resource* upstream)
999 : _M_opts(munge_options(opts)), _M_unpooled(upstream),
1000 _M_npools(select_num_pools(_M_opts))
1001 { }
1002
1003 __pool_resource::~__pool_resource() { release(); }
1004
1005 void
1006 __pool_resource::release() noexcept
1007 {
1008 memory_resource* res = resource();
1009 // deallocate oversize allocations
1010 for (auto& b : _M_unpooled)
1011 res->deallocate(b.pointer, b.size(), b.align());
1012 pmr::vector<_BigBlock>{res}.swap(_M_unpooled);
1013 }
1014
1015 void*
1016 __pool_resource::allocate(size_t bytes, size_t alignment)
1017 {
1018 auto& b = _M_unpooled.emplace_back(bytes, alignment);
1019 __try {
1020 // N.B. need to allocate b.size(), which might be larger than bytes.
1021 // Also use b.align() instead of alignment parameter, which will be
1022 // an impossibly large value if (bytes+bookkeeping) > SIZE_MAX.
1023 void* p = resource()->allocate(b.size(), b.align());
1024 b.pointer = p;
1025 if (_M_unpooled.size() > 1)
1026 {
1027 const auto mid = _M_unpooled.end() - 1;
1028 // move to right position in vector
1029 std::rotate(std::lower_bound(_M_unpooled.begin(), mid, p),
1030 mid, _M_unpooled.end());
1031 }
1032 return p;
1033 } __catch(...) {
1034 _M_unpooled.pop_back();
1035 __throw_exception_again;
1036 }
1037 }
1038
1039 void
1040 __pool_resource::deallocate(void* p, size_t bytes [[maybe_unused]],
1041 size_t alignment [[maybe_unused]])
1042 {
1043 const auto it
1044 = std::lower_bound(_M_unpooled.begin(), _M_unpooled.end(), p);
1045 __glibcxx_assert(it != _M_unpooled.end() && it->pointer == p);
1046 if (it != _M_unpooled.end() && it->pointer == p) // [[likely]]
1047 {
1048 const auto b = *it;
1049 __glibcxx_assert(b.size() == b.alloc_size(bytes));
1050 __glibcxx_assert(b.align() == alignment);
1051 _M_unpooled.erase(it);
1052 // N.B. need to deallocate b.size(), which might be larger than bytes.
1053 resource()->deallocate(p, b.size(), b.align());
1054 }
1055 }
1056
1057 // Create array of pools, allocated from upstream resource.
1058 auto
1059 __pool_resource::_M_alloc_pools()
1060 -> _Pool*
1061 {
1062 polymorphic_allocator<_Pool> alloc{resource()};
1063 _Pool* p = alloc.allocate(_M_npools);
1064 for (int i = 0; i < _M_npools; ++i)
1065 {
1066 // For last pool use largest_required_pool_block
1067 const size_t block_size = (i+1 == _M_npools)
1068 ? _M_opts.largest_required_pool_block
1069 : pool_sizes[i];
1070
1071 // Decide on initial number of blocks per chunk.
1072 // At least 16 blocks per chunk seems reasonable,
1073 // more for smaller blocks:
1074 size_t blocks_per_chunk = 1024 / block_size;
1075 blocks_per_chunk = std::max(size_t(16), blocks_per_chunk);
1076 // But don't exceed the requested max_blocks_per_chunk:
1077 blocks_per_chunk
1078 = std::min(blocks_per_chunk, _M_opts.max_blocks_per_chunk);
1079 // Allow space for bitset to track which blocks are used/unused:
1080 blocks_per_chunk *= 1 - 1.0 / (__CHAR_BIT__ * block_size);
1081 // Construct a _Pool for the given block size and initial chunk size:
1082 alloc.construct(p + i, block_size, blocks_per_chunk);
1083 }
1084 return p;
1085 }
1086
1087 // Determine the appropriate allocation size, rounding up to a multiple
1088 // of the alignment if needed.
1089 static inline size_t
1090 choose_block_size(size_t bytes, size_t alignment)
1091 {
1092 if (bytes == 0) [[unlikely]]
1093 return alignment;
1094
1095 // Use bit_ceil in case alignment is invalid (i.e. not a power of two).
1096 size_t mask = std::__bit_ceil(alignment) - 1;
1097 // Round up to a multiple of alignment.
1098 size_t block_size = (bytes + mask) & ~mask;
1099
1100 if (block_size >= bytes) [[likely]]
1101 return block_size;
1102
1103 // Wrapped around to zero, bytes must have been impossibly large.
1104 return numeric_limits<size_t>::max();
1105 }
1106
1107
1108 #ifdef _GLIBCXX_HAS_GTHREADS
1109 // synchronized_pool_resource members.
1110
1111 /* Notes on implementation and thread safety:
1112 *
1113 * Each synchronized_pool_resource manages a linked list of N+1 _TPools
1114 * objects, where N is the number of threads using the pool resource.
1115 * Each _TPools object has its own set of pools, with their own chunks.
1116 * The first element of the list, _M_tpools[0], can be used by any thread.
1117 * The rest of the list contains a _TPools object for each thread,
1118 * accessed via the thread-specific key _M_key (and referred to for
1119 * exposition as _M_tpools[_M_key]).
1120 * The first element, _M_tpools[0], contains "orphaned chunks" which were
1121 * allocated by a thread which has since exited, and so there is no
1122 * _M_tpools[_M_key] for that thread. Orphaned chunks are never reused,
1123 * they're only held in _M_tpools[0] so they can be deallocated.
1124 * A thread can access its own thread-specific set of pools via _M_key
1125 * while holding a shared lock on _M_mx. Accessing _M_impl._M_unpooled
1126 * or _M_tpools[0] or any other thread's _M_tpools[_M_key] requires an
1127 * exclusive lock.
1128 * The upstream_resource() pointer can be obtained without a lock, but
1129 * any dereference of that pointer requires an exclusive lock.
1130 * The _M_impl._M_opts and _M_impl._M_npools members are immutable,
1131 * and can safely be accessed concurrently.
1132 *
1133 * In a single-threaded program (i.e. __gthread_active_p() == false)
1134 * the pool resource only needs one set of pools and never has orphaned
1135 * chunks, so just uses _M_tpools[0] directly, and _M_tpools->next is null.
1136 */
1137
1138 extern "C" {
1139 static void destroy_TPools(void*);
1140 }
1141
1142 struct synchronized_pool_resource::_TPools
1143 {
1144 // Exclusive lock must be held in the thread where this constructor runs.
1145 explicit
1146 _TPools(synchronized_pool_resource& owner, exclusive_lock&)
1147 : owner(owner), pools(owner._M_impl._M_alloc_pools())
1148 {
1149 // __builtin_printf("%p constructing\n", this);
1150 __glibcxx_assert(pools);
1151 }
1152
1153 // Exclusive lock must be held in the thread where this destructor runs.
1154 ~_TPools()
1155 {
1156 __glibcxx_assert(pools);
1157 if (pools)
1158 {
1159 memory_resource* r = owner.upstream_resource();
1160 for (int i = 0; i < owner._M_impl._M_npools; ++i)
1161 pools[i].release(r);
1162 std::destroy_n(pools, owner._M_impl._M_npools);
1163 polymorphic_allocator<__pool_resource::_Pool> a(r);
1164 a.deallocate(pools, owner._M_impl._M_npools);
1165 }
1166 if (prev)
1167 prev->next = next;
1168 if (next)
1169 next->prev = prev;
1170 }
1171
1172 // Exclusive lock must be held in the thread where this function runs.
1173 void move_nonempty_chunks()
1174 {
1175 __glibcxx_assert(pools);
1176 __glibcxx_assert(__gthread_active_p());
1177 if (!pools)
1178 return;
1179 memory_resource* const r = owner.upstream_resource();
1180 auto* const shared = owner._M_tpools->pools;
1181 // move all non-empty chunks to the shared _TPools
1182 for (int i = 0; i < owner._M_impl._M_npools; ++i)
1183 for (auto& c : pools[i]._M_chunks)
1184 if (!c.empty())
1185 shared[i]._M_chunks.insert(std::move(c), r);
1186 }
1187
1188 synchronized_pool_resource& owner;
1189 __pool_resource::_Pool* pools = nullptr;
1190 _TPools* prev = nullptr;
1191 _TPools* next = nullptr;
1192
1193 static void destroy(_TPools* p)
1194 {
1195 exclusive_lock l(p->owner._M_mx);
1196 // __glibcxx_assert(p != p->owner._M_tpools);
1197 p->move_nonempty_chunks();
1198 polymorphic_allocator<_TPools> a(p->owner.upstream_resource());
1199 p->~_TPools();
1200 a.deallocate(p, 1);
1201 }
1202 };
1203
1204 // Called when a thread exits
1205 extern "C" {
1206 static void destroy_TPools(void* p)
1207 {
1208 using _TPools = synchronized_pool_resource::_TPools;
1209 _TPools::destroy(static_cast<_TPools*>(p));
1210 }
1211 }
1212
1213 // Constructor
1214 synchronized_pool_resource::
1215 synchronized_pool_resource(const pool_options& opts,
1216 memory_resource* upstream)
1217 : _M_impl(opts, upstream)
1218 {
1219 if (__gthread_active_p())
1220 if (int err = __gthread_key_create(&_M_key, destroy_TPools))
1221 __throw_system_error(err);
1222 exclusive_lock l(_M_mx);
1223 _M_tpools = _M_alloc_shared_tpools(l);
1224 }
1225
1226 // Destructor
1227 synchronized_pool_resource::~synchronized_pool_resource()
1228 {
1229 release();
1230 if (__gthread_active_p())
1231 __gthread_key_delete(_M_key); // does not run destroy_TPools
1232 }
1233
1234 void
1235 synchronized_pool_resource::release()
1236 {
1237 exclusive_lock l(_M_mx);
1238 if (_M_tpools)
1239 {
1240 if (__gthread_active_p())
1241 {
1242 __gthread_key_delete(_M_key); // does not run destroy_TPools
1243 __gthread_key_create(&_M_key, destroy_TPools);
1244 }
1245 polymorphic_allocator<_TPools> a(upstream_resource());
1246 // destroy+deallocate each _TPools
1247 do
1248 {
1249 _TPools* p = _M_tpools;
1250 _M_tpools = _M_tpools->next;
1251 p->~_TPools();
1252 a.deallocate(p, 1);
1253 }
1254 while (_M_tpools);
1255 }
1256 // release unpooled memory
1257 _M_impl.release();
1258 }
1259
1260 // Caller must hold shared or exclusive lock to ensure the pointer
1261 // isn't invalidated before it can be used.
1262 auto
1263 synchronized_pool_resource::_M_thread_specific_pools() noexcept
1264 {
1265 __pool_resource::_Pool* pools = nullptr;
1266 __glibcxx_assert(__gthread_active_p());
1267 if (auto tp = static_cast<_TPools*>(__gthread_getspecific(_M_key)))
1268 {
1269 pools = tp->pools;
1270 // __glibcxx_assert(tp->pools);
1271 }
1272 return pools;
1273 }
1274
1275 // Override for memory_resource::do_allocate
1276 void*
1277 synchronized_pool_resource::
1278 do_allocate(size_t bytes, size_t alignment)
1279 {
1280 const auto block_size = choose_block_size(bytes, alignment);
1281 const pool_options opts = _M_impl._M_opts;
1282 if (block_size <= opts.largest_required_pool_block)
1283 {
1284 const ptrdiff_t index = pool_index(block_size, _M_impl._M_npools);
1285 if (__gthread_active_p())
1286 {
1287 // Try to allocate from the thread-specific pool.
1288 shared_lock l(_M_mx);
1289 if (auto pools = _M_thread_specific_pools()) // [[likely]]
1290 {
1291 // Need exclusive lock to replenish so use try_allocate:
1292 if (void* p = pools[index].try_allocate())
1293 return p;
1294 // Need to take exclusive lock and replenish pool.
1295 }
1296 // Need to allocate or replenish thread-specific pools using
1297 // upstream resource, so need to hold exclusive lock.
1298 }
1299 else // single-threaded
1300 {
1301 if (!_M_tpools) // [[unlikely]]
1302 {
1303 exclusive_lock dummy(_M_mx);
1304 _M_tpools = _M_alloc_shared_tpools(dummy);
1305 }
1306 return _M_tpools->pools[index].allocate(upstream_resource(), opts);
1307 }
1308
1309 // N.B. Another thread could call release() now lock is not held.
1310 exclusive_lock excl(_M_mx);
1311 if (!_M_tpools) // [[unlikely]]
1312 _M_tpools = _M_alloc_shared_tpools(excl);
1313 auto pools = _M_thread_specific_pools();
1314 if (!pools)
1315 pools = _M_alloc_tpools(excl)->pools;
1316 return pools[index].allocate(upstream_resource(), opts);
1317 }
1318 exclusive_lock l(_M_mx);
1319 return _M_impl.allocate(bytes, alignment); // unpooled allocation
1320 }
1321
1322 // Override for memory_resource::do_deallocate
1323 void
1324 synchronized_pool_resource::
1325 do_deallocate(void* p, size_t bytes, size_t alignment)
1326 {
1327 size_t block_size = choose_block_size(bytes, alignment);
1328 if (block_size <= _M_impl._M_opts.largest_required_pool_block)
1329 {
1330 const ptrdiff_t index = pool_index(block_size, _M_impl._M_npools);
1331 __glibcxx_assert(index != -1);
1332 if (__gthread_active_p())
1333 {
1334 shared_lock l(_M_mx);
1335 if (auto pools = _M_thread_specific_pools())
1336 {
1337 // No need to lock here, no other thread is accessing this pool.
1338 if (pools[index].deallocate(upstream_resource(), p))
1339 return;
1340 }
1341 // Block might have come from a different thread's pool,
1342 // take exclusive lock and check every pool.
1343 }
1344 else // single-threaded
1345 {
1346 __glibcxx_assert(_M_tpools != nullptr);
1347 if (_M_tpools) // [[likely]]
1348 _M_tpools->pools[index].deallocate(upstream_resource(), p);
1349 return;
1350 }
1351
1352 // TODO store {p, bytes, alignment} somewhere and defer returning
1353 // the block to the correct thread-specific pool until we next
1354 // take the exclusive lock.
1355
1356 exclusive_lock excl(_M_mx);
1357 auto my_pools = _M_thread_specific_pools();
1358 for (_TPools* t = _M_tpools; t != nullptr; t = t->next)
1359 {
1360 if (t->pools != my_pools)
1361 if (t->pools) // [[likely]]
1362 {
1363 if (t->pools[index].deallocate(upstream_resource(), p))
1364 return;
1365 }
1366 }
1367 // Not necessarily an error to reach here, release() could have been
1368 // called on another thread between releasing the shared lock and
1369 // acquiring the exclusive lock.
1370 return;
1371 }
1372 exclusive_lock l(_M_mx);
1373 _M_impl.deallocate(p, bytes, alignment);
1374 }
1375
1376 // Allocate a thread-specific _TPools object and add it to the linked list.
1377 auto
1378 synchronized_pool_resource::_M_alloc_tpools(exclusive_lock& l)
1379 -> _TPools*
1380 {
1381 __glibcxx_assert(_M_tpools != nullptr);
1382 __glibcxx_assert(__gthread_active_p());
1383 // dump_list(_M_tpools);
1384 polymorphic_allocator<_TPools> a(upstream_resource());
1385 _TPools* p = a.allocate(1);
1386 bool constructed = false;
1387 __try
1388 {
1389 a.construct(p, *this, l);
1390 constructed = true;
1391 // __glibcxx_assert(__gthread_getspecific(_M_key) == nullptr);
1392 if (int err = __gthread_setspecific(_M_key, p))
1393 __throw_system_error(err);
1394 }
1395 __catch(...)
1396 {
1397 if (constructed)
1398 a.destroy(p);
1399 a.deallocate(p, 1);
1400 __throw_exception_again;
1401 }
1402 p->prev = _M_tpools;
1403 p->next = _M_tpools->next;
1404 _M_tpools->next = p;
1405 if (p->next)
1406 p->next->prev = p;
1407 return p;
1408 }
1409
1410 // Allocate the shared _TPools object, _M_tpools[0]
1411 auto
1412 synchronized_pool_resource::_M_alloc_shared_tpools(exclusive_lock& l)
1413 -> _TPools*
1414 {
1415 __glibcxx_assert(_M_tpools == nullptr);
1416 polymorphic_allocator<_TPools> a(upstream_resource());
1417 _TPools* p = a.allocate(1);
1418 __try
1419 {
1420 a.construct(p, *this, l);
1421 }
1422 __catch(...)
1423 {
1424 a.deallocate(p, 1);
1425 __throw_exception_again;
1426 }
1427 // __glibcxx_assert(p->next == nullptr);
1428 // __glibcxx_assert(p->prev == nullptr);
1429 return p;
1430 }
1431 #endif // _GLIBCXX_HAS_GTHREADS
1432
1433 // unsynchronized_pool_resource member functions
1434
1435 // Constructor
1436 unsynchronized_pool_resource::
1437 unsynchronized_pool_resource(const pool_options& opts,
1438 memory_resource* upstream)
1439 : _M_impl(opts, upstream), _M_pools(_M_impl._M_alloc_pools())
1440 { }
1441
1442 // Destructor
1443 unsynchronized_pool_resource::~unsynchronized_pool_resource()
1444 { release(); }
1445
1446 // Return all memory to upstream resource.
1447 void
1448 unsynchronized_pool_resource::release()
1449 {
1450 // release pooled memory
1451 if (_M_pools)
1452 {
1453 memory_resource* res = upstream_resource();
1454 polymorphic_allocator<_Pool> alloc{res};
1455 for (int i = 0; i < _M_impl._M_npools; ++i)
1456 {
1457 _M_pools[i].release(res);
1458 alloc.destroy(_M_pools + i);
1459 }
1460 alloc.deallocate(_M_pools, _M_impl._M_npools);
1461 _M_pools = nullptr;
1462 }
1463
1464 // release unpooled memory
1465 _M_impl.release();
1466 }
1467
1468 // Find the right pool for a block of size block_size.
1469 auto
1470 unsynchronized_pool_resource::_M_find_pool(size_t block_size) noexcept
1471 {
1472 __pool_resource::_Pool* pool = nullptr;
1473 if (_M_pools) // [[likely]]
1474 {
1475 int index = pool_index(block_size, _M_impl._M_npools);
1476 if (index != -1)
1477 pool = _M_pools + index;
1478 }
1479 return pool;
1480 }
1481
1482 // Override for memory_resource::do_allocate
1483 void*
1484 unsynchronized_pool_resource::do_allocate(size_t bytes, size_t alignment)
1485 {
1486 const auto block_size = choose_block_size(bytes, alignment);
1487 if (block_size <= _M_impl._M_opts.largest_required_pool_block)
1488 {
1489 // Recreate pools if release() has been called:
1490 if (__builtin_expect(_M_pools == nullptr, false))
1491 _M_pools = _M_impl._M_alloc_pools();
1492 if (auto pool = _M_find_pool(block_size))
1493 return pool->allocate(upstream_resource(), _M_impl._M_opts);
1494 }
1495 return _M_impl.allocate(bytes, alignment);
1496 }
1497
1498 // Override for memory_resource::do_deallocate
1499 void
1500 unsynchronized_pool_resource::
1501 do_deallocate(void* p, size_t bytes, size_t alignment)
1502 {
1503 size_t block_size = choose_block_size(bytes, alignment);
1504 if (block_size <= _M_impl._M_opts.largest_required_pool_block)
1505 {
1506 if (auto pool = _M_find_pool(block_size))
1507 {
1508 pool->deallocate(upstream_resource(), p);
1509 return;
1510 }
1511 }
1512 _M_impl.deallocate(p, bytes, alignment);
1513 }
1514
1515 } // namespace pmr
1516 _GLIBCXX_END_NAMESPACE_VERSION
1517 } // namespace std