blob: e9d6ab6a8b39d6dd64bbe2563bee2cb54626296f [file] [log] [blame]
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001
2/* An object allocator for Python.
3
4 Here is an introduction to the layers of the Python memory architecture,
5 showing where the object allocator is actually used (layer +2), It is
6 called for every object allocation and deallocation (PyObject_New/Del),
7 unless the object-specific allocators implement a proprietary allocation
8 scheme (ex.: ints use a simple free list). This is also the place where
9 the cyclic garbage collector operates selectively on container objects.
10
11
12 Object-specific allocators
13 _____ ______ ______ ________
14 [ int ] [ dict ] [ list ] ... [ string ] Python core |
15+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
16 _______________________________ | |
17 [ Python's object allocator ] | |
18+2 | ####### Object memory ####### | <------ Internal buffers ------> |
19 ______________________________________________________________ |
20 [ Python's raw memory allocator (PyMem_ API) ] |
21+1 | <----- Python memory (under PyMem manager's control) ------> | |
22 __________________________________________________________________
23 [ Underlying general-purpose allocator (ex: C library malloc) ]
24 0 | <------ Virtual memory allocated for the python process -------> |
25
26 =========================================================================
27 _______________________________________________________________________
28 [ OS-specific Virtual Memory Manager (VMM) ]
29-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
30 __________________________________ __________________________________
31 [ ] [ ]
32-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
33
34*/
35/*==========================================================================*/
36
37/* A fast, special-purpose memory allocator for small blocks, to be used
38 on top of a general-purpose malloc -- heavily based on previous art. */
39
40/* Vladimir Marangozov -- August 2000 */
41
42/*
43 * "Memory management is where the rubber meets the road -- if we do the wrong
44 * thing at any level, the results will not be good. And if we don't make the
45 * levels work well together, we are in serious trouble." (1)
46 *
47 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
48 * "Dynamic Storage Allocation: A Survey and Critical Review",
49 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
50 */
51
52#ifndef Py_INTERNAL_PYMALLOC_H
53#define Py_INTERNAL_PYMALLOC_H
54
55/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
56
57/*==========================================================================*/
58
59/*
60 * Allocation strategy abstract:
61 *
62 * For small requests, the allocator sub-allocates <Big> blocks of memory.
63 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
64 * system's allocator.
65 *
66 * Small requests are grouped in size classes spaced 8 bytes apart, due
67 * to the required valid alignment of the returned address. Requests of
68 * a particular size are serviced from memory pools of 4K (one VMM page).
69 * Pools are fragmented on demand and contain free lists of blocks of one
70 * particular size class. In other words, there is a fixed-size allocator
71 * for each size class. Free pools are shared by the different allocators
72 * thus minimizing the space reserved for a particular size class.
73 *
74 * This allocation strategy is a variant of what is known as "simple
75 * segregated storage based on array of free lists". The main drawback of
76 * simple segregated storage is that we might end up with lot of reserved
77 * memory for the different free lists, which degenerate in time. To avoid
78 * this, we partition each free list in pools and we share dynamically the
79 * reserved space between all free lists. This technique is quite efficient
80 * for memory intensive programs which allocate mainly small-sized blocks.
81 *
82 * For small requests we have the following table:
83 *
84 * Request in bytes Size of allocated block Size class idx
85 * ----------------------------------------------------------------
86 * 1-8 8 0
87 * 9-16 16 1
88 * 17-24 24 2
89 * 25-32 32 3
90 * 33-40 40 4
91 * 41-48 48 5
92 * 49-56 56 6
93 * 57-64 64 7
94 * 65-72 72 8
95 * ... ... ...
96 * 497-504 504 62
97 * 505-512 512 63
98 *
99 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
100 * allocator.
101 */
102
103/*==========================================================================*/
104
105/*
106 * -- Main tunable settings section --
107 */
108
109/*
110 * Alignment of addresses returned to the user. 8-bytes alignment works
111 * on most current architectures (with 32-bit or 64-bit address busses).
112 * The alignment value is also used for grouping small requests in size
113 * classes spaced ALIGNMENT bytes apart.
114 *
115 * You shouldn't change this unless you know what you are doing.
116 */
117#define ALIGNMENT 8 /* must be 2^N */
118#define ALIGNMENT_SHIFT 3
119
120/* Return the number of bytes in size class I, as a uint. */
121#define INDEX2SIZE(I) (((unsigned int)(I) + 1) << ALIGNMENT_SHIFT)
122
123/*
124 * Max size threshold below which malloc requests are considered to be
125 * small enough in order to use preallocated memory pools. You can tune
126 * this value according to your application behaviour and memory needs.
127 *
128 * Note: a size threshold of 512 guarantees that newly created dictionaries
129 * will be allocated from preallocated memory pools on 64-bit.
130 *
131 * The following invariants must hold:
132 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
133 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
134 *
135 * Although not required, for better performance and space efficiency,
136 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
137 */
138#define SMALL_REQUEST_THRESHOLD 512
139#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
140
141#if NB_SMALL_SIZE_CLASSES > 64
142#error "NB_SMALL_SIZE_CLASSES should be less than 64"
143#endif /* NB_SMALL_SIZE_CLASSES > 64 */
144
145/*
146 * The system's VMM page size can be obtained on most unices with a
147 * getpagesize() call or deduced from various header files. To make
148 * things simpler, we assume that it is 4K, which is OK for most systems.
149 * It is probably better if this is the native page size, but it doesn't
150 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
151 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
152 * violation fault. 4K is apparently OK for all the platforms that python
153 * currently targets.
154 */
155#define SYSTEM_PAGE_SIZE (4 * 1024)
156#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
157
158/*
159 * Maximum amount of memory managed by the allocator for small requests.
160 */
161#ifdef WITH_MEMORY_LIMITS
162#ifndef SMALL_MEMORY_LIMIT
163#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
164#endif
165#endif
166
167/*
168 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
169 * on a page boundary. This is a reserved virtual address space for the
170 * current process (obtained through a malloc()/mmap() call). In no way this
171 * means that the memory arenas will be used entirely. A malloc(<Big>) is
172 * usually an address range reservation for <Big> bytes, unless all pages within
173 * this space are referenced subsequently. So malloc'ing big blocks and not
174 * using them does not mean "wasting memory". It's an addressable range
175 * wastage...
176 *
177 * Arenas are allocated with mmap() on systems supporting anonymous memory
178 * mappings to reduce heap fragmentation.
179 */
180#define ARENA_SIZE (256 << 10) /* 256KB */
181
182#ifdef WITH_MEMORY_LIMITS
183#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
184#endif
185
186/*
187 * Size of the pools used for small blocks. Should be a power of 2,
188 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
189 */
190#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
191#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
192
193/*
194 * -- End of tunable settings section --
195 */
196
197/*==========================================================================*/
198
199/*
200 * Locking
201 *
202 * To reduce lock contention, it would probably be better to refine the
203 * crude function locking with per size class locking. I'm not positive
204 * however, whether it's worth switching to such locking policy because
205 * of the performance penalty it might introduce.
206 *
207 * The following macros describe the simplest (should also be the fastest)
208 * lock object on a particular platform and the init/fini/lock/unlock
209 * operations on it. The locks defined here are not expected to be recursive
210 * because it is assumed that they will always be called in the order:
211 * INIT, [LOCK, UNLOCK]*, FINI.
212 */
213
214/*
215 * Python's threads are serialized, so object malloc locking is disabled.
216 */
217#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
218#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
219#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
220#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
221#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
222
223/* When you say memory, my mind reasons in terms of (pointers to) blocks */
224typedef uint8_t pyblock;
225
226/* Pool for small blocks. */
227struct pool_header {
228 union { pyblock *_padding;
229 unsigned int count; } ref; /* number of allocated blocks */
230 pyblock *freeblock; /* pool's free list head */
231 struct pool_header *nextpool; /* next pool of this size class */
232 struct pool_header *prevpool; /* previous pool "" */
233 unsigned int arenaindex; /* index into arenas of base adr */
234 unsigned int szidx; /* block size class index */
235 unsigned int nextoffset; /* bytes to virgin block */
236 unsigned int maxnextoffset; /* largest valid nextoffset */
237};
238
239typedef struct pool_header *poolp;
240
241/* Record keeping for arenas. */
242struct arena_object {
243 /* The address of the arena, as returned by malloc. Note that 0
244 * will never be returned by a successful malloc, and is used
245 * here to mark an arena_object that doesn't correspond to an
246 * allocated arena.
247 */
248 uintptr_t address;
249
250 /* Pool-aligned pointer to the next pool to be carved off. */
251 pyblock* pool_address;
252
253 /* The number of available pools in the arena: free pools + never-
254 * allocated pools.
255 */
256 unsigned int nfreepools;
257
258 /* The total number of pools in the arena, whether or not available. */
259 unsigned int ntotalpools;
260
261 /* Singly-linked list of available pools. */
262 struct pool_header* freepools;
263
264 /* Whenever this arena_object is not associated with an allocated
265 * arena, the nextarena member is used to link all unassociated
266 * arena_objects in the singly-linked `unused_arena_objects` list.
267 * The prevarena member is unused in this case.
268 *
269 * When this arena_object is associated with an allocated arena
270 * with at least one available pool, both members are used in the
271 * doubly-linked `usable_arenas` list, which is maintained in
272 * increasing order of `nfreepools` values.
273 *
274 * Else this arena_object is associated with an allocated arena
275 * all of whose pools are in use. `nextarena` and `prevarena`
276 * are both meaningless in this case.
277 */
278 struct arena_object* nextarena;
279 struct arena_object* prevarena;
280};
281
282#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
283
284#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
285
286/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
287#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
288
289/* Return total number of blocks in pool of size index I, as a uint. */
290#define NUMBLOCKS(I) \
291 ((unsigned int)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
292
293/*==========================================================================*/
294
295/*
296 * This malloc lock
297 */
298SIMPLELOCK_DECL(_malloc_lock)
299#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
300#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
301#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
302#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
303
304/*
305 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
306
307This is involved. For an index i, usedpools[i+i] is the header for a list of
308all partially used pools holding small blocks with "size class idx" i. So
309usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
31016, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
311
312Pools are carved off an arena's highwater mark (an arena_object's pool_address
313member) as needed. Once carved off, a pool is in one of three states forever
314after:
315
316used == partially used, neither empty nor full
317 At least one block in the pool is currently allocated, and at least one
318 block in the pool is not currently allocated (note this implies a pool
319 has room for at least two blocks).
320 This is a pool's initial state, as a pool is created only when malloc
321 needs space.
322 The pool holds blocks of a fixed size, and is in the circular list headed
323 at usedpools[i] (see above). It's linked to the other used pools of the
324 same size class via the pool_header's nextpool and prevpool members.
325 If all but one block is currently allocated, a malloc can cause a
326 transition to the full state. If all but one block is not currently
327 allocated, a free can cause a transition to the empty state.
328
329full == all the pool's blocks are currently allocated
330 On transition to full, a pool is unlinked from its usedpools[] list.
331 It's not linked to from anything then anymore, and its nextpool and
332 prevpool members are meaningless until it transitions back to used.
333 A free of a block in a full pool puts the pool back in the used state.
334 Then it's linked in at the front of the appropriate usedpools[] list, so
335 that the next allocation for its size class will reuse the freed block.
336
337empty == all the pool's blocks are currently available for allocation
338 On transition to empty, a pool is unlinked from its usedpools[] list,
339 and linked to the front of its arena_object's singly-linked freepools list,
340 via its nextpool member. The prevpool member has no meaning in this case.
341 Empty pools have no inherent size class: the next time a malloc finds
342 an empty list in usedpools[], it takes the first pool off of freepools.
343 If the size class needed happens to be the same as the size class the pool
344 last had, some pool initialization can be skipped.
345
346
347Block Management
348
349Blocks within pools are again carved out as needed. pool->freeblock points to
350the start of a singly-linked list of free blocks within the pool. When a
351block is freed, it's inserted at the front of its pool's freeblock list. Note
352that the available blocks in a pool are *not* linked all together when a pool
353is initialized. Instead only "the first two" (lowest addresses) blocks are
354set up, returning the first such block, and setting pool->freeblock to a
355one-block list holding the second such block. This is consistent with that
356pymalloc strives at all levels (arena, pool, and block) never to touch a piece
357of memory until it's actually needed.
358
359So long as a pool is in the used state, we're certain there *is* a block
360available for allocating, and pool->freeblock is not NULL. If pool->freeblock
361points to the end of the free list before we've carved the entire pool into
362blocks, that means we simply haven't yet gotten to one of the higher-address
363blocks. The offset from the pool_header to the start of "the next" virgin
364block is stored in the pool_header nextoffset member, and the largest value
365of nextoffset that makes sense is stored in the maxnextoffset member when a
366pool is initialized. All the blocks in a pool have been passed out at least
367once when and only when nextoffset > maxnextoffset.
368
369
370Major obscurity: While the usedpools vector is declared to have poolp
371entries, it doesn't really. It really contains two pointers per (conceptual)
372poolp entry, the nextpool and prevpool members of a pool_header. The
373excruciating initialization code below fools C so that
374
375 usedpool[i+i]
376
377"acts like" a genuine poolp, but only so long as you only reference its
378nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
379compensating for that a pool_header's nextpool and prevpool members
380immediately follow a pool_header's first two members:
381
382 union { block *_padding;
383 uint count; } ref;
384 block *freeblock;
385
386each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
387contains is a fudged-up pointer p such that *if* C believes it's a poolp
388pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
389circular list is empty).
390
391It's unclear why the usedpools setup is so convoluted. It could be to
392minimize the amount of cache required to hold this heavily-referenced table
393(which only *needs* the two interpool pointer members of a pool_header). OTOH,
394referencing code has to remember to "double the index" and doing so isn't
395free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
396on that C doesn't insert any padding anywhere in a pool_header at or before
397the prevpool member.
398**************************************************************************** */
399
400#define MAX_POOLS (2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8)
401
402/*==========================================================================
403Arena management.
404
405`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
406which may not be currently used (== they're arena_objects that aren't
407currently associated with an allocated arena). Note that arenas proper are
408separately malloc'ed.
409
410Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
411we do try to free() arenas, and use some mild heuristic strategies to increase
412the likelihood that arenas eventually can be freed.
413
414unused_arena_objects
415
416 This is a singly-linked list of the arena_objects that are currently not
417 being used (no arena is associated with them). Objects are taken off the
418 head of the list in new_arena(), and are pushed on the head of the list in
419 PyObject_Free() when the arena is empty. Key invariant: an arena_object
420 is on this list if and only if its .address member is 0.
421
422usable_arenas
423
424 This is a doubly-linked list of the arena_objects associated with arenas
425 that have pools available. These pools are either waiting to be reused,
426 or have not been used before. The list is sorted to have the most-
427 allocated arenas first (ascending order based on the nfreepools member).
428 This means that the next allocation will come from a heavily used arena,
429 which gives the nearly empty arenas a chance to be returned to the system.
430 In my unscientific tests this dramatically improved the number of arenas
431 that could be freed.
432
433Note that an arena_object associated with an arena all of whose pools are
434currently in use isn't on either list.
435*/
436
437/* How many arena_objects do we initially allocate?
438 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
439 * `arenas` vector.
440 */
441#define INITIAL_ARENA_OBJECTS 16
442
443#endif /* Py_INTERNAL_PYMALLOC_H */