1 /* sl_malloc.c - malloc routines using a per-thread slab */
4 * Copyright 2003 The OpenLDAP Foundation, All Rights Reserved.
5 * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
11 #include <ac/string.h>
27 struct slab_heap *sh = data;
33 BER_MEMALLOC_FN sl_malloc;
34 BER_MEMCALLOC_FN sl_calloc;
35 BER_MEMREALLOC_FN sl_realloc;
36 BER_MEMFREE_FN sl_free;
38 static BerMemoryFunctions sl_bmf =
39 { sl_malloc, sl_calloc, sl_realloc, sl_free };
44 ber_set_option( NULL, LBER_OPT_MEMORY_FNS, &sl_bmf );
53 struct slab_heap *sh = NULL;
54 int pad = 2*sizeof(int)-1;
56 ldap_pvt_thread_pool_getkey( ctx, sl_mem_init, (void **)&sh, NULL );
58 /* round up to doubleword boundary */
63 sh = ch_malloc( sizeof(struct slab_heap) );
64 sh->h_base = ch_malloc( size );
65 ldap_pvt_thread_pool_setkey( ctx, sl_mem_init, (void *)sh, sl_mem_destroy );
66 } else if ( size > sh->h_end - sh->h_base ) {
67 sh->h_base = ch_realloc( sh->h_base, size );
69 sh->h_last = sh->h_base;
70 sh->h_end = sh->h_base + size;
80 struct slab_heap *sh = ctx;
81 int pad = 2*sizeof(int)-1;
84 /* ber_set_option calls us like this */
85 if (!ctx) return ber_memalloc_x( size, NULL );
87 /* round up to doubleword boundary */
88 size += pad + sizeof( ber_len_t );
91 if (sh->h_last + size >= sh->h_end ) {
93 LDAP_LOG( OPERATION, ERR,
94 "sl_malloc: allocation of %lu bytes failed\n", (long)size, 0,0 );
96 Debug( LDAP_DEBUG_ANY, "sl_malloc of %lu bytes failed\n",
100 exit( EXIT_FAILURE );
103 *new++ = size - sizeof(ber_len_t);
106 return( (void *)new );
110 sl_calloc( ber_len_t n, ber_len_t size, void *ctx )
114 new = sl_malloc( n*size, ctx );
116 memset( new, 0, n*size );
122 sl_realloc( void *ptr, ber_len_t size, void *ctx )
124 struct slab_heap *sh = ctx;
125 int pad = 2*sizeof(int)-1;
126 ber_len_t *p = (ber_len_t *)ptr;
129 if ( ptr == NULL ) return sl_malloc( size, ctx );
131 if ( ptr < sh->h_base || ptr >= sh->h_end ) {
133 LDAP_LOG( OPERATION, ERR,
134 "sl_free: not mine: 0x%lx\n", (long)ptr, 0,0 );
136 Debug( LDAP_DEBUG_ANY,
137 "sl_free: not mine: 0x%lx\n", (long)ptr, 0,0 );
140 exit( EXIT_FAILURE );
143 if ( size == 0 ) return NULL;
145 /* round up to doubleword boundary */
146 size += pad + sizeof( ber_len_t );
149 /* We always alloc a new block */
154 new = sl_malloc( size, ctx );
155 AC_MEMCPY( new, ptr, p[-1] );
161 sl_free( void *ptr, void *ctx )
163 struct slab_heap *sh = ctx;
165 if ( ptr < sh->h_base || ptr >= sh->h_end ) {
167 LDAP_LOG( OPERATION, ERR,
168 "sl_free: not mine: 0x%lx\n", (long)ptr, 0,0 );
170 Debug( LDAP_DEBUG_ANY,
171 "sl_free: not mine: 0x%lx\n", (long)ptr, 0,0 );
174 exit( EXIT_FAILURE );