1 /* sl_malloc.c - malloc routines using a per-thread slab */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2003-2010 The OpenLDAP Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted only as authorized by the OpenLDAP
12 * A copy of this license is available in the file LICENSE in the
13 * top-level directory of the distribution or, alternatively, at
14 * <http://www.OpenLDAP.org/license.html>.
20 #include <ac/string.h>
25 * This allocator returns temporary memory from a slab in a given memory
26 * context, aligned on a 2-int boundary. It cannot be used for data
27 * which will outlive the task allocating it.
29 * A new memory context attaches to the creator's thread context, if any.
30 * Threads cannot use other threads' memory contexts; there are no locks.
32 * The caller of slap_sl_malloc, usually a thread pool task, must
33 * slap_sl_free the memory before finishing: New tasks reuse the context
34 * and normally reset it, reclaiming memory left over from last task.
36 * The allocator helps memory fragmentation, speed and memory leaks.
37 * It is not (yet) reliable as a garbage collector:
39 * It falls back to context NULL - plain ber_memalloc() - when the
40 * context's slab is full. A reset does not reclaim such memory.
41 * Conversely, free/realloc of data not from the given context assumes
42 * context NULL. The data must not belong to another memory context.
44 * Code which has lost track of the current memory context can try
45 * slap_sl_context() or ch_malloc.c:ch_free/ch_realloc().
47 * Allocations cannot yet return failure. Like ch_malloc, they succeed
48 * or abort slapd. This will change, do fix code which assumes success.
52 * The stack-based allocator stores (ber_len_t)sizeof(head+block) at
53 * the head and tail of each allocated block. The tail length of a freed
54 * block is ORed with 1 to mark it free. Freed blocks are only reclaimed
55 * from the last block forward. This is fast, but when a block is never
56 * freed, older blocks will not be reclaimed until the slab is reset...
59 #ifdef SLAP_NO_SL_MALLOC /* Useful with memory debuggers like Valgrind */
60 enum { No_sl_malloc = 1 };
62 enum { No_sl_malloc = 0 };
66 Align = sizeof(ber_len_t) > 2*sizeof(int)
67 ? sizeof(ber_len_t) : 2*sizeof(int),
68 Align_log2 = 1 + (Align>2) + (Align>4) + (Align>8) + (Align>16),
69 order_start = Align_log2 - 1,
73 static struct slab_object * slap_replenish_sopool(struct slab_heap* sh);
75 static void print_slheap(int level, void *ctx);
78 /* Keep memory context in a thread-local var, or in a global when no threads */
80 static struct slab_heap *slheap;
81 # define SET_MEMCTX(thrctx, memctx, sfree) ((void) (slheap = (memctx)))
82 # define GET_MEMCTX(thrctx, memctxp) (*(memctxp) = slheap))
84 # define memctx_key ((void *) slap_sl_mem_init)
85 # define SET_MEMCTX(thrctx, memctx, kfree) \
86 ldap_pvt_thread_pool_setkey(thrctx,memctx_key, memctx,kfree, NULL,NULL)
87 # define GET_MEMCTX(thrctx, memctxp) \
88 ((void) (*(memctxp) = NULL), \
89 (void) ldap_pvt_thread_pool_getkey(thrctx,memctx_key, memctxp,NULL), \
91 #endif /* NO_THREADS */
94 /* Destroy the context, or if key==NULL clean it up for reuse. */
101 struct slab_heap *sh = data;
102 struct slab_object *so;
106 for (i = 0; i <= sh->sh_maxorder - order_start; i++) {
107 so = LDAP_LIST_FIRST(&sh->sh_free[i]);
109 struct slab_object *so_tmp = so;
110 so = LDAP_LIST_NEXT(so, so_link);
111 LDAP_LIST_INSERT_HEAD(&sh->sh_sopool, so_tmp, so_link);
113 ch_free(sh->sh_map[i]);
115 ch_free(sh->sh_free);
118 so = LDAP_LIST_FIRST(&sh->sh_sopool);
120 struct slab_object *so_tmp = so;
121 so = LDAP_LIST_NEXT(so, so_link);
122 if (!so_tmp->so_blockhead) {
123 LDAP_LIST_REMOVE(so_tmp, so_link);
126 so = LDAP_LIST_FIRST(&sh->sh_sopool);
128 struct slab_object *so_tmp = so;
129 so = LDAP_LIST_NEXT(so, so_link);
135 ber_memfree_x(sh->sh_base, NULL);
136 ber_memfree_x(sh, NULL);
140 BerMemoryFunctions slap_sl_mfuncs =
141 { slap_sl_malloc, slap_sl_calloc, slap_sl_realloc, slap_sl_free };
146 assert( Align == 1 << Align_log2 );
147 /* Adding head+tail preserves alignment */
148 assert( 2*sizeof(ber_len_t) % Align == 0 );
150 ber_set_option( NULL, LBER_OPT_MEMORY_FNS, &slap_sl_mfuncs );
153 /* Create, reset or just return the memory context of the current thread. */
163 struct slab_heap *sh;
164 ber_len_t size_shift;
165 struct slab_object *so;
167 sh = GET_MEMCTX(thrctx, &memctx);
171 /* round up to doubleword boundary */
172 size = (size + Align-1) & -Align;
175 sh = ch_malloc(sizeof(struct slab_heap));
176 sh->sh_base = ch_malloc(size);
177 SET_MEMCTX(thrctx, sh, slap_sl_mem_destroy);
179 slap_sl_mem_destroy(NULL, sh);
180 if ( size > (char *)sh->sh_end - (char *)sh->sh_base ) {
183 newptr = ch_realloc( sh->sh_base, size );
184 if ( newptr == NULL ) return NULL;
185 sh->sh_base = newptr;
188 sh->sh_end = (char *) sh->sh_base + size;
190 sh->sh_stack = stack;
192 /* insert dummy len */
194 ber_len_t *i = sh->sh_base;
199 int i, order = -1, order_end = -1;
201 size_shift = size - 1;
204 } while (size_shift >>= 1);
205 order = order_end - order_start + 1;
206 sh->sh_maxorder = order_end;
208 sh->sh_free = (struct sh_freelist *)
209 ch_malloc(order * sizeof(struct sh_freelist));
210 for (i = 0; i < order; i++) {
211 LDAP_LIST_INIT(&sh->sh_free[i]);
214 LDAP_LIST_INIT(&sh->sh_sopool);
216 if (LDAP_LIST_EMPTY(&sh->sh_sopool)) {
217 slap_replenish_sopool(sh);
219 so = LDAP_LIST_FIRST(&sh->sh_sopool);
220 LDAP_LIST_REMOVE(so, so_link);
221 so->so_ptr = sh->sh_base;
223 LDAP_LIST_INSERT_HEAD(&sh->sh_free[order-1], so, so_link);
225 sh->sh_map = (unsigned char **)
226 ch_malloc(order * sizeof(unsigned char *));
227 for (i = 0; i < order; i++) {
228 int shiftamt = order_start + 1 + i;
229 int nummaps = size >> shiftamt;
232 if (!nummaps) nummaps = 1;
233 sh->sh_map[i] = (unsigned char *) ch_malloc(nummaps);
234 memset(sh->sh_map[i], 0, nummaps);
241 * Separate memory context from thread context. Future users must
242 * know the context, since ch_free/slap_sl_context() cannot find it.
250 SET_MEMCTX(thrctx, NULL, 0);
259 struct slab_heap *sh = ctx;
260 ber_len_t *ptr, *newptr;
262 /* ber_set_option calls us like this */
263 if (No_sl_malloc || !ctx) {
264 newptr = ber_memalloc_x( size, NULL );
265 if ( newptr ) return newptr;
266 Debug(LDAP_DEBUG_ANY, "slap_sl_malloc of %lu bytes failed\n",
267 (unsigned long) size, 0, 0);
269 exit( EXIT_FAILURE );
272 /* round up to doubleword boundary, plus space for len at head and tail */
273 size = (size + 2*sizeof(ber_len_t) + Align-1) & -Align;
276 if (size < (ber_len_t) ((char *) sh->sh_end - (char *) sh->sh_last)) {
277 newptr = sh->sh_last;
278 sh->sh_last = (char *) sh->sh_last + size;
279 size -= sizeof(ber_len_t);
281 ((ber_len_t *) sh->sh_last)[-1] = size;
282 return( (void *)newptr );
285 size -= 2*sizeof(ber_len_t);
288 struct slab_object *so_new, *so_left, *so_right;
289 ber_len_t size_shift;
291 int i, j, order = -1;
293 size_shift = size - 1;
296 } while (size_shift >>= 1);
298 size -= sizeof(ber_len_t);
300 for (i = order; i <= sh->sh_maxorder &&
301 LDAP_LIST_EMPTY(&sh->sh_free[i-order_start]); i++);
304 so_new = LDAP_LIST_FIRST(&sh->sh_free[i-order_start]);
305 LDAP_LIST_REMOVE(so_new, so_link);
306 ptr = so_new->so_ptr;
307 diff = (unsigned long)((char*)ptr -
308 (char*)sh->sh_base) >> (order + 1);
309 sh->sh_map[order-order_start][diff>>3] |= (1 << (diff & 0x7));
311 LDAP_LIST_INSERT_HEAD(&sh->sh_sopool, so_new, so_link);
313 } else if (i <= sh->sh_maxorder) {
314 for (j = i; j > order; j--) {
315 so_left = LDAP_LIST_FIRST(&sh->sh_free[j-order_start]);
316 LDAP_LIST_REMOVE(so_left, so_link);
317 if (LDAP_LIST_EMPTY(&sh->sh_sopool)) {
318 slap_replenish_sopool(sh);
320 so_right = LDAP_LIST_FIRST(&sh->sh_sopool);
321 LDAP_LIST_REMOVE(so_right, so_link);
322 so_right->so_ptr = (void *)((char *)so_left->so_ptr + (1 << j));
323 if (j == order + 1) {
324 ptr = so_left->so_ptr;
325 diff = (unsigned long)((char*)ptr -
326 (char*)sh->sh_base) >> (order+1);
327 sh->sh_map[order-order_start][diff>>3] |=
330 LDAP_LIST_INSERT_HEAD(
331 &sh->sh_free[j-1-order_start], so_right, so_link);
332 LDAP_LIST_INSERT_HEAD(&sh->sh_sopool, so_left, so_link);
335 LDAP_LIST_INSERT_HEAD(
336 &sh->sh_free[j-1-order_start], so_right, so_link);
337 LDAP_LIST_INSERT_HEAD(
338 &sh->sh_free[j-1-order_start], so_left, so_link);
342 /* FIXME: missing return; guessing we failed... */
345 Debug(LDAP_DEBUG_TRACE,
346 "slap_sl_malloc of %lu bytes failed, using ch_malloc\n",
347 (unsigned long) size, 0, 0);
348 return ch_malloc(size);
351 #define LIM_SQRT(t) /* some value < sqrt(max value of unsigned type t) */ \
352 ((0UL|(t)-1) >>31>>31 > 1 ? ((t)1 <<32) - 1 : \
353 (0UL|(t)-1) >>31 ? 65535U : (0UL|(t)-1) >>15 ? 255U : 15U)
356 slap_sl_calloc( ber_len_t n, ber_len_t size, void *ctx )
359 ber_len_t total = n * size;
361 /* The sqrt test is a slight optimization: often avoids the division */
362 if ((n | size) <= LIM_SQRT(ber_len_t) || n == 0 || total/n == size) {
363 newptr = slap_sl_malloc( total, ctx );
364 memset( newptr, 0, n*size );
366 Debug(LDAP_DEBUG_ANY, "slap_sl_calloc(%lu,%lu) out of range\n",
367 (unsigned long) n, (unsigned long) size, 0);
375 slap_sl_realloc(void *ptr, ber_len_t size, void *ctx)
377 struct slab_heap *sh = ctx;
378 ber_len_t oldsize, *p = (ber_len_t *) ptr;
382 return slap_sl_malloc(size, ctx);
384 /* Not our memory? */
385 if (No_sl_malloc || !sh || ptr < sh->sh_base || ptr >= sh->sh_end) {
386 /* Like ch_realloc(), except not trying a new context */
387 newptr = ber_memrealloc_x(ptr, size, NULL);
391 Debug(LDAP_DEBUG_ANY, "slap_sl_realloc of %lu bytes failed\n",
392 (unsigned long) size, 0, 0);
394 exit( EXIT_FAILURE );
398 slap_sl_free(ptr, ctx);
405 /* Round up to doubleword boundary, add room for head */
406 size = ((size + Align-1) & -Align) + sizeof( ber_len_t );
410 /* Never shrink blocks */
411 if (size <= oldsize) {
414 /* If reallocing the last block, try to grow it */
415 } else if ((char *) ptr + oldsize == sh->sh_last) {
416 if (size < (char *) sh->sh_end - (char *) ptr) {
417 sh->sh_last = (char *) ptr + size;
419 p[size/sizeof(ber_len_t)] = size;
423 /* Nowhere to grow, need to alloc and copy */
425 /* Slight optimization of the final realloc variant */
426 size -= sizeof(ber_len_t);
427 oldsize -= sizeof(ber_len_t);
428 newptr = slap_sl_malloc(size, ctx);
429 AC_MEMCPY(newptr, ptr, oldsize);
430 /* Not last block, can just mark old region as free */
431 p[p[0]/sizeof(ber_len_t)] |= 1;
435 size -= sizeof(ber_len_t);
436 oldsize -= sizeof(ber_len_t);
438 } else if (oldsize > size) {
442 newptr = slap_sl_malloc(size, ctx);
443 AC_MEMCPY(newptr, ptr, oldsize);
444 slap_sl_free(ptr, ctx);
449 slap_sl_free(void *ptr, void *ctx)
451 struct slab_heap *sh = ctx;
453 ber_len_t *p = (ber_len_t *)ptr, *tmpp;
458 if (No_sl_malloc || !sh || ptr < sh->sh_base || ptr >= sh->sh_end) {
459 ber_memfree_x(ptr, NULL);
461 } else if (sh->sh_stack) {
463 p = (ber_len_t *) ((char *) ptr + size);
466 /* reclaim free space off tail */
467 if (sh->sh_last == p) {
469 p = (ber_len_t *) ((char *) p - size + 1) - 1;
476 int size_shift, order_size;
477 struct slab_object *so;
479 int i, inserted = 0, order = -1;
482 size_shift = size + sizeof(ber_len_t) - 1;
485 } while (size_shift >>= 1);
487 for (i = order, tmpp = p; i <= sh->sh_maxorder; i++) {
488 order_size = 1 << (i+1);
489 diff = (unsigned long)((char*)tmpp - (char*)sh->sh_base) >> (i+1);
490 sh->sh_map[i-order_start][diff>>3] &= (~(1 << (diff & 0x7)));
491 if (diff == ((diff>>1)<<1)) {
492 if (!(sh->sh_map[i-order_start][(diff+1)>>3] &
493 (1<<((diff+1)&0x7)))) {
494 so = LDAP_LIST_FIRST(&sh->sh_free[i-order_start]);
496 if ((char*)so->so_ptr == (char*)tmpp) {
497 LDAP_LIST_REMOVE( so, so_link );
498 } else if ((char*)so->so_ptr ==
499 (char*)tmpp + order_size) {
500 LDAP_LIST_REMOVE(so, so_link);
503 so = LDAP_LIST_NEXT(so, so_link);
506 if (i < sh->sh_maxorder) {
509 LDAP_LIST_INSERT_HEAD(&sh->sh_free[i-order_start+1],
514 if (LDAP_LIST_EMPTY(&sh->sh_sopool)) {
515 slap_replenish_sopool(sh);
517 so = LDAP_LIST_FIRST(&sh->sh_sopool);
518 LDAP_LIST_REMOVE(so, so_link);
520 LDAP_LIST_INSERT_HEAD(&sh->sh_free[i-order_start],
524 Debug(LDAP_DEBUG_TRACE, "slap_sl_free: "
525 "free object not found while bit is clear.\n",
532 if (LDAP_LIST_EMPTY(&sh->sh_sopool)) {
533 slap_replenish_sopool(sh);
535 so = LDAP_LIST_FIRST(&sh->sh_sopool);
536 LDAP_LIST_REMOVE(so, so_link);
538 LDAP_LIST_INSERT_HEAD(&sh->sh_free[i-order_start],
544 if (!(sh->sh_map[i-order_start][(diff-1)>>3] &
545 (1<<((diff-1)&0x7)))) {
546 so = LDAP_LIST_FIRST(&sh->sh_free[i-order_start]);
548 if ((char*)so->so_ptr == (char*)tmpp) {
549 LDAP_LIST_REMOVE(so, so_link);
550 } else if ((char*)tmpp == (char *)so->so_ptr + order_size) {
551 LDAP_LIST_REMOVE(so, so_link);
555 so = LDAP_LIST_NEXT(so, so_link);
558 if (i < sh->sh_maxorder) {
560 LDAP_LIST_INSERT_HEAD(&sh->sh_free[i-order_start+1], so, so_link);
564 if (LDAP_LIST_EMPTY(&sh->sh_sopool)) {
565 slap_replenish_sopool(sh);
567 so = LDAP_LIST_FIRST(&sh->sh_sopool);
568 LDAP_LIST_REMOVE(so, so_link);
570 LDAP_LIST_INSERT_HEAD(&sh->sh_free[i-order_start],
574 Debug(LDAP_DEBUG_TRACE, "slap_sl_free: "
575 "free object not found while bit is clear.\n",
582 if (LDAP_LIST_EMPTY(&sh->sh_sopool)) {
583 slap_replenish_sopool(sh);
585 so = LDAP_LIST_FIRST(&sh->sh_sopool);
586 LDAP_LIST_REMOVE(so, so_link);
588 LDAP_LIST_INSERT_HEAD(&sh->sh_free[i-order_start],
599 * Return the memory context of the current thread if the given block of
600 * memory belongs to it, otherwise return NULL.
603 slap_sl_context( void *ptr )
606 struct slab_heap *sh;
608 if ( slapMode & SLAP_TOOL_MODE ) return NULL;
610 sh = GET_MEMCTX(ldap_pvt_thread_pool_context(), &memctx);
611 if (sh && ptr >= sh->sh_base && ptr <= sh->sh_end) {
617 static struct slab_object *
618 slap_replenish_sopool(
622 struct slab_object *so_block;
625 so_block = (struct slab_object *)ch_malloc(
626 SLAP_SLAB_SOBLOCK * sizeof(struct slab_object));
628 if ( so_block == NULL ) {
632 so_block[0].so_blockhead = 1;
633 LDAP_LIST_INSERT_HEAD(&sh->sh_sopool, &so_block[0], so_link);
634 for (i = 1; i < SLAP_SLAB_SOBLOCK; i++) {
635 so_block[i].so_blockhead = 0;
636 LDAP_LIST_INSERT_HEAD(&sh->sh_sopool, &so_block[i], so_link );
644 print_slheap(int level, void *ctx)
646 struct slab_heap *sh = ctx;
647 struct slab_object *so;
651 Debug(level, "NULL memctx\n", 0, 0, 0);
655 Debug(level, "sh->sh_maxorder=%d\n", sh->sh_maxorder, 0, 0);
657 for (i = order_start; i <= sh->sh_maxorder; i++) {
659 Debug(level, "order=%d\n", i, 0, 0);
660 for (j = 0; j < (1<<(sh->sh_maxorder-i))/8; j++) {
661 Debug(level, "%02x ", sh->sh_map[i-order_start][j], 0, 0);
665 Debug(level, "%02x ", sh->sh_map[i-order_start][0], 0, 0);
667 Debug(level, "\n", 0, 0, 0);
668 Debug(level, "free list:\n", 0, 0, 0);
669 so = LDAP_LIST_FIRST(&sh->sh_free[i-order_start]);
671 Debug(level, "%p\n", so->so_ptr, 0, 0);
672 so = LDAP_LIST_NEXT(so, so_link);