pycore_obmalloc.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. #ifndef Py_INTERNAL_OBMALLOC_H
  2. #define Py_INTERNAL_OBMALLOC_H
  3. #ifdef __cplusplus
  4. extern "C" {
  5. #endif
  6. #ifndef Py_BUILD_CORE
  7. # error "this header requires Py_BUILD_CORE define"
  8. #endif
  9. typedef unsigned int pymem_uint; /* assuming >= 16 bits */
  10. #undef uint
  11. #define uint pymem_uint
  12. /* An object allocator for Python.
  13. Here is an introduction to the layers of the Python memory architecture,
  14. showing where the object allocator is actually used (layer +2), It is
  15. called for every object allocation and deallocation (PyObject_New/Del),
  16. unless the object-specific allocators implement a proprietary allocation
  17. scheme (ex.: ints use a simple free list). This is also the place where
  18. the cyclic garbage collector operates selectively on container objects.
  19. Object-specific allocators
  20. _____ ______ ______ ________
  21. [ int ] [ dict ] [ list ] ... [ string ] Python core |
  22. +3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
  23. _______________________________ | |
  24. [ Python's object allocator ] | |
  25. +2 | ####### Object memory ####### | <------ Internal buffers ------> |
  26. ______________________________________________________________ |
  27. [ Python's raw memory allocator (PyMem_ API) ] |
  28. +1 | <----- Python memory (under PyMem manager's control) ------> | |
  29. __________________________________________________________________
  30. [ Underlying general-purpose allocator (ex: C library malloc) ]
  31. 0 | <------ Virtual memory allocated for the python process -------> |
  32. =========================================================================
  33. _______________________________________________________________________
  34. [ OS-specific Virtual Memory Manager (VMM) ]
  35. -1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
  36. __________________________________ __________________________________
  37. [ ] [ ]
  38. -2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
  39. */
  40. /*==========================================================================*/
  41. /* A fast, special-purpose memory allocator for small blocks, to be used
  42. on top of a general-purpose malloc -- heavily based on previous art. */
  43. /* Vladimir Marangozov -- August 2000 */
  44. /*
  45. * "Memory management is where the rubber meets the road -- if we do the wrong
  46. * thing at any level, the results will not be good. And if we don't make the
  47. * levels work well together, we are in serious trouble." (1)
  48. *
  49. * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
  50. * "Dynamic Storage Allocation: A Survey and Critical Review",
  51. * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
  52. */
  53. /* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
  54. /*==========================================================================*/
  55. /*
  56. * Allocation strategy abstract:
  57. *
  58. * For small requests, the allocator sub-allocates <Big> blocks of memory.
  59. * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
  60. * system's allocator.
  61. *
  62. * Small requests are grouped in size classes spaced 8 bytes apart, due
  63. * to the required valid alignment of the returned address. Requests of
  64. * a particular size are serviced from memory pools of 4K (one VMM page).
  65. * Pools are fragmented on demand and contain free lists of blocks of one
  66. * particular size class. In other words, there is a fixed-size allocator
  67. * for each size class. Free pools are shared by the different allocators
  68. * thus minimizing the space reserved for a particular size class.
  69. *
  70. * This allocation strategy is a variant of what is known as "simple
  71. * segregated storage based on array of free lists". The main drawback of
  72. * simple segregated storage is that we might end up with lot of reserved
  73. * memory for the different free lists, which degenerate in time. To avoid
  74. * this, we partition each free list in pools and we share dynamically the
  75. * reserved space between all free lists. This technique is quite efficient
  76. * for memory intensive programs which allocate mainly small-sized blocks.
  77. *
  78. * For small requests we have the following table:
  79. *
  80. * Request in bytes Size of allocated block Size class idx
  81. * ----------------------------------------------------------------
  82. * 1-8 8 0
  83. * 9-16 16 1
  84. * 17-24 24 2
  85. * 25-32 32 3
  86. * 33-40 40 4
  87. * 41-48 48 5
  88. * 49-56 56 6
  89. * 57-64 64 7
  90. * 65-72 72 8
  91. * ... ... ...
  92. * 497-504 504 62
  93. * 505-512 512 63
  94. *
  95. * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
  96. * allocator.
  97. */
  98. /*==========================================================================*/
  99. /*
  100. * -- Main tunable settings section --
  101. */
  102. /*
  103. * Alignment of addresses returned to the user. 8-bytes alignment works
  104. * on most current architectures (with 32-bit or 64-bit address buses).
  105. * The alignment value is also used for grouping small requests in size
  106. * classes spaced ALIGNMENT bytes apart.
  107. *
  108. * You shouldn't change this unless you know what you are doing.
  109. */
  110. #if SIZEOF_VOID_P > 4
  111. #define ALIGNMENT 16 /* must be 2^N */
  112. #define ALIGNMENT_SHIFT 4
  113. #else
  114. #define ALIGNMENT 8 /* must be 2^N */
  115. #define ALIGNMENT_SHIFT 3
  116. #endif
  117. /* Return the number of bytes in size class I, as a uint. */
  118. #define INDEX2SIZE(I) (((pymem_uint)(I) + 1) << ALIGNMENT_SHIFT)
  119. /*
  120. * Max size threshold below which malloc requests are considered to be
  121. * small enough in order to use preallocated memory pools. You can tune
  122. * this value according to your application behaviour and memory needs.
  123. *
  124. * Note: a size threshold of 512 guarantees that newly created dictionaries
  125. * will be allocated from preallocated memory pools on 64-bit.
  126. *
  127. * The following invariants must hold:
  128. * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
  129. * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
  130. *
  131. * Although not required, for better performance and space efficiency,
  132. * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
  133. */
  134. #define SMALL_REQUEST_THRESHOLD 512
  135. #define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
  136. /*
  137. * The system's VMM page size can be obtained on most unices with a
  138. * getpagesize() call or deduced from various header files. To make
  139. * things simpler, we assume that it is 4K, which is OK for most systems.
  140. * It is probably better if this is the native page size, but it doesn't
  141. * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
  142. * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
  143. * violation fault. 4K is apparently OK for all the platforms that python
  144. * currently targets.
  145. */
  146. #define SYSTEM_PAGE_SIZE (4 * 1024)
  147. /*
  148. * Maximum amount of memory managed by the allocator for small requests.
  149. */
  150. #ifdef WITH_MEMORY_LIMITS
  151. #ifndef SMALL_MEMORY_LIMIT
  152. #define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
  153. #endif
  154. #endif
  155. #if !defined(WITH_PYMALLOC_RADIX_TREE)
  156. /* Use radix-tree to track arena memory regions, for address_in_range().
  157. * Enable by default since it allows larger pool sizes. Can be disabled
  158. * using -DWITH_PYMALLOC_RADIX_TREE=0 */
  159. #define WITH_PYMALLOC_RADIX_TREE 1
  160. #endif
  161. #if SIZEOF_VOID_P > 4
  162. /* on 64-bit platforms use larger pools and arenas if we can */
  163. #define USE_LARGE_ARENAS
  164. #if WITH_PYMALLOC_RADIX_TREE
  165. /* large pools only supported if radix-tree is enabled */
  166. #define USE_LARGE_POOLS
  167. #endif
  168. #endif
  169. /*
  170. * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
  171. * on a page boundary. This is a reserved virtual address space for the
  172. * current process (obtained through a malloc()/mmap() call). In no way this
  173. * means that the memory arenas will be used entirely. A malloc(<Big>) is
  174. * usually an address range reservation for <Big> bytes, unless all pages within
  175. * this space are referenced subsequently. So malloc'ing big blocks and not
  176. * using them does not mean "wasting memory". It's an addressable range
  177. * wastage...
  178. *
  179. * Arenas are allocated with mmap() on systems supporting anonymous memory
  180. * mappings to reduce heap fragmentation.
  181. */
  182. #ifdef USE_LARGE_ARENAS
  183. #define ARENA_BITS 20 /* 1 MiB */
  184. #else
  185. #define ARENA_BITS 18 /* 256 KiB */
  186. #endif
  187. #define ARENA_SIZE (1 << ARENA_BITS)
  188. #define ARENA_SIZE_MASK (ARENA_SIZE - 1)
  189. #ifdef WITH_MEMORY_LIMITS
  190. #define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
  191. #endif
  192. /*
  193. * Size of the pools used for small blocks. Must be a power of 2.
  194. */
  195. #ifdef USE_LARGE_POOLS
  196. #define POOL_BITS 14 /* 16 KiB */
  197. #else
  198. #define POOL_BITS 12 /* 4 KiB */
  199. #endif
  200. #define POOL_SIZE (1 << POOL_BITS)
  201. #define POOL_SIZE_MASK (POOL_SIZE - 1)
  202. #if !WITH_PYMALLOC_RADIX_TREE
  203. #if POOL_SIZE != SYSTEM_PAGE_SIZE
  204. # error "pool size must be equal to system page size"
  205. #endif
  206. #endif
  207. #define MAX_POOLS_IN_ARENA (ARENA_SIZE / POOL_SIZE)
  208. #if MAX_POOLS_IN_ARENA * POOL_SIZE != ARENA_SIZE
  209. # error "arena size not an exact multiple of pool size"
  210. #endif
  211. /*
  212. * -- End of tunable settings section --
  213. */
  214. /*==========================================================================*/
  215. /* When you say memory, my mind reasons in terms of (pointers to) blocks */
  216. typedef uint8_t pymem_block;
  217. /* Pool for small blocks. */
  218. struct pool_header {
  219. union { pymem_block *_padding;
  220. uint count; } ref; /* number of allocated blocks */
  221. pymem_block *freeblock; /* pool's free list head */
  222. struct pool_header *nextpool; /* next pool of this size class */
  223. struct pool_header *prevpool; /* previous pool "" */
  224. uint arenaindex; /* index into arenas of base adr */
  225. uint szidx; /* block size class index */
  226. uint nextoffset; /* bytes to virgin block */
  227. uint maxnextoffset; /* largest valid nextoffset */
  228. };
  229. typedef struct pool_header *poolp;
  230. /* Record keeping for arenas. */
  231. struct arena_object {
  232. /* The address of the arena, as returned by malloc. Note that 0
  233. * will never be returned by a successful malloc, and is used
  234. * here to mark an arena_object that doesn't correspond to an
  235. * allocated arena.
  236. */
  237. uintptr_t address;
  238. /* Pool-aligned pointer to the next pool to be carved off. */
  239. pymem_block* pool_address;
  240. /* The number of available pools in the arena: free pools + never-
  241. * allocated pools.
  242. */
  243. uint nfreepools;
  244. /* The total number of pools in the arena, whether or not available. */
  245. uint ntotalpools;
  246. /* Singly-linked list of available pools. */
  247. struct pool_header* freepools;
  248. /* Whenever this arena_object is not associated with an allocated
  249. * arena, the nextarena member is used to link all unassociated
  250. * arena_objects in the singly-linked `unused_arena_objects` list.
  251. * The prevarena member is unused in this case.
  252. *
  253. * When this arena_object is associated with an allocated arena
  254. * with at least one available pool, both members are used in the
  255. * doubly-linked `usable_arenas` list, which is maintained in
  256. * increasing order of `nfreepools` values.
  257. *
  258. * Else this arena_object is associated with an allocated arena
  259. * all of whose pools are in use. `nextarena` and `prevarena`
  260. * are both meaningless in this case.
  261. */
  262. struct arena_object* nextarena;
  263. struct arena_object* prevarena;
  264. };
  265. #define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
  266. #define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
  267. /* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
  268. #define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
  269. /* Return total number of blocks in pool of size index I, as a uint. */
  270. #define NUMBLOCKS(I) ((pymem_uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
  271. /*==========================================================================*/
  272. /*
  273. * Pool table -- headed, circular, doubly-linked lists of partially used pools.
  274. This is involved. For an index i, usedpools[i+i] is the header for a list of
  275. all partially used pools holding small blocks with "size class idx" i. So
  276. usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
  277. 16, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
  278. Pools are carved off an arena's highwater mark (an arena_object's pool_address
  279. member) as needed. Once carved off, a pool is in one of three states forever
  280. after:
  281. used == partially used, neither empty nor full
  282. At least one block in the pool is currently allocated, and at least one
  283. block in the pool is not currently allocated (note this implies a pool
  284. has room for at least two blocks).
  285. This is a pool's initial state, as a pool is created only when malloc
  286. needs space.
  287. The pool holds blocks of a fixed size, and is in the circular list headed
  288. at usedpools[i] (see above). It's linked to the other used pools of the
  289. same size class via the pool_header's nextpool and prevpool members.
  290. If all but one block is currently allocated, a malloc can cause a
  291. transition to the full state. If all but one block is not currently
  292. allocated, a free can cause a transition to the empty state.
  293. full == all the pool's blocks are currently allocated
  294. On transition to full, a pool is unlinked from its usedpools[] list.
  295. It's not linked to from anything then anymore, and its nextpool and
  296. prevpool members are meaningless until it transitions back to used.
  297. A free of a block in a full pool puts the pool back in the used state.
  298. Then it's linked in at the front of the appropriate usedpools[] list, so
  299. that the next allocation for its size class will reuse the freed block.
  300. empty == all the pool's blocks are currently available for allocation
  301. On transition to empty, a pool is unlinked from its usedpools[] list,
  302. and linked to the front of its arena_object's singly-linked freepools list,
  303. via its nextpool member. The prevpool member has no meaning in this case.
  304. Empty pools have no inherent size class: the next time a malloc finds
  305. an empty list in usedpools[], it takes the first pool off of freepools.
  306. If the size class needed happens to be the same as the size class the pool
  307. last had, some pool initialization can be skipped.
  308. Block Management
  309. Blocks within pools are again carved out as needed. pool->freeblock points to
  310. the start of a singly-linked list of free blocks within the pool. When a
  311. block is freed, it's inserted at the front of its pool's freeblock list. Note
  312. that the available blocks in a pool are *not* linked all together when a pool
  313. is initialized. Instead only "the first two" (lowest addresses) blocks are
  314. set up, returning the first such block, and setting pool->freeblock to a
  315. one-block list holding the second such block. This is consistent with that
  316. pymalloc strives at all levels (arena, pool, and block) never to touch a piece
  317. of memory until it's actually needed.
  318. So long as a pool is in the used state, we're certain there *is* a block
  319. available for allocating, and pool->freeblock is not NULL. If pool->freeblock
  320. points to the end of the free list before we've carved the entire pool into
  321. blocks, that means we simply haven't yet gotten to one of the higher-address
  322. blocks. The offset from the pool_header to the start of "the next" virgin
  323. block is stored in the pool_header nextoffset member, and the largest value
  324. of nextoffset that makes sense is stored in the maxnextoffset member when a
  325. pool is initialized. All the blocks in a pool have been passed out at least
  326. once when and only when nextoffset > maxnextoffset.
  327. Major obscurity: While the usedpools vector is declared to have poolp
  328. entries, it doesn't really. It really contains two pointers per (conceptual)
  329. poolp entry, the nextpool and prevpool members of a pool_header. The
  330. excruciating initialization code below fools C so that
  331. usedpool[i+i]
  332. "acts like" a genuine poolp, but only so long as you only reference its
  333. nextpool and prevpool members. The "- 2*sizeof(pymem_block *)" gibberish is
  334. compensating for that a pool_header's nextpool and prevpool members
  335. immediately follow a pool_header's first two members:
  336. union { pymem_block *_padding;
  337. uint count; } ref;
  338. pymem_block *freeblock;
  339. each of which consume sizeof(pymem_block *) bytes. So what usedpools[i+i] really
  340. contains is a fudged-up pointer p such that *if* C believes it's a poolp
  341. pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
  342. circular list is empty).
  343. It's unclear why the usedpools setup is so convoluted. It could be to
  344. minimize the amount of cache required to hold this heavily-referenced table
  345. (which only *needs* the two interpool pointer members of a pool_header). OTOH,
  346. referencing code has to remember to "double the index" and doing so isn't
  347. free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
  348. on that C doesn't insert any padding anywhere in a pool_header at or before
  349. the prevpool member.
  350. **************************************************************************** */
  351. #define OBMALLOC_USED_POOLS_SIZE (2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8)
  352. struct _obmalloc_pools {
  353. poolp used[OBMALLOC_USED_POOLS_SIZE];
  354. };
  355. /*==========================================================================
  356. Arena management.
  357. `arenas` is a vector of arena_objects. It contains maxarenas entries, some of
  358. which may not be currently used (== they're arena_objects that aren't
  359. currently associated with an allocated arena). Note that arenas proper are
  360. separately malloc'ed.
  361. Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
  362. we do try to free() arenas, and use some mild heuristic strategies to increase
  363. the likelihood that arenas eventually can be freed.
  364. unused_arena_objects
  365. This is a singly-linked list of the arena_objects that are currently not
  366. being used (no arena is associated with them). Objects are taken off the
  367. head of the list in new_arena(), and are pushed on the head of the list in
  368. PyObject_Free() when the arena is empty. Key invariant: an arena_object
  369. is on this list if and only if its .address member is 0.
  370. usable_arenas
  371. This is a doubly-linked list of the arena_objects associated with arenas
  372. that have pools available. These pools are either waiting to be reused,
  373. or have not been used before. The list is sorted to have the most-
  374. allocated arenas first (ascending order based on the nfreepools member).
  375. This means that the next allocation will come from a heavily used arena,
  376. which gives the nearly empty arenas a chance to be returned to the system.
  377. In my unscientific tests this dramatically improved the number of arenas
  378. that could be freed.
  379. Note that an arena_object associated with an arena all of whose pools are
  380. currently in use isn't on either list.
  381. Changed in Python 3.8: keeping usable_arenas sorted by number of free pools
  382. used to be done by one-at-a-time linear search when an arena's number of
  383. free pools changed. That could, overall, consume time quadratic in the
  384. number of arenas. That didn't really matter when there were only a few
  385. hundred arenas (typical!), but could be a timing disaster when there were
  386. hundreds of thousands. See bpo-37029.
  387. Now we have a vector of "search fingers" to eliminate the need to search:
  388. nfp2lasta[nfp] returns the last ("rightmost") arena in usable_arenas
  389. with nfp free pools. This is NULL if and only if there is no arena with
  390. nfp free pools in usable_arenas.
  391. */
  392. /* How many arena_objects do we initially allocate?
  393. * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
  394. * `arenas` vector.
  395. */
  396. #define INITIAL_ARENA_OBJECTS 16
  397. struct _obmalloc_mgmt {
  398. /* Array of objects used to track chunks of memory (arenas). */
  399. struct arena_object* arenas;
  400. /* Number of slots currently allocated in the `arenas` vector. */
  401. uint maxarenas;
  402. /* The head of the singly-linked, NULL-terminated list of available
  403. * arena_objects.
  404. */
  405. struct arena_object* unused_arena_objects;
  406. /* The head of the doubly-linked, NULL-terminated at each end, list of
  407. * arena_objects associated with arenas that have pools available.
  408. */
  409. struct arena_object* usable_arenas;
  410. /* nfp2lasta[nfp] is the last arena in usable_arenas with nfp free pools */
  411. struct arena_object* nfp2lasta[MAX_POOLS_IN_ARENA + 1];
  412. /* Number of arenas allocated that haven't been free()'d. */
  413. size_t narenas_currently_allocated;
  414. /* Total number of times malloc() called to allocate an arena. */
  415. size_t ntimes_arena_allocated;
  416. /* High water mark (max value ever seen) for narenas_currently_allocated. */
  417. size_t narenas_highwater;
  418. Py_ssize_t raw_allocated_blocks;
  419. };
  420. #if WITH_PYMALLOC_RADIX_TREE
  421. /*==========================================================================*/
  422. /* radix tree for tracking arena usage. If enabled, used to implement
  423. address_in_range().
  424. memory address bit allocation for keys
  425. 64-bit pointers, IGNORE_BITS=0 and 2^20 arena size:
  426. 15 -> MAP_TOP_BITS
  427. 15 -> MAP_MID_BITS
  428. 14 -> MAP_BOT_BITS
  429. 20 -> ideal aligned arena
  430. ----
  431. 64
  432. 64-bit pointers, IGNORE_BITS=16, and 2^20 arena size:
  433. 16 -> IGNORE_BITS
  434. 10 -> MAP_TOP_BITS
  435. 10 -> MAP_MID_BITS
  436. 8 -> MAP_BOT_BITS
  437. 20 -> ideal aligned arena
  438. ----
  439. 64
  440. 32-bit pointers and 2^18 arena size:
  441. 14 -> MAP_BOT_BITS
  442. 18 -> ideal aligned arena
  443. ----
  444. 32
  445. */
  446. #if SIZEOF_VOID_P == 8
  447. /* number of bits in a pointer */
  448. #define POINTER_BITS 64
  449. /* High bits of memory addresses that will be ignored when indexing into the
  450. * radix tree. Setting this to zero is the safe default. For most 64-bit
  451. * machines, setting this to 16 would be safe. The kernel would not give
  452. * user-space virtual memory addresses that have significant information in
  453. * those high bits. The main advantage to setting IGNORE_BITS > 0 is that less
  454. * virtual memory will be used for the top and middle radix tree arrays. Those
  455. * arrays are allocated in the BSS segment and so will typically consume real
  456. * memory only if actually accessed.
  457. */
  458. #define IGNORE_BITS 0
  459. /* use the top and mid layers of the radix tree */
  460. #define USE_INTERIOR_NODES
  461. #elif SIZEOF_VOID_P == 4
  462. #define POINTER_BITS 32
  463. #define IGNORE_BITS 0
  464. #else
  465. /* Currently this code works for 64-bit or 32-bit pointers only. */
  466. #error "obmalloc radix tree requires 64-bit or 32-bit pointers."
  467. #endif /* SIZEOF_VOID_P */
  468. /* arena_coverage_t members require this to be true */
  469. #if ARENA_BITS >= 32
  470. # error "arena size must be < 2^32"
  471. #endif
  472. /* the lower bits of the address that are not ignored */
  473. #define ADDRESS_BITS (POINTER_BITS - IGNORE_BITS)
  474. #ifdef USE_INTERIOR_NODES
  475. /* number of bits used for MAP_TOP and MAP_MID nodes */
  476. #define INTERIOR_BITS ((ADDRESS_BITS - ARENA_BITS + 2) / 3)
  477. #else
  478. #define INTERIOR_BITS 0
  479. #endif
  480. #define MAP_TOP_BITS INTERIOR_BITS
  481. #define MAP_TOP_LENGTH (1 << MAP_TOP_BITS)
  482. #define MAP_TOP_MASK (MAP_TOP_LENGTH - 1)
  483. #define MAP_MID_BITS INTERIOR_BITS
  484. #define MAP_MID_LENGTH (1 << MAP_MID_BITS)
  485. #define MAP_MID_MASK (MAP_MID_LENGTH - 1)
  486. #define MAP_BOT_BITS (ADDRESS_BITS - ARENA_BITS - 2*INTERIOR_BITS)
  487. #define MAP_BOT_LENGTH (1 << MAP_BOT_BITS)
  488. #define MAP_BOT_MASK (MAP_BOT_LENGTH - 1)
  489. #define MAP_BOT_SHIFT ARENA_BITS
  490. #define MAP_MID_SHIFT (MAP_BOT_BITS + MAP_BOT_SHIFT)
  491. #define MAP_TOP_SHIFT (MAP_MID_BITS + MAP_MID_SHIFT)
  492. #define AS_UINT(p) ((uintptr_t)(p))
  493. #define MAP_BOT_INDEX(p) ((AS_UINT(p) >> MAP_BOT_SHIFT) & MAP_BOT_MASK)
  494. #define MAP_MID_INDEX(p) ((AS_UINT(p) >> MAP_MID_SHIFT) & MAP_MID_MASK)
  495. #define MAP_TOP_INDEX(p) ((AS_UINT(p) >> MAP_TOP_SHIFT) & MAP_TOP_MASK)
  496. #if IGNORE_BITS > 0
  497. /* Return the ignored part of the pointer address. Those bits should be same
  498. * for all valid pointers if IGNORE_BITS is set correctly.
  499. */
  500. #define HIGH_BITS(p) (AS_UINT(p) >> ADDRESS_BITS)
  501. #else
  502. #define HIGH_BITS(p) 0
  503. #endif
  504. /* This is the leaf of the radix tree. See arena_map_mark_used() for the
  505. * meaning of these members. */
  506. typedef struct {
  507. int32_t tail_hi;
  508. int32_t tail_lo;
  509. } arena_coverage_t;
  510. typedef struct arena_map_bot {
  511. /* The members tail_hi and tail_lo are accessed together. So, it
  512. * better to have them as an array of structs, rather than two
  513. * arrays.
  514. */
  515. arena_coverage_t arenas[MAP_BOT_LENGTH];
  516. } arena_map_bot_t;
  517. #ifdef USE_INTERIOR_NODES
  518. typedef struct arena_map_mid {
  519. struct arena_map_bot *ptrs[MAP_MID_LENGTH];
  520. } arena_map_mid_t;
  521. typedef struct arena_map_top {
  522. struct arena_map_mid *ptrs[MAP_TOP_LENGTH];
  523. } arena_map_top_t;
  524. #endif
  525. struct _obmalloc_usage {
  526. /* The root of radix tree. Note that by initializing like this, the memory
  527. * should be in the BSS. The OS will only memory map pages as the MAP_MID
  528. * nodes get used (OS pages are demand loaded as needed).
  529. */
  530. #ifdef USE_INTERIOR_NODES
  531. arena_map_top_t arena_map_root;
  532. /* accounting for number of used interior nodes */
  533. int arena_map_mid_count;
  534. int arena_map_bot_count;
  535. #else
  536. arena_map_bot_t arena_map_root;
  537. #endif
  538. };
  539. #endif /* WITH_PYMALLOC_RADIX_TREE */
  540. struct _obmalloc_global_state {
  541. int dump_debug_stats;
  542. Py_ssize_t interpreter_leaks;
  543. };
  544. struct _obmalloc_state {
  545. struct _obmalloc_pools pools;
  546. struct _obmalloc_mgmt mgmt;
  547. #if WITH_PYMALLOC_RADIX_TREE
  548. struct _obmalloc_usage usage;
  549. #endif
  550. };
  551. #undef uint
  552. /* Allocate memory directly from the O/S virtual memory system,
  553. * where supported. Otherwise fallback on malloc */
  554. void *_PyObject_VirtualAlloc(size_t size);
  555. void _PyObject_VirtualFree(void *, size_t size);
  556. /* This function returns the number of allocated memory blocks, regardless of size */
  557. extern Py_ssize_t _Py_GetGlobalAllocatedBlocks(void);
  558. #define _Py_GetAllocatedBlocks() \
  559. _Py_GetGlobalAllocatedBlocks()
  560. extern Py_ssize_t _PyInterpreterState_GetAllocatedBlocks(PyInterpreterState *);
  561. extern void _PyInterpreterState_FinalizeAllocatedBlocks(PyInterpreterState *);
  562. #ifdef WITH_PYMALLOC
  563. // Export the symbol for the 3rd party guppy3 project
  564. PyAPI_FUNC(int) _PyObject_DebugMallocStats(FILE *out);
  565. #endif
  566. #ifdef __cplusplus
  567. }
  568. #endif
  569. #endif // !Py_INTERNAL_OBMALLOC_H