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;
39 BerMemoryFunctions sl_mfuncs =
40 { sl_malloc, sl_calloc, sl_realloc, sl_free };
45 ber_set_option( NULL, LBER_OPT_MEMORY_FNS, &sl_mfuncs );
54 struct slab_heap *sh = NULL;
55 int pad = 2*sizeof(int)-1;
57 ldap_pvt_thread_pool_getkey( ctx, sl_mem_init, (void **)&sh, NULL );
59 /* round up to doubleword boundary */
64 sh = ch_malloc( sizeof(struct slab_heap) );
65 sh->h_base = ch_malloc( size );
66 ldap_pvt_thread_pool_setkey( ctx, sl_mem_init, (void *)sh, sl_mem_destroy );
67 } else if ( size > sh->h_end - sh->h_base ) {
68 sh->h_base = ch_realloc( sh->h_base, size );
70 sh->h_last = sh->h_base;
71 sh->h_end = sh->h_base + size;
81 struct slab_heap *sh = ctx;
82 int pad = 2*sizeof(int)-1;
85 /* ber_set_option calls us like this */
86 if (!ctx) return ber_memalloc_x( size, NULL );
88 /* round up to doubleword boundary */
89 size += pad + sizeof( ber_len_t );
92 if (sh->h_last + size >= sh->h_end ) {
94 LDAP_LOG( OPERATION, INFO,
95 "sl_malloc of %lu bytes failed, using ch_malloc\n", (long)size, 0,0 );
97 Debug( LDAP_DEBUG_TRACE,
98 "sl_malloc of %lu bytes failed, using ch_malloc\n", (long)size, 0,0 );
100 return ch_malloc( size );
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 /* Not our memory? */
132 if ( !sh || ptr < sh->h_base || ptr >= sh->h_end ) {
133 return ch_realloc( ptr, size );
136 if ( size == 0 ) return NULL;
138 /* round up to doubleword boundary */
139 size += pad + sizeof( ber_len_t );
142 /* Never shrink blocks, always alloc if growth needed */
146 new = sl_malloc( size, ctx );
147 AC_MEMCPY( new, ptr, p[-1] );
153 sl_free( void *ptr, void *ctx )
155 struct slab_heap *sh = ctx;
157 if ( !sh || ptr < sh->h_base || ptr >= sh->h_end ) {
163 sl_release( void *ptr, void *ctx )
165 struct slab_heap *sh = ctx;
167 if ( sh && ptr >= sh->h_base && ptr <= sh->h_end ) {
175 struct slab_heap *sh = ctx;
178 if (sh) ret = sh->h_last;