1 // MT-optimized allocator -*- C++ -*-
3 // Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
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 2, or (at your option)
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.
16 // You should have received a copy of the GNU General Public License along
17 // with this library; see the file COPYING. If not, write to the Free
18 // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
21 // As a special exception, you may use this file as part of a free software
22 // library without restriction. Specifically, if other files instantiate
23 // templates or use macros or inline functions from this file, or you compile
24 // this file and link it with other files to produce an executable, this
25 // file does not by itself cause the resulting executable to be covered by
26 // the GNU General Public License. This exception does not however
27 // invalidate any other reasons why the executable file might be covered by
28 // the GNU General Public License.
30 /** @file ext/mt_allocator.h
31 * This file is a GNU extension to the Standard C++ Library.
34 #ifndef _MT_ALLOCATOR_H
35 #define _MT_ALLOCATOR_H 1
39 #include <bits/functexcept.h>
40 #include <bits/gthr.h>
41 #include <bits/atomicity.h>
45 typedef void (*__destroy_handler)(void*);
47 /// @brief Base class for pool object.
50 // Using short int as type for the binmap implies we are never
51 // caching blocks larger than 32768 with this allocator.
52 typedef unsigned short int _Binmap_type;
54 // Variables used to configure the behavior of the allocator,
55 // assigned and explained in detail below.
58 // Compile time constants for the default _Tune values.
59 enum { _S_align = 8 };
60 enum { _S_max_bytes = 128 };
61 enum { _S_min_bin = 8 };
62 enum { _S_chunk_size = 4096 - 4 * sizeof(void*) };
63 enum { _S_max_threads = 4096 };
64 enum { _S_freelist_headroom = 10 };
67 // NB: In any case must be >= sizeof(_Block_record), that
68 // is 4 on 32 bit machines and 8 on 64 bit machines.
71 // Allocation requests (after round-up to power of 2) below
72 // this value will be handled by the allocator. A raw new/
73 // call will be used for requests larger than this value.
74 // NB: Must be much smaller than _M_chunk_size and in any
78 // Size in bytes of the smallest bin.
79 // NB: Must be a power of 2 and >= _M_align (and of course
80 // much smaller than _M_max_bytes).
83 // In order to avoid fragmenting and minimize the number of
84 // new() calls we always request new memory using this
85 // value. Based on previous discussions on the libstdc++
86 // mailing list we have choosen the value below.
87 // See http://gcc.gnu.org/ml/libstdc++/2001-07/msg00077.html
88 // NB: At least one order of magnitude > _M_max_bytes.
91 // The maximum number of supported threads. For
92 // single-threaded operation, use one. Maximum values will
93 // vary depending on details of the underlying system. (For
94 // instance, Linux 2.4.18 reports 4070 in
95 // /proc/sys/kernel/threads-max, while Linux 2.6.6 reports
97 size_t _M_max_threads;
99 // Each time a deallocation occurs in a threaded application
100 // we make sure that there are no more than
101 // _M_freelist_headroom % of used memory on the freelist. If
102 // the number of additional records is more than
103 // _M_freelist_headroom % of the freelist, we move these
104 // records back to the global pool.
105 size_t _M_freelist_headroom;
107 // Set to true forces all allocations to use new().
112 : _M_align(_S_align), _M_max_bytes(_S_max_bytes), _M_min_bin(_S_min_bin),
113 _M_chunk_size(_S_chunk_size), _M_max_threads(_S_max_threads),
114 _M_freelist_headroom(_S_freelist_headroom),
115 _M_force_new(getenv("GLIBCXX_FORCE_NEW") ? true : false)
119 _Tune(size_t __align, size_t __maxb, size_t __minbin, size_t __chunk,
120 size_t __maxthreads, size_t __headroom, bool __force)
121 : _M_align(__align), _M_max_bytes(__maxb), _M_min_bin(__minbin),
122 _M_chunk_size(__chunk), _M_max_threads(__maxthreads),
123 _M_freelist_headroom(__headroom), _M_force_new(__force)
127 struct _Block_address
130 _Block_address* _M_next;
134 _M_get_options() const
135 { return _M_options; }
138 _M_set_options(_Tune __t)
145 _M_check_threshold(size_t __bytes)
146 { return __bytes > _M_options._M_max_bytes || _M_options._M_force_new; }
149 _M_get_binmap(size_t __bytes)
150 { return _M_binmap[__bytes]; }
154 { return _M_options._M_align; }
158 : _M_options(_Tune()), _M_binmap(NULL), _M_init(false) { }
161 __pool_base(const _Tune& __options)
162 : _M_options(__options), _M_binmap(NULL), _M_init(false) { }
166 __pool_base(const __pool_base&);
169 operator=(const __pool_base&);
172 // Configuration options.
175 _Binmap_type* _M_binmap;
177 // Configuration of the pool object via _M_options can happen
178 // after construction but before initialization. After
179 // initialization is complete, this variable is set to true.
185 * @brief Data describing the underlying memory pool, parameterized on
188 template<bool _Thread>
191 /// Specialization for single thread.
193 class __pool<false> : public __pool_base
198 // Points to the block_record of the next free block.
199 _Block_record* volatile _M_next;
204 // An "array" of pointers to the first free block.
205 _Block_record** volatile _M_first;
207 // A list of the initial addresses of all allocated blocks.
208 _Block_address* _M_address;
214 if (__builtin_expect(_M_init == false, false))
219 _M_destroy() throw();
222 _M_reserve_block(size_t __bytes, const size_t __thread_id);
225 _M_reclaim_block(char* __p, size_t __bytes);
228 _M_get_thread_id() { return 0; }
231 _M_get_bin(size_t __which)
232 { return _M_bin[__which]; }
235 _M_adjust_freelist(const _Bin_record&, _Block_record*, size_t)
239 : _M_bin(NULL), _M_bin_size(1) { }
241 explicit __pool(const __pool_base::_Tune& __tune)
242 : __pool_base(__tune), _M_bin(NULL), _M_bin_size(1) { }
245 // An "array" of bin_records each of which represents a specific
246 // power of 2 size. Memory to this "array" is allocated in
248 _Bin_record* volatile _M_bin;
250 // Actual value calculated in _M_initialize().
258 /// Specialization for thread enabled, via gthreads.h.
260 class __pool<true> : public __pool_base
263 // Each requesting thread is assigned an id ranging from 1 to
264 // _S_max_threads. Thread id 0 is used as a global memory pool.
265 // In order to get constant performance on the thread assignment
266 // routine, we keep a list of free ids. When a thread first
267 // requests memory we remove the first record in this list and
268 // stores the address in a __gthread_key. When initializing the
269 // __gthread_key we specify a destructor. When this destructor
270 // (i.e. the thread dies) is called, we return the thread id to
271 // the front of this list.
272 struct _Thread_record
274 // Points to next free thread id record. NULL if last record in list.
275 _Thread_record* volatile _M_next;
277 // Thread id ranging from 1 to _S_max_threads.
283 // Points to the block_record of the next free block.
284 _Block_record* volatile _M_next;
286 // The thread id of the thread which has requested this block.
292 // An "array" of pointers to the first free block for each
293 // thread id. Memory to this "array" is allocated in
294 // _S_initialize() for _S_max_threads + global pool 0.
295 _Block_record** volatile _M_first;
297 // A list of the initial addresses of all allocated blocks.
298 _Block_address* _M_address;
300 // An "array" of counters used to keep track of the amount of
301 // blocks that are on the freelist/used for each thread id.
302 // Memory to these "arrays" is allocated in _S_initialize() for
303 // _S_max_threads + global pool 0.
304 size_t* volatile _M_free;
305 size_t* volatile _M_used;
307 // Each bin has its own mutex which is used to ensure data
308 // integrity while changing "ownership" on a block. The mutex
309 // is initialized in _S_initialize().
310 __gthread_mutex_t* _M_mutex;
313 // XXX GLIBCXX_ABI Deprecated
315 _M_initialize(__destroy_handler);
320 if (__builtin_expect(_M_init == false, false))
325 _M_destroy() throw();
328 _M_reserve_block(size_t __bytes, const size_t __thread_id);
331 _M_reclaim_block(char* __p, size_t __bytes);
334 _M_get_bin(size_t __which)
335 { return _M_bin[__which]; }
338 _M_adjust_freelist(const _Bin_record& __bin, _Block_record* __block,
341 if (__gthread_active_p())
343 __block->_M_thread_id = __thread_id;
344 --__bin._M_free[__thread_id];
345 ++__bin._M_used[__thread_id];
349 // XXX GLIBCXX_ABI Deprecated
351 _M_destroy_thread_key(void*);
357 : _M_bin(NULL), _M_bin_size(1), _M_thread_freelist(NULL)
360 explicit __pool(const __pool_base::_Tune& __tune)
361 : __pool_base(__tune), _M_bin(NULL), _M_bin_size(1),
362 _M_thread_freelist(NULL)
366 // An "array" of bin_records each of which represents a specific
367 // power of 2 size. Memory to this "array" is allocated in
369 _Bin_record* volatile _M_bin;
371 // Actual value calculated in _M_initialize().
374 _Thread_record* _M_thread_freelist;
375 void* _M_thread_freelist_initial;
382 template<template <bool> class _PoolTp, bool _Thread>
385 typedef _PoolTp<_Thread> pool_type;
390 static pool_type _S_pool;
395 template<template <bool> class _PoolTp, bool _Thread>
396 struct __common_pool_base;
398 template<template <bool> class _PoolTp>
399 struct __common_pool_base<_PoolTp, false>
400 : public __common_pool<_PoolTp, false>
402 using __common_pool<_PoolTp, false>::_S_get_pool;
408 if (__builtin_expect(__init == false, false))
410 _S_get_pool()._M_initialize_once();
417 template<template <bool> class _PoolTp>
418 struct __common_pool_base<_PoolTp, true>
419 : public __common_pool<_PoolTp, true>
421 using __common_pool<_PoolTp, true>::_S_get_pool;
425 { _S_get_pool()._M_initialize_once(); }
431 if (__builtin_expect(__init == false, false))
433 if (__gthread_active_p())
435 // On some platforms, __gthread_once_t is an aggregate.
436 static __gthread_once_t __once = __GTHREAD_ONCE_INIT;
437 __gthread_once(&__once, _S_initialize);
440 // Double check initialization. May be necessary on some
441 // systems for proper construction when not compiling with
443 _S_get_pool()._M_initialize_once();
450 /// @brief Policy for shared __pool objects.
451 template<template <bool> class _PoolTp, bool _Thread>
452 struct __common_pool_policy : public __common_pool_base<_PoolTp, _Thread>
454 template<typename _Tp1, template <bool> class _PoolTp1 = _PoolTp,
455 bool _Thread1 = _Thread>
457 { typedef __common_pool_policy<_PoolTp1, _Thread1> other; };
459 using __common_pool_base<_PoolTp, _Thread>::_S_get_pool;
460 using __common_pool_base<_PoolTp, _Thread>::_S_initialize_once;
464 template<typename _Tp, template <bool> class _PoolTp, bool _Thread>
465 struct __per_type_pool
467 typedef _Tp value_type;
468 typedef _PoolTp<_Thread> pool_type;
473 // Sane defaults for the _PoolTp.
474 typedef typename pool_type::_Block_record _Block_record;
475 const static size_t __a = (__alignof__(_Tp) >= sizeof(_Block_record)
476 ? __alignof__(_Tp) : sizeof(_Block_record));
478 typedef typename __pool_base::_Tune _Tune;
479 static _Tune _S_tune(__a, sizeof(_Tp) * 64,
480 sizeof(_Tp) * 2 >= __a ? sizeof(_Tp) * 2 : __a,
481 sizeof(_Tp) * size_t(_Tune::_S_chunk_size),
482 _Tune::_S_max_threads,
483 _Tune::_S_freelist_headroom,
484 getenv("GLIBCXX_FORCE_NEW") ? true : false);
485 static pool_type _S_pool(_S_tune);
490 template<typename _Tp, template <bool> class _PoolTp, bool _Thread>
491 struct __per_type_pool_base;
493 template<typename _Tp, template <bool> class _PoolTp>
494 struct __per_type_pool_base<_Tp, _PoolTp, false>
495 : public __per_type_pool<_Tp, _PoolTp, false>
497 using __per_type_pool<_Tp, _PoolTp, false>::_S_get_pool;
503 if (__builtin_expect(__init == false, false))
505 _S_get_pool()._M_initialize_once();
512 template<typename _Tp, template <bool> class _PoolTp>
513 struct __per_type_pool_base<_Tp, _PoolTp, true>
514 : public __per_type_pool<_Tp, _PoolTp, true>
516 using __per_type_pool<_Tp, _PoolTp, true>::_S_get_pool;
520 { _S_get_pool()._M_initialize_once(); }
526 if (__builtin_expect(__init == false, false))
528 if (__gthread_active_p())
530 // On some platforms, __gthread_once_t is an aggregate.
531 static __gthread_once_t __once = __GTHREAD_ONCE_INIT;
532 __gthread_once(&__once, _S_initialize);
535 // Double check initialization. May be necessary on some
536 // systems for proper construction when not compiling with
538 _S_get_pool()._M_initialize_once();
545 /// @brief Policy for individual __pool objects.
546 template<typename _Tp, template <bool> class _PoolTp, bool _Thread>
547 struct __per_type_pool_policy
548 : public __per_type_pool_base<_Tp, _PoolTp, _Thread>
550 template<typename _Tp1, template <bool> class _PoolTp1 = _PoolTp,
551 bool _Thread1 = _Thread>
553 { typedef __per_type_pool_policy<_Tp1, _PoolTp1, _Thread1> other; };
555 using __per_type_pool_base<_Tp, _PoolTp, _Thread>::_S_get_pool;
556 using __per_type_pool_base<_Tp, _PoolTp, _Thread>::_S_initialize_once;
560 /// @brief Base class for _Tp dependent member functions.
561 template<typename _Tp>
562 class __mt_alloc_base
565 typedef size_t size_type;
566 typedef ptrdiff_t difference_type;
567 typedef _Tp* pointer;
568 typedef const _Tp* const_pointer;
569 typedef _Tp& reference;
570 typedef const _Tp& const_reference;
571 typedef _Tp value_type;
574 address(reference __x) const
578 address(const_reference __x) const
582 max_size() const throw()
583 { return size_t(-1) / sizeof(_Tp); }
585 // _GLIBCXX_RESOLVE_LIB_DEFECTS
586 // 402. wrong new expression in [some_] allocator::construct
588 construct(pointer __p, const _Tp& __val)
589 { ::new(__p) _Tp(__val); }
592 destroy(pointer __p) { __p->~_Tp(); }
596 #define __thread_default true
598 #define __thread_default false
602 * @brief This is a fixed size (power of 2) allocator which - when
603 * compiled with thread support - will maintain one freelist per
604 * size per thread plus a "global" one. Steps are taken to limit
605 * the per thread freelist sizes (by returning excess back to
606 * the "global" list).
609 * http://gcc.gnu.org/onlinedocs/libstdc++/ext/mt_allocator.html
611 template<typename _Tp,
612 typename _Poolp = __common_pool_policy<__pool, __thread_default> >
613 class __mt_alloc : public __mt_alloc_base<_Tp>
616 typedef size_t size_type;
617 typedef ptrdiff_t difference_type;
618 typedef _Tp* pointer;
619 typedef const _Tp* const_pointer;
620 typedef _Tp& reference;
621 typedef const _Tp& const_reference;
622 typedef _Tp value_type;
623 typedef _Poolp __policy_type;
624 typedef typename _Poolp::pool_type __pool_type;
626 template<typename _Tp1, typename _Poolp1 = _Poolp>
629 typedef typename _Poolp1::template _M_rebind<_Tp1>::other pol_type;
630 typedef __mt_alloc<_Tp1, pol_type> other;
633 __mt_alloc() throw() { }
635 __mt_alloc(const __mt_alloc&) throw() { }
637 template<typename _Tp1, typename _Poolp1>
638 __mt_alloc(const __mt_alloc<_Tp1, _Poolp1>&) throw() { }
640 ~__mt_alloc() throw() { }
643 allocate(size_type __n, const void* = 0);
646 deallocate(pointer __p, size_type __n);
648 const __pool_base::_Tune
651 // Return a copy, not a reference, for external consumption.
652 return __policy_type::_S_get_pool()._M_get_options();
656 _M_set_options(__pool_base::_Tune __t)
657 { __policy_type::_S_get_pool()._M_set_options(__t); }
660 template<typename _Tp, typename _Poolp>
661 typename __mt_alloc<_Tp, _Poolp>::pointer
662 __mt_alloc<_Tp, _Poolp>::
663 allocate(size_type __n, const void*)
665 if (__builtin_expect(__n > this->max_size(), false))
666 std::__throw_bad_alloc();
668 __policy_type::_S_initialize_once();
670 // Requests larger than _M_max_bytes are handled by operator
671 // new/delete directly.
672 __pool_type& __pool = __policy_type::_S_get_pool();
673 const size_t __bytes = __n * sizeof(_Tp);
674 if (__pool._M_check_threshold(__bytes))
676 void* __ret = ::operator new(__bytes);
677 return static_cast<_Tp*>(__ret);
680 // Round up to power of 2 and figure out which bin to use.
681 const size_t __which = __pool._M_get_binmap(__bytes);
682 const size_t __thread_id = __pool._M_get_thread_id();
684 // Find out if we have blocks on our freelist. If so, go ahead
685 // and use them directly without having to lock anything.
687 typedef typename __pool_type::_Bin_record _Bin_record;
688 const _Bin_record& __bin = __pool._M_get_bin(__which);
689 if (__bin._M_first[__thread_id])
692 typedef typename __pool_type::_Block_record _Block_record;
693 _Block_record* __block = __bin._M_first[__thread_id];
694 __bin._M_first[__thread_id] = __block->_M_next;
696 __pool._M_adjust_freelist(__bin, __block, __thread_id);
697 __c = reinterpret_cast<char*>(__block) + __pool._M_get_align();
702 __c = __pool._M_reserve_block(__bytes, __thread_id);
704 return static_cast<_Tp*>(static_cast<void*>(__c));
707 template<typename _Tp, typename _Poolp>
709 __mt_alloc<_Tp, _Poolp>::
710 deallocate(pointer __p, size_type __n)
712 if (__builtin_expect(__p != 0, true))
714 // Requests larger than _M_max_bytes are handled by
715 // operators new/delete directly.
716 __pool_type& __pool = __policy_type::_S_get_pool();
717 const size_t __bytes = __n * sizeof(_Tp);
718 if (__pool._M_check_threshold(__bytes))
719 ::operator delete(__p);
721 __pool._M_reclaim_block(reinterpret_cast<char*>(__p), __bytes);
725 template<typename _Tp, typename _Poolp>
727 operator==(const __mt_alloc<_Tp, _Poolp>&, const __mt_alloc<_Tp, _Poolp>&)
730 template<typename _Tp, typename _Poolp>
732 operator!=(const __mt_alloc<_Tp, _Poolp>&, const __mt_alloc<_Tp, _Poolp>&)
735 #undef __thread_default
736 } // namespace __gnu_cxx