su_alloc.c 39.6 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1 2 3 4 5 6 7
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
8
 * This library is free software; you can redistribute it and/or
Pekka Pessi's avatar
Pekka Pessi committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include "config.h"

/**@defgroup su_alloc Memory Management Tutorial
 *
 * This page gives a short overview of home-based memory management used
 * with Sofia. Such home-based memory management is useful when a lot of
 * memory blocks are allocated for given task. The allocations are done via
32 33 34
 * the @e memory @e home, which keeps a reference to each block. When the
 * memory home is then freed, it will free all blocks to which it has
 * reference.
Pekka Pessi's avatar
Pekka Pessi committed
35 36
 *
 * Typically, there is a @e home @e object which contains a su_home_t
37 38
 * structure in the beginning of the object (sort of inheritance from
 * su_home_t):
Pekka Pessi's avatar
Pekka Pessi committed
39 40 41 42 43 44 45 46
 * @code
 * struct context {
 *   su_home_t ctx_home[1];
 *   other_t  *ctx_stuff;
 *   ...
 * }
 * @endcode
 * 
47 48 49 50 51 52 53 54
 * A new home memory pool can be created with su_home_new():
 * @code
 * struct context *ctx = su_home_new(sizeof (struct context));
 * @endcode
 *
 * It is also possible to create a secondary memory pool that can be
 * released separately:
 *
Pekka Pessi's avatar
Pekka Pessi committed
55 56 57 58
 * @code
 * struct context *ctx = su_home_clone(tophome, sizeof (struct context));
 * @endcode
 *
59 60
 * Note that the tophome has a reference to @a ctx structure; whenever
 * tophome is freed, the @a ctx is also freed.
61 62
 * 
 * You can also create an independent home object by passing NULL as @a
63
 * tophome argument. This is identical to the call to su_home_new().
Pekka Pessi's avatar
Pekka Pessi committed
64
 *
65
 * The memory allocations using @a ctx proceed then as follows:
Pekka Pessi's avatar
Pekka Pessi committed
66
 * @code
67
 *    zeroblock = su_zalloc(ctx->ctx_home, sizeof (*zeroblock));
Pekka Pessi's avatar
Pekka Pessi committed
68 69 70
 * @endcode
 *
 * The home memory pool - the home object and all the memory blocks
71
 * allocated using it - are freed when su_home_unref() is called:
Pekka Pessi's avatar
Pekka Pessi committed
72 73
 *
 * @code
74
 *    su_home_unref(ctx->ctx_home).
Pekka Pessi's avatar
Pekka Pessi committed
75 76
 * @endcode
 *
77 78 79 80 81
 * @note For historical reasons, su_home_unref() is also known as
 * su_home_zap().
 *
 * As you might have guessed, it is also possible to use reference counting
 * with home objects. The function su_home_ref() increases the reference
82 83
 * count, su_home_unref() decreases it. A newly allocated or initialized
 * home object has reference count of 1.
84
 *
85 86 87 88
 * @note Please note that while it is possible to create new references to
 * secondary home objects which have a parent home, the secondary home
 * objects will always be destroyed when the parent home is destroyed even
 * if there are other references left to them.
89 90 91
 *
 * The memory blocks in a cloned home object are freed when the object with
 * home itself is freed:
Pekka Pessi's avatar
Pekka Pessi committed
92 93 94 95
 * @code
 *    su_free(tophome, ctx);
 * @endcode
 * 
96 97 98
 * @note
 *
 * The su_home_destroy() function is deprecated as it does not free the home
99 100
 * object itself. Like su_home_deinit(), it should be called only on home
 * objects with reference count of 1.
101
 *
102 103 104 105
 * The function su_home_init() initializes a home object structure. When the
 * initialized home object is destroyed or deinitialized or its reference
 * count reaches zero, the memory allocate thorugh it reclaimed but the home
 * object structure itself is not freed.
Pekka Pessi's avatar
Pekka Pessi committed
106
 *
107
 * @section su_home_destructor_usage Destructors
108 109 110 111 112 113
 *
 * It is possible to give a destructor function to a home object. The
 * destructor releases other resources associated with the home object
 * besides memory. The destructor function will be called when the reference
 * count of home reaches zero (upon calling su_home_unref()) or the home
 * object is otherwise deinitialized (calling su_home_deinit() on
114
 * objects allocated from stack).
115
 *
Pekka Pessi's avatar
Pekka Pessi committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
 * @section su_home_move_example Combining Allocations
 *
 * In some cases, an operation that makes multiple memory allocations may
 * fail, making those allocations redundant. If the allocations are made
 * through a temporary home, they can be conveniently freed by calling
 * su_home_deinit(), for instance. If, however, the operation is successful,
 * and one wants to keep the allocations, the allocations can be combined
 * into an existing home with su_home_move(). For example,
 * @code
 * int example(su_home_t *home, ...) 
 * {
 *   su_home_t temphome[1] = { SU_HOME_INIT(temphome) };
 *   
 *   ... do lot of allocations with temphome ...
 *  
 *   if (success) 
 *     su_home_move(home, temphome);
 *   su_home_deinit(temphome);
 *
 *   return success;
 * }
 * @endcode
 *
 * Note that the @a temphome is deinitialized in every case, but when
 * operation is successful, the allocations are moved from @a temphome to @a
 * home.
 *
 * @section su_alloc_threadsafe Threadsafe Operation
 *
 * If multiple threads need to access same home object, it must be marked as
146
 * @e threadsafe by calling su_home_threadsafe() with the home pointer as
147
 * argument. The threadsafeness is not inherited by clones.
148 149
 *
 * The threadsafe home objects can be locked and unlocked with
150 151
 * su_home_mutex_lock() and su_home_mutex_unlock(). These operations are
 * no-op on home object that is not threadsafe.
152 153 154
 *
 * @section su_alloc_preloading Preloading a Memory Home
 *
155 156
 * In some situations there is quite heavy overhead if the global heap
 * allocator is used. The overhead caused by the large number of small
157 158
 * allocations can be reduced by using su_home_preload(): it allocates or
 * preloads some a memory to home to be used as a kind of private heap. The
159
 * preloaded memory area is then used to satisfy small enough allocations. 
160 161 162 163 164 165 166 167 168 169 170
 * For instance, the SIP parser typically preloads some 2K of memory when it
 * starts to parse the message.
 *
 * @section su_alloc_stack Using Stack
 *
 * In some situation, it is sensible to use memory allocated from stack for
 * some operations. The su_home_auto() function can be used for that
 * purpose. The memory area from stack is used to satisfy the allocations as
 * far as possible; if it is not enough, allocation is made from heap.
 *
 * The word @e auto refers to the automatic scope; however, the home object
171 172 173
 * that was initialized with su_home_auto() must be explicitly deinitialized
 * with su_home_deinit() or su_home_unref() when the program exits the scope
 * where the stack frame used in su_home_auto() was allocated.
Pekka Pessi's avatar
Pekka Pessi committed
174 175
 */

Pekka Pessi's avatar
Pekka Pessi committed
176 177 178 179 180 181 182 183
/**@ingroup su_alloc
 * @CFILE su_alloc.c  Home-based memory management.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>.
 * 
 * @date Created: Thu Aug 19 01:12:25 1999 ppessi
 */

184 185 186 187
#include <sofia-sip/su_config.h>
#include "sofia-sip/su_alloc.h"
#include "sofia-sip/su_alloc_stat.h"
#include "sofia-sip/su_errno.h"
188

Pekka Pessi's avatar
Pekka Pessi committed
189 190 191 192 193 194 195 196 197 198
#include <stdlib.h>
#include <stddef.h>
#include <memory.h>
#include <limits.h>

#include <assert.h>

void (*su_home_locker)(void *mutex);
void (*su_home_unlocker)(void *mutex);

199 200 201
void (*su_home_mutex_locker)(void *mutex);
void (*su_home_mutex_unlocker)(void *mutex);

202 203
void (*su_home_destroy_mutexes)(void *mutex);

204
#define MEMLOCK(h)   \
Pekka Pessi's avatar
Pekka Pessi committed
205 206 207 208 209 210 211 212 213 214 215
  (((h) && (h)->suh_lock ? su_home_locker((h)->suh_lock) : (void)0), (h)->suh_blocks)
#define UNLOCK(h) (((h) && (h)->suh_lock ? su_home_unlocker((h)->suh_lock) : (void)0), NULL)

#ifdef NDEBUG
#define MEMCHECK 0
#define MEMCHECK_EXTRA 0
#elif !defined(MEMCHECK)
/* Default settings for valgrinding */
#define MEMCHECK 1
#define MEMCHECK_EXTRA 0
#elif !defined(MEMCHECK_EXTRA)
216
#define MEMCHECK_EXTRA sizeof (size_t)
Pekka Pessi's avatar
Pekka Pessi committed
217 218 219 220
#endif

enum { 
  SUB_N = 31,			/**< Initial size */
221
  SUB_N_AUTO = 7,		/**< Initial size for autohome */
Pekka Pessi's avatar
Pekka Pessi committed
222 223 224 225 226 227
  SUB_P = 29			/**< Secondary probe.
				 * Secondary probe must be relative prime 
				 * with all sub_n values */
};		

#define ALIGNMENT (8)
228
#define ALIGN(n) (size_t)(((n) + (ALIGNMENT - 1)) & (size_t)~(ALIGNMENT - 1))
229
#define SIZEBITS (sizeof (unsigned) * 8 - 1)
Pekka Pessi's avatar
Pekka Pessi committed
230 231

typedef struct {
232
  unsigned sua_size:SIZEBITS;	/**< Size of the block */
233
  unsigned sua_home:1;		/**< Is this another home? */
234
  unsigned :0;
235
  void    *sua_data;		/**< Data pointer */
Pekka Pessi's avatar
Pekka Pessi committed
236 237 238
} su_alloc_t;

struct su_block_s {
239
  su_home_t  *sub_parent;	/**< Parent home */
240 241
  char       *sub_preload;	/**< Preload area */
  su_home_stat_t *sub_stats;	/**< Statistics.. */
242
  void      (*sub_destructor)(void *); /**< Destructor function */
243
  size_t      sub_ref;		/**< Reference count */
244
#define REF_MAX SIZE_MAX
245 246
  size_t      sub_used;		/**< Number of blocks allocated */
  size_t      sub_n;		/**< Size of hash table  */
Pekka Pessi's avatar
Pekka Pessi committed
247 248 249

  unsigned    sub_prsize:16;	/**< Preload size */
  unsigned    sub_prused:16;	/**< Used from preload */
250 251 252
  unsigned    sub_hauto:1;      /**< "Home" is not from malloc */
  unsigned    sub_auto:1;	/**< struct su_block_s is not from malloc */
  unsigned    sub_preauto:1;	/**< Preload is not from malloc */
Pekka Pessi's avatar
Pekka Pessi committed
253 254
  unsigned    sub_auto_all:1;	/**< Everything is from stack! */
  unsigned :0;
255

Pekka Pessi's avatar
Pekka Pessi committed
256 257 258 259 260
  su_alloc_t  sub_nodes[SUB_N];	/**< Pointers to data/lower blocks */
};

static void su_home_check_blocks(su_block_t const *b);

261
static void su_home_stats_alloc(su_block_t *, void *p, void *preload,
262
				size_t size, int zero);
263
static void su_home_stats_free(su_block_t *sub, void *p, void *preload,
264
			       unsigned size);
Pekka Pessi's avatar
Pekka Pessi committed
265

266 267
static void _su_home_deinit(su_home_t *home);

Pekka Pessi's avatar
Pekka Pessi committed
268 269 270
#define SU_ALLOC_STATS 1

#if SU_ALLOC_STATS
271 272 273 274
size_t count_su_block_find, count_su_block_find_loop;
size_t size_su_block_find, used_su_block_find;
size_t max_size_su_block_find, max_used_su_block_find;
size_t su_block_find_collision, su_block_find_collision_used, 
Pekka Pessi's avatar
Pekka Pessi committed
275 276 277
  su_block_find_collision_size;
#endif

278
su_inline su_alloc_t *su_block_find(su_block_t *b, void const *p)
Pekka Pessi's avatar
Pekka Pessi committed
279
{
280
  size_t h, h0, probe;
Pekka Pessi's avatar
Pekka Pessi committed
281 282

#if SU_ALLOC_STATS  
283
  size_t collision = 0;
Pekka Pessi's avatar
Pekka Pessi committed
284 285 286 287 288 289 290 291 292 293 294 295

  count_su_block_find++;
  size_su_block_find += b->sub_n;
  used_su_block_find += b->sub_used;
  if (b->sub_n > max_size_su_block_find)
    max_size_su_block_find = b->sub_n;
  if (b->sub_used > max_used_su_block_find)
    max_used_su_block_find = b->sub_used;
#endif

  assert(p != NULL);

296
  h = h0 = (size_t)((uintptr_t)p % b->sub_n);
Pekka Pessi's avatar
Pekka Pessi committed
297

298 299
  probe = (b->sub_n > SUB_P) ? SUB_P : 1;

Pekka Pessi's avatar
Pekka Pessi committed
300 301 302
  do {
    if (b->sub_nodes[h].sua_data == p)
      return &b->sub_nodes[h];
303
    h += probe;
Pekka Pessi's avatar
Pekka Pessi committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317
    if (h >= b->sub_n)
      h -= b->sub_n;
#if SU_ALLOC_STATS
    if (++collision > su_block_find_collision)
      su_block_find_collision = collision, 
	su_block_find_collision_used = b->sub_used,
	su_block_find_collision_size = b->sub_n;
    count_su_block_find_loop++;
#endif
  } while (h != h0);

  return NULL;
}

318
su_inline su_alloc_t *su_block_add(su_block_t *b, void *p)
Pekka Pessi's avatar
Pekka Pessi committed
319
{
320
  size_t h, probe;
Pekka Pessi's avatar
Pekka Pessi committed
321 322 323

  assert(p != NULL);

324
  h = (size_t)((uintptr_t)p % b->sub_n);
Pekka Pessi's avatar
Pekka Pessi committed
325

326 327
  probe = (b->sub_n > SUB_P) ? SUB_P : 1;

Pekka Pessi's avatar
Pekka Pessi committed
328
  while (b->sub_nodes[h].sua_data) {
329
    h += probe;
Pekka Pessi's avatar
Pekka Pessi committed
330 331 332 333 334 335 336 337 338 339
    if (h >= b->sub_n)
      h -= b->sub_n;
  }

  b->sub_used++;
  b->sub_nodes[h].sua_data = p;

  return &b->sub_nodes[h];
}

340
su_inline int su_is_preloaded(su_block_t const *sub, char *data)
Pekka Pessi's avatar
Pekka Pessi committed
341 342 343 344 345 346 347
{
  return
    sub->sub_preload && 
    sub->sub_preload <= data && 
    sub->sub_preload + sub->sub_prsize > data;
}

348
su_inline int su_alloc_check(su_block_t const *sub, su_alloc_t const *sua)
Pekka Pessi's avatar
Pekka Pessi committed
349 350
{
#if MEMCHECK_EXTRA
351
  size_t size, term;
Pekka Pessi's avatar
Pekka Pessi committed
352 353
  assert(sua);
  if (sua) {
354
    size = (size_t)sua->sua_size;
355
    memcpy(&term, (char *)sua->sua_data + size, sizeof (term));
356 357
    assert(size - term == 0);
    return size - term == 0;
Pekka Pessi's avatar
Pekka Pessi committed
358 359 360 361 362 363 364 365 366
  }
  else
    return 0;
#endif
  return sua != NULL;
}

/** Allocate the block hash table.
 *
367 368 369
 * @internal
 *
 * Allocate a block hash table of @a n elements.
Pekka Pessi's avatar
Pekka Pessi committed
370 371 372 373 374 375 376 377
 *
 * @param home  pointer to home object
 * @param n     number of buckets in hash table
 *
 * @return
 *   This function returns a pointer to the allocated hash table or
 *   NULL if an error occurred.
 */
378
su_inline su_block_t *su_hash_alloc(size_t n)
Pekka Pessi's avatar
Pekka Pessi committed
379
{
380
  su_block_t *b = calloc(1, offsetof(su_block_t, sub_nodes[n]));
Pekka Pessi's avatar
Pekka Pessi committed
381

382 383 384 385
  if (b) {
    /* Implicit su_home_init(); */
    b->sub_ref = 1;
    b->sub_hauto = 1;
Pekka Pessi's avatar
Pekka Pessi committed
386
    b->sub_n = n;
387
  }
Pekka Pessi's avatar
Pekka Pessi committed
388 389 390 391

  return b;
}

392 393
enum sub_zero { do_malloc, do_calloc, do_clone };

Pekka Pessi's avatar
Pekka Pessi committed
394
/** Allocate a memory block.
395 396
 *
 * @internal
Pekka Pessi's avatar
Pekka Pessi committed
397
 *
398
 * Precondition: locked home
Pekka Pessi's avatar
Pekka Pessi committed
399
 *
400 401 402 403 404
 * @param home home to allocate
 * @param sub  block structure used to allocate
 * @param size
 * @param zero if true, zero allocated block;
 *             if > 1, allocate a subhome
Pekka Pessi's avatar
Pekka Pessi committed
405 406
 *
 */
407 408 409
static 
void *sub_alloc(su_home_t *home, 
		su_block_t *sub,
410
		size_t size,
411
		enum sub_zero zero)
Pekka Pessi's avatar
Pekka Pessi committed
412
{
Pekka Pessi's avatar
Pekka Pessi committed
413
  void *data, *preload = NULL;
414
  
415 416 417 418
  assert (size < (((size_t)1) << SIZEBITS));

  if (size >= ((size_t)1) << SIZEBITS)
    return (void)(errno = ENOMEM), NULL;
Pekka Pessi's avatar
Pekka Pessi committed
419 420

  if (sub == NULL || 3 * sub->sub_used > 2 * sub->sub_n) {
421
    /* Resize the hash table */
422
    size_t i, n, n2, used;
Pekka Pessi's avatar
Pekka Pessi committed
423 424 425 426 427 428 429
    su_block_t *b2;

    if (sub)
      n = home->suh_blocks->sub_n, n2 = 4 * n + 3, used = sub->sub_used;
    else
      n = 0, n2 = SUB_N, used = 0;

Pekka Pessi's avatar
Pekka Pessi committed
430 431 432
#if 0
    printf("su_alloc(home = %p): realloc block hash of size %d\n", home, n2);
#endif
Pekka Pessi's avatar
Pekka Pessi committed
433

434 435
    if (!(b2 = su_hash_alloc(n2)))
      return NULL;
Pekka Pessi's avatar
Pekka Pessi committed
436 437

    for (i = 0; i < n; i++) {
438
      if (sub->sub_nodes[i].sua_data)
Pekka Pessi's avatar
Pekka Pessi committed
439 440 441 442 443
	su_block_add(b2, sub->sub_nodes[i].sua_data)[0] = sub->sub_nodes[i];
    }

    if (sub) {
      b2->sub_parent = sub->sub_parent;
444
      b2->sub_ref = sub->sub_ref;
Pekka Pessi's avatar
Pekka Pessi committed
445 446 447
      b2->sub_preload = sub->sub_preload;
      b2->sub_prsize = sub->sub_prsize;
      b2->sub_prused = sub->sub_prused;
448
      b2->sub_hauto = sub->sub_hauto;
Pekka Pessi's avatar
Pekka Pessi committed
449
      b2->sub_preauto = sub->sub_preauto;
450
      b2->sub_destructor = sub->sub_destructor;
451
      /* auto_all is not copied! */
Pekka Pessi's avatar
Pekka Pessi committed
452 453 454
      b2->sub_stats = sub->sub_stats;
    }

455 456
    home->suh_blocks = b2;

Pekka Pessi's avatar
Pekka Pessi committed
457 458 459
    if (sub && !sub->sub_auto)
      free(sub);
    sub = b2;
Pekka Pessi's avatar
Pekka Pessi committed
460 461
  }

462
  if (size && sub && zero < do_clone &&
463
      sub->sub_preload && size <= sub->sub_prsize) {
464
    /* Use preloaded memory */
465
    size_t prused = sub->sub_prused + size + MEMCHECK_EXTRA; 
466 467
    prused = ALIGN(prused);
    if (prused <= sub->sub_prsize) {
Pekka Pessi's avatar
Pekka Pessi committed
468
      preload = (char *)sub->sub_preload + sub->sub_prused;
469
      sub->sub_prused = (unsigned)prused;
Pekka Pessi's avatar
Pekka Pessi committed
470 471
    }
  }
472

473
  if (preload && zero)
Pekka Pessi's avatar
Pekka Pessi committed
474
    data = memset(preload, 0, size);
475
  else if (preload)
Pekka Pessi's avatar
Pekka Pessi committed
476
    data = preload;
477 478
  else if (zero)
    data = calloc(1, size + MEMCHECK_EXTRA);
Pekka Pessi's avatar
Pekka Pessi committed
479 480 481 482
  else
    data = malloc(size + MEMCHECK_EXTRA);

  if (data) {
483 484
    su_alloc_t *sua;

Pekka Pessi's avatar
Pekka Pessi committed
485
#if MEMCHECK_EXTRA
486
    size_t term = 0 - size;
Pekka Pessi's avatar
Pekka Pessi committed
487 488 489
    memcpy((char *)data + size, &term, sizeof (term));
#endif

490 491 492
    if (!preload)
      sub->sub_auto_all = 0;

493
    if (zero >= do_clone) {
494
      /* Prepare cloned home */ 
495 496 497 498 499 500 501
      su_home_t *subhome = data;

      assert(preload == 0);

      subhome->suh_blocks = su_hash_alloc(SUB_N);
      if (!subhome->suh_blocks) 
	return (void)free(data), NULL;
502

503
      subhome->suh_size = (unsigned)size;
504
      subhome->suh_blocks->sub_parent = home;
505
      subhome->suh_blocks->sub_hauto = 0;
506 507
    }

508 509
    /* OK, add the block to the hash table. */

510
    sua = su_block_add(sub, data); assert(sua);
511
    sua->sua_size = (unsigned)size;
512
    sua->sua_home = zero > 1;
Pekka Pessi's avatar
Pekka Pessi committed
513 514

    if (sub->sub_stats)
515
      su_home_stats_alloc(sub, data, preload, size, zero);
Pekka Pessi's avatar
Pekka Pessi committed
516 517
  }

518 519 520 521 522 523 524
  return data;
}

/**Create a new su_home_t object.
 *
 * Create a home object used to collect multiple memory allocations under
 * one handle. The memory allocations made using this home object is freed
525 526 527
 * either when this home is destroyed. 
 *
 * The maximum @a size of a home object is INT_MAX (2 gigabytes).
528 529 530
 *
 * @param size    size of home object
 *
531
 * The memory home object allocated with su_home_new() can be reclaimed with
532 533 534 535 536 537
 * su_home_unref().
 *
 * @return
 * This function returns a pointer to an su_home_t object, or NULL upon
 * an error.
 */
538
void *su_home_new(isize_t size)
539 540 541 542 543 544
{
  su_home_t *home;

  assert(size >= sizeof (*home));

  if (size < sizeof (*home))
545
    return (void)(errno = EINVAL), NULL;
546
  else if (size > INT_MAX)
547
    return (void)(errno = ENOMEM), NULL;
548 549 550

  home = calloc(1, size);
  if (home) {
551
    home->suh_size = (int)size;
552 553
    home->suh_blocks = su_hash_alloc(SUB_N);
    if (home->suh_blocks)
554
      home->suh_blocks->sub_hauto = 0;
555 556 557 558 559 560 561 562
    else
      free(home), home = NULL;
  }

  return home;
}

/** Create a new reference to a home object. */
563
void *su_home_ref(su_home_t const *home)
564 565 566 567 568 569 570 571 572 573
{
  if (home) {
    su_block_t *sub = MEMLOCK(home);

    if (sub == NULL || sub->sub_ref == 0) {
      assert(sub && sub->sub_ref != 0);
      UNLOCK(home);
      return NULL;
    }
    
574
    if (sub->sub_ref != REF_MAX)
575 576 577
      sub->sub_ref++;
    UNLOCK(home);
  }
578 579
  else
    su_seterrno(EFAULT);
580

581
  return (void *)home;
582 583
}

584 585 586 587 588 589 590 591 592 593
/** Set destructor function.
 *
 * The destructor function is called after the reference count of a
 * #su_home_t object reaches zero or a home object is deinitialized, but
 * before any of the memory areas within the home object are freed.
 *
 * @since New in @VERSION_1_12_4.
 * Earlier versions had su_home_desctructor() (spelling).
 */
int su_home_destructor(su_home_t *home, void (*destructor)(void *))
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
{
  int retval = -1;

  if (home) {
    su_block_t *sub = MEMLOCK(home);
    if (sub && sub->sub_destructor == NULL) {
      sub->sub_destructor = destructor;
      retval = 0;
    }
    UNLOCK(home);
  }
  else
    su_seterrno(EFAULT);

  return retval;
}

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
#undef su_home_desctructor

/** Set destructor function.
 *
 * @deprecated The su_home_destructor() was added in @VERSION_1_12_4. The
 * su_home_desctructor() is now defined as a macro expanding as
 * su_home_destructor(). If you want to compile an application as binary
 * compatible with earlier versions, you have to define su_home_desctructor
 * as itself, e.g.,
 * @code
 * #define su_home_desctructor su_home_desctructor
 * #include <sofia-sip/su_alloc.h>
 * @endcode
 */
int su_home_desctructor(su_home_t *home, void (*destructor)(void *))
{
  return su_home_destructor(home, destructor);
}
629

630 631
/**Unreference a su_home_t object.
 *
632 633
 * Decrements the reference count on home object and destroys and frees it
 * and the memory allocations using it if the reference count reaches 0.
634
 *
635
 * @param home memory pool object to be unreferenced
636 637 638
 *
 * @retval 1 if object was freed
 * @retval 0 if object is still alive
639
 */
640
int su_home_unref(su_home_t *home)
641 642 643 644
{
  su_block_t *sub;

  if (home == NULL)
645
    return 0;
646 647 648 649 650

  sub = MEMLOCK(home);

  if (sub == NULL) {
    /* Xyzzy */
651
    return 0;
652
  }
653
  else if (sub->sub_ref == REF_MAX) {
654
    UNLOCK(home);
655
    return 0;
656 657 658
  }
  else if (--sub->sub_ref > 0) {
    UNLOCK(home);
659 660 661 662 663 664 665
    return 0;
  }
  else if (sub->sub_parent) {
    su_home_t *parent = sub->sub_parent;
    UNLOCK(home);
    su_free(parent, home);
    return 1;
666 667
  }
  else {
668
    int hauto = sub->sub_hauto;
669
    _su_home_deinit(home);
670 671
    if (!hauto)
      free(home);
672
    /* UNLOCK(home); */
673
    return 1;
674 675 676
  }
}

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
/** Return reference count of home. */
size_t su_home_refcount(su_home_t *home)
{
  size_t count = 0;

  if (home) {
    su_block_t *sub = MEMLOCK(home);

    if (sub)
      count = sub->sub_ref;

    UNLOCK(home);
  }

  return count;
}
693 694 695 696 697

/**Clone a su_home_t object.
 *
 * Clone a secondary home object used to collect multiple memoryf
 * allocations under one handle. The memory is freed either when the cloned
698
 * home is destroyed or when the parent home is destroyed.
699 700 701 702 703 704 705
 *
 * An independent
 * home object is created if NULL is passed as @a parent argument.
 *
 * @param parent  a parent object (may be NULL)
 * @param size    size of home object
 *
706
 * The memory home object allocated with su_home_clone() can be freed with
707 708 709 710 711 712
 * su_home_unref().
 *
 * @return
 * This function returns a pointer to an su_home_t object, or NULL upon
 * an error.
 */
713
void *su_home_clone(su_home_t *parent, isize_t size)
714 715 716 717 718 719
{
  su_home_t *home;

  assert(size >= sizeof (*home));

  if (size < sizeof (*home))
720 721 722
    return (void)(errno = EINVAL), NULL;
  else if (size > INT_MAX)
    return (void)(errno = ENOMEM), NULL;
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

  if (parent) {
    su_block_t *sub = MEMLOCK(parent);
    home = sub_alloc(parent, sub, size, 2);
    UNLOCK(parent);
  }
  else {
    home = su_home_new(size);
  }

  return home;
}

/** Return true if home is a clone. */
int su_home_has_parent(su_home_t const *home)
{
  return home && !home->suh_lock && 
    home->suh_blocks && home->suh_blocks->sub_parent;
}

/** Allocate a memory block.
 *
745
 * Allocates a memory block of a given @a size.
746 747 748 749 750 751 752 753 754 755
 *
 * If @a home is NULL, this function behaves exactly like malloc().
 *
 * @param home  pointer to home object
 * @param size  size of the memory block to be allocated
 *
 * @return
 * This function returns a pointer to the allocated memory block or
 * NULL if an error occurred.
 */
756
void *su_alloc(su_home_t *home, isize_t size)
757 758 759 760
{
  void *data;

  if (home) {
761
    data = sub_alloc(home, MEMLOCK(home), size, 0);
762 763 764 765
    UNLOCK(home);
  }
  else
    data = malloc(size);
Pekka Pessi's avatar
Pekka Pessi committed
766 767 768 769 770 771

  return data;
}

/**Free a memory block.
 *
772 773 774
 * Frees a single memory block. The @a home must be the owner of the memory
 * block (usually the memory home used to allocate the memory block, or NULL
 * if no home was used).
Pekka Pessi's avatar
Pekka Pessi committed
775 776 777 778 779 780 781 782
 *
 * @param home  pointer to home object
 * @param data  pointer to the memory block to be freed
 */
void su_free(su_home_t *home, void *data)
{
  if (home && data) {
    su_alloc_t *allocation;
783
    su_block_t *sub = MEMLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
784 785 786 787 788 789

    assert(sub);
    allocation = su_block_find(sub, data);
    assert(allocation);

    if (su_alloc_check(sub, allocation)) {
790 791 792 793 794
      void *preloaded = NULL;

      /* Is this preloaded data? */
      if (su_is_preloaded(sub, data))
	preloaded = data;
Pekka Pessi's avatar
Pekka Pessi committed
795 796

      if (sub->sub_stats)
797
	su_home_stats_free(sub, data, preloaded, allocation->sua_size);
Pekka Pessi's avatar
Pekka Pessi committed
798

799 800 801 802
      if (allocation->sua_home) {
	su_home_t *subhome = data;
	su_block_t *sub = MEMLOCK(subhome);

803
	assert(sub->sub_ref != REF_MAX);
804 805 806 807 808 809
	/* assert(sub->sub_ref > 0); */

	sub->sub_ref = 0;	/* Zap all references */

	_su_home_deinit(subhome);
      }
Pekka Pessi's avatar
Pekka Pessi committed
810 811

#if MEMCHECK != 0
812
      memset(data, 0xaa, (size_t)allocation->sua_size);
Pekka Pessi's avatar
Pekka Pessi committed
813 814 815 816
#endif

      memset(allocation, 0, sizeof (*allocation));
      sub->sub_used--;
817 818 819

      if (preloaded)
	data = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
820 821 822 823 824 825 826 827 828 829
    }

    UNLOCK(home);
  }

  free(data);
}

/** Check home consistency.
 *
830 831 832
 * Ensures that the home structure and all memory blocks allocated through
 * it are consistent. It can be used to catch memory allocation and usage
 * errors.
Pekka Pessi's avatar
Pekka Pessi committed
833 834 835 836 837 838
 *
 * @param home Pointer to a memory home.
 */
void su_home_check(su_home_t const *home)
{
#if MEMCHECK != 0
839
  su_block_t const *b = MEMLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
840 841 842 843 844 845 846 847 848 849 850 851 852

  su_home_check_blocks(b);

  UNLOCK(home);
#endif
}

/** Check home blocks. */
static
void su_home_check_blocks(su_block_t const *b)
{
#if MEMCHECK != 0
  if (b) {
853
    size_t i, used;
Pekka Pessi's avatar
Pekka Pessi committed
854 855 856 857 858
    assert(b->sub_used <= b->sub_n);

    for (i = 0, used = 0; i < b->sub_n; i++)
      if (b->sub_nodes[i].sua_data) {
	su_alloc_check(b, &b->sub_nodes[i]), used++;
859
	if (b->sub_nodes[i].sua_home)
Pekka Pessi's avatar
Pekka Pessi committed
860 861 862 863 864 865 866 867 868 869 870
	  su_home_check((su_home_t *)b->sub_nodes[i].sua_data);
      }

    assert(used == b->sub_used);
  }
#endif
}

/**
 * Create an su_home_t object.
 *
871 872
 * Creates a home object. A home object is used to collect multiple memory
 * allocations, so that they all can be freed by calling su_home_unref().
Pekka Pessi's avatar
Pekka Pessi committed
873
 *
874
 * @return This function returns a pointer to an #su_home_t object, or 
Pekka Pessi's avatar
Pekka Pessi committed
875 876 877 878
 * NULL upon an error. 
 */
su_home_t *su_home_create(void)
{
879
  return su_home_new(sizeof(su_home_t));
Pekka Pessi's avatar
Pekka Pessi committed
880 881
}

882
/** Destroy a home object
Pekka Pessi's avatar
Pekka Pessi committed
883
 *
884 885
 * Frees all memory blocks associated with a home object. Note that the home
 * object structure is not freed.
Pekka Pessi's avatar
Pekka Pessi committed
886
 *
887
 * @param home pointer to a home object
Pekka Pessi's avatar
Pekka Pessi committed
888 889
 *
 * @deprecated
890 891
 * su_home_destroy() is included for backwards compatibility only. Use
 * su_home_unref() instead of su_home_destroy().
Pekka Pessi's avatar
Pekka Pessi committed
892 893 894
 */
void su_home_destroy(su_home_t *home)
{
895 896 897 898 899 900 901 902 903
  if (MEMLOCK(home)) {
    assert(home->suh_blocks);
    assert(home->suh_blocks->sub_ref == 1);
    if (!home->suh_blocks->sub_hauto)
      /* should warn user */;
    home->suh_blocks->sub_hauto = 1;
    _su_home_deinit(home);
    /* UNLOCK(home); */
  }
Pekka Pessi's avatar
Pekka Pessi committed
904 905
}

906
/** Initialize an su_home_t struct.
Pekka Pessi's avatar
Pekka Pessi committed
907
 *
908 909 910
 * Initializes an su_home_t structure. It can be used when the home
 * structure is allocated from stack or when the home structure is part of
 * an another object.
Pekka Pessi's avatar
Pekka Pessi committed
911 912 913
 *
 * @param home pointer to home object
 *
914 915 916 917
 * @retval 0 when successful
 * @retval -1 upon an error.
 *
 * @sa SU_HOME_INIT(), su_home_deinit(), su_home_new(), su_home_clone()
Pekka Pessi's avatar
Pekka Pessi committed
918 919 920
 */
int su_home_init(su_home_t *home)
{
921 922
  su_block_t *sub;
    
Pekka Pessi's avatar
Pekka Pessi committed
923 924 925
  if (home == NULL)
    return -1;

926 927 928
  home->suh_blocks = sub = su_hash_alloc(SUB_N);
  if (!sub)
    return -1;
Pekka Pessi's avatar
Pekka Pessi committed
929

930
  return 0;
Pekka Pessi's avatar
Pekka Pessi committed
931 932 933 934 935 936
}

/** Internal deinitialization */
static
void _su_home_deinit(su_home_t *home)
{
937
  if (home->suh_blocks) {
938
    size_t i;
Pekka Pessi's avatar
Pekka Pessi committed
939 940
    su_block_t *b;

941
     if (home->suh_blocks->sub_destructor) {
942 943 944 945 946
      void (*destructor)(void *) = home->suh_blocks->sub_destructor;
      home->suh_blocks->sub_destructor = NULL;
      destructor(home);
    }

Pekka Pessi's avatar
Pekka Pessi committed
947 948 949 950 951 952
    b = home->suh_blocks;

    su_home_check_blocks(b);

    for (i = 0; i < b->sub_n; i++) {
      if (b->sub_nodes[i].sua_data) {
953 954
	if (b->sub_nodes[i].sua_home) {
	  su_home_t *subhome = b->sub_nodes[i].sua_data;
955 956 957 958 959 960 961 962 963 964
	  su_block_t *subb = MEMLOCK(subhome);

	  assert(subb); assert(subb->sub_ref >= 1);
#if 0
	  if (subb->sub_ref > 0)
	    SU_DEBUG_7(("su_home_unref: subhome %p with destructor %p has still %u refs\n",
			subhome, subb->sub_destructor, subb->sub_ref));
#endif
	  subb->sub_ref = 0;	/* zap them all */
	  _su_home_deinit(subhome);
965 966 967 968
	}
	else if (su_is_preloaded(b, b->sub_nodes[i].sua_data))
	  continue;
	free(b->sub_nodes[i].sua_data);
Pekka Pessi's avatar
Pekka Pessi committed
969 970 971
      }
    }

Pekka Pessi's avatar
Pekka Pessi committed
972
    if (b->sub_preload && !b->sub_preauto)
Pekka Pessi's avatar
Pekka Pessi committed
973 974 975
      free(b->sub_preload);
    if (b->sub_stats)
      free(b->sub_stats);
Pekka Pessi's avatar
Pekka Pessi committed
976 977
    if (!b->sub_auto)
      free(b);
Pekka Pessi's avatar
Pekka Pessi committed
978 979

    home->suh_blocks = NULL;
980 981 982

    if (home->suh_lock)
      su_home_destroy_mutexes(home->suh_lock);
Pekka Pessi's avatar
Pekka Pessi committed
983 984
  }

985
  home->suh_lock = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
986 987 988 989
}

/** Free memory blocks allocated through home.
 *
990 991 992
 * Frees the memory blocks associated with the home object allocated. It
 * does not free the home object itself. Use su_home_unref() to free the
 * home object.
Pekka Pessi's avatar
Pekka Pessi committed
993 994
 *
 * @param home pointer to home object
995 996
 *
 * @sa su_home_init()
Pekka Pessi's avatar
Pekka Pessi committed
997 998 999
 */
void su_home_deinit(su_home_t *home)
{
1000
  if (MEMLOCK(home)) {
1001 1002 1003
    assert(home->suh_blocks);
    assert(home->suh_blocks->sub_ref == 1);
    assert(home->suh_blocks->sub_hauto);
Pekka Pessi's avatar
Pekka Pessi committed
1004
    _su_home_deinit(home);
1005 1006
    /* UNLOCK(home); */
  }
Pekka Pessi's avatar
Pekka Pessi committed
1007 1008 1009 1010
}

/**Move allocations from a su_home_t object to another.
 *
1011 1012 1013 1014 1015
 * Moves allocations made through the @a src home object under the @a dst
 * home object. It is handy, for example, if an operation allocates some
 * number of blocks that should be freed upon an error. It uses a temporary
 * home and moves the blocks from temporary to a proper home when
 * successful, but frees the temporary home upon an error.
Pekka Pessi's avatar
Pekka Pessi committed
1016
 *
1017
 * If @a src has destructor, it is called before starting to move.
1018
 *
Pekka Pessi's avatar
Pekka Pessi committed
1019 1020 1021 1022 1023 1024 1025 1026
 * @param dst destination home
 * @param src source home
 *
 * @retval 0 if succesful
 * @retval -1 upon an error
 */
int su_home_move(su_home_t *dst, su_home_t *src)
{
1027
  size_t i, n, n2, used;
Pekka Pessi's avatar
Pekka Pessi committed
1028 1029 1030 1031 1032 1033
  su_block_t *s, *d, *d2;

  if (src == NULL || dst == src)
    return 0;

  if (dst) {
1034
    s = MEMLOCK(src); d = MEMLOCK(dst);
Pekka Pessi's avatar
Pekka Pessi committed
1035 1036

    if (s && s->sub_n) {
1037 1038 1039 1040 1041 1042 1043

      if (s->sub_destructor) {
	void (*destructor)(void *) = s->sub_destructor;
	s->sub_destructor = NULL;
	destructor(src);
      }

Pekka Pessi's avatar
Pekka Pessi committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
      if (d) 
	used = s->sub_used + d->sub_used;
      else
	used = s->sub_used;

      if ((used && d == NULL) || 3 * used > 2 * d->sub_n) {
	if (d)
	  for (n = n2 = d->sub_n; 3 * used > 2 * n2; n2 = 4 * n2 + 3)
	    ;
	else
	  n = 0, n2 = s->sub_n;
1055 1056

	if (!(d2 = su_hash_alloc(n2))) {
Pekka Pessi's avatar
Pekka Pessi committed
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
	  UNLOCK(dst); UNLOCK(src);
	  return -1;
	}

	dst->suh_blocks = d2;

      	for (i = 0; i < n; i++)
	  if (d->sub_nodes[i].sua_data) 
	    su_block_add(d2, d->sub_nodes[i].sua_data)[0] = d->sub_nodes[i];

	if (d) {
	  d2->sub_parent = d->sub_parent;
1069
	  d2->sub_ref = d->sub_ref;
Pekka Pessi's avatar
Pekka Pessi committed
1070 1071 1072
	  d2->sub_preload = d->sub_preload;
	  d2->sub_prsize = d->sub_prsize;
	  d2->sub_prused = d->sub_prused;
Pekka Pessi's avatar
Pekka Pessi committed
1073
	  d2->sub_preauto = d->sub_preauto;
Pekka Pessi's avatar
Pekka Pessi committed
1074 1075 1076
	  d2->sub_stats = d->sub_stats;
	}

Pekka Pessi's avatar
Pekka Pessi committed
1077 1078 1079 1080
	if (d && !d->sub_auto)
	  free(d);

	d = d2;
Pekka Pessi's avatar
Pekka Pessi committed
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
      }

      if ((n = s->sub_n)) {
	for (i = 0; i < n; i++)
	  if (s->sub_nodes[i].sua_data) {
	    su_block_add(d, s->sub_nodes[i].sua_data)[0] = s->sub_nodes[i];
	  }

	s->sub_used = 0;

	memset(s->sub_nodes, 0, n * sizeof (s->sub_nodes[0]));
      }

      if (s->sub_stats) {
      }
    }

    UNLOCK(dst); UNLOCK(src);
  }
  else {
1101
    s = MEMLOCK(src); 
Pekka Pessi's avatar
Pekka Pessi committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115

    if (s && s->sub_used) {
      s->sub_used = 0;
      memset(s->sub_nodes, 0, s->sub_n * sizeof (s->sub_nodes[0]));
    }

    UNLOCK(src);
  }

  return 0;
}

/** Preload a memory home.
 *
1116
 * The function su_home_preload() preloads a memory home.
Pekka Pessi's avatar
Pekka Pessi committed
1117
 */
1118
void su_home_preload(su_home_t *home, isize_t n, isize_t isize)
Pekka Pessi's avatar
Pekka Pessi committed
1119 1120 1121 1122 1123 1124 1125 1126 1127
{
  su_block_t *sub;

  if (home == NULL)
    return;

  if (home->suh_blocks == NULL) 
    su_home_init(home);

1128
  sub = MEMLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
1129
  if (!sub->sub_preload) {
1130
    size_t size;
Pekka Pessi's avatar
Pekka Pessi committed
1131 1132 1133
    void *preload;

    size = n * ALIGN(isize);
1134 1135
    if (size > 65535)		/* We have 16 bits... */
      size = 65535 & (ALIGNMENT - 1);
Pekka Pessi's avatar
Pekka Pessi committed
1136 1137 1138 1139

    preload = malloc(size);

    home->suh_blocks->sub_preload = preload;
1140
    home->suh_blocks->sub_prsize = (unsigned)size;
Pekka Pessi's avatar
Pekka Pessi committed
1141 1142 1143 1144
  }
  UNLOCK(home);
}

Pekka Pessi's avatar
Pekka Pessi committed
1145 1146
/** Preload a memory home from stack.
 *
1147 1148
 * Initializes a memory home using an area allocated from stack. Poor man's
 * alloca().
Pekka Pessi's avatar
Pekka Pessi committed
1149
 */
1150
su_home_t *su_home_auto(void *area, isize_t size)
Pekka Pessi's avatar
Pekka Pessi committed
1151 1152 1153 1154
{
  su_home_t *home;
  su_block_t *sub;
  size_t homesize = ALIGN(sizeof *home);
1155
  size_t subsize = ALIGN(offsetof(su_block_t, sub_nodes[SUB_N_AUTO]));
1156
  size_t prepsize;
Pekka Pessi's avatar
Pekka Pessi committed
1157 1158 1159

  char *p = area;

1160 1161 1162
  prepsize = homesize + subsize + (ALIGN((intptr_t)p) - (intptr_t)p);

  if (area == NULL || size < prepsize)
Pekka Pessi's avatar
Pekka Pessi committed
1163 1164
    return NULL;

1165 1166 1167
  if (size > INT_MAX)
    size = INT_MAX;

Pekka Pessi's avatar
Pekka Pessi committed
1168
  home = memset(p, 0, homesize);
1169
  home->suh_size = (int)size;
Pekka Pessi's avatar
Pekka Pessi committed
1170 1171 1172 1173

  sub = memset(p + homesize, 0, subsize);
  home->suh_blocks = sub;

1174 1175 1176
  if (size > prepsize + 65535)
    size = prepsize + 65535;

1177
  sub->sub_n = SUB_N_AUTO;
1178
  sub->sub_ref = 1;
1179
  sub->sub_preload = p + prepsize;
1180
  sub->sub_prsize = (unsigned)(size - prepsize);
1181
  sub->sub_hauto = 1;
Pekka Pessi's avatar
Pekka Pessi committed
1182
  sub->sub_auto = 1;
1183
  sub->sub_preauto = 1;
Pekka Pessi's avatar
Pekka Pessi committed
1184 1185 1186 1187 1188 1189
  sub->sub_auto_all = 1;

  return home;
}


Pekka Pessi's avatar
Pekka Pessi committed
1190 1191
/** Reallocate a memory block.
 *
1192
 *   Allocates a memory block of @a size bytes.
Pekka Pessi's avatar
Pekka Pessi committed
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
 *   It copies the old block contents to the new block and frees the old
 *   block.
 *
 *   If @a home is NULL, this function behaves exactly like realloc().
 *
 *   @param home  pointer to memory pool object
 *   @param data  pointer to old memory block
 *   @param size  size of the memory block to be allocated
 *   
 * @return
1203
 *   A pointer to the allocated memory block or
Pekka Pessi's avatar
Pekka Pessi committed
1204 1205
 *   NULL if an error occurred.
 */
1206
void *su_realloc(su_home_t *home, void *data, isize_t size)
Pekka Pessi's avatar
Pekka Pessi committed
1207 1208 1209 1210
{
  void *ndata;
  su_alloc_t *sua;
  su_block_t *sub;
1211
  size_t p;
1212
  size_t term = 0 - size;
Pekka Pessi's avatar
Pekka Pessi committed
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

  if (!home) 
    return realloc(data, size);

  if (size == 0) {
    if (data)
      su_free(home, data);
    return NULL;
  }

1223
  sub = MEMLOCK(home);
1224 1225 1226 1227 1228 1229
  if (!data) {
    data = sub_alloc(home, sub, size, 0);
    UNLOCK(home);
    return data;
  }

Pekka Pessi's avatar
Pekka Pessi committed
1230 1231 1232 1233 1234
  sua = su_block_find(sub, data);

  if (!su_alloc_check(sub, sua))
    return UNLOCK(home);
  
1235 1236
  assert(!sua->sua_home);
  if (sua->sua_home)
Pekka Pessi's avatar
Pekka Pessi committed
1237 1238 1239 1240 1241 1242
    return UNLOCK(home);
  
  if (!su_is_preloaded(sub, data)) {
    ndata = realloc(data, size + MEMCHECK_EXTRA);
    if (ndata) {
      if (sub->sub_stats) {
1243 1244
	su_home_stats_free(sub, data, 0, sua->sua_size);
	su_home_stats_alloc(sub, data, 0, size, 1);
Pekka Pessi's avatar
Pekka Pessi committed
1245 1246 1247 1248 1249 1250 1251 1252 1253
      }

#if MEMCHECK_EXTRA
      memcpy((char *)ndata + size, &term, sizeof (term));
#else
      (void)term;
#endif
      memset(sua, 0, sizeof *sua);
      sub->sub_used--;
1254
      su_block_add(sub, ndata)->sua_size = (unsigned)size;
Pekka Pessi's avatar
Pekka Pessi committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    }
    UNLOCK(home);

    return ndata;
  }

  p = (char *)data - home->suh_blocks->sub_preload;
  p += sua->sua_size + MEMCHECK_EXTRA;
  p = ALIGN(p);

  if (p == sub->sub_prused) {
1266
    size_t p2 = (char *)data - sub->sub_preload + size + MEMCHECK_EXTRA;
Pekka Pessi's avatar
Pekka Pessi committed
1267 1268 1269
    p2 = ALIGN(p2);
    if (p2 <= sub->sub_prsize) {
      /* Extend/reduce existing preload */
1270 1271 1272 1273 1274
      if (sub->sub_stats) {
	su_home_stats_free(sub, data, data, sua->sua_size);
	su_home_stats_alloc(sub, data, data, size, 0);
      }

1275
      sub->sub_prused = (unsigned)p2;
1276
      sua->sua_size = (unsigned)size;
1277

Pekka Pessi's avatar
Pekka Pessi committed
1278 1279 1280 1281 1282 1283 1284
#if MEMCHECK_EXTRA
      memcpy((char *)data + size, &term, sizeof (term));
#endif
      UNLOCK(home);
      return data;
    }
  }
1285
  else if (size < (size_t)sua->sua_size) {
Pekka Pessi's avatar
Pekka Pessi committed
1286
    /* Reduce existing preload */
1287 1288 1289 1290
    if (sub->sub_stats) {
      su_home_stats_free(sub, data, data, sua->sua_size);
      su_home_stats_alloc(sub, data, data, size, 0);
    }
Pekka Pessi's avatar
Pekka Pessi committed
1291 1292 1293
#if MEMCHECK_EXTRA
    memcpy((char *)data + size, &term, sizeof (term));
#endif
1294
    sua->sua_size = (unsigned)size;
Pekka Pessi's avatar
Pekka Pessi committed
1295 1296 1297 1298 1299 1300 1301
    UNLOCK(home);
    return data;
  }

  ndata = malloc(size + MEMCHECK_EXTRA);

  if (ndata) {
1302
    if (p == sub->sub_prused) {
Pekka Pessi's avatar
Pekka Pessi committed
1303 1304
      /* Free preload */
      sub->sub_prused = (char *)data - home->suh_blocks->sub_preload;
1305 1306 1307
      if (sub->sub_stats)
	su_home_stats_free(sub, data, data, sua->sua_size);
    }
Pekka Pessi's avatar
Pekka Pessi committed
1308
    
1309 1310 1311 1312
    memcpy(ndata, data,
	   (size_t)sua->sua_size < size
	   ? (size_t)sua->sua_size
	   : size);
Pekka Pessi's avatar
Pekka Pessi committed
1313 1314 1315 1316
#if MEMCHECK_EXTRA
    memcpy((char *)ndata + size, &term, sizeof (term));
#endif

1317 1318
    if (sub->sub_stats)
      su_home_stats_alloc(sub, data, 0, size, 1);
Pekka Pessi's avatar
Pekka Pessi committed
1319 1320 1321

    memset(sua, 0, sizeof *sua); sub->sub_used--;

1322
    su_block_add(sub, ndata)->sua_size = (unsigned)size;
Pekka Pessi's avatar
Pekka Pessi committed
1323 1324 1325 1326 1327 1328 1329 1330
  }

  UNLOCK(home);

  return ndata;
}


1331 1332 1333 1334 1335 1336 1337 1338 1339
/**Check if a memory block has been allocated from the @a home.
 *
 * Check if the given memory block has been allocated from the home.
 *
 * @param home pointer to memory pool object
 * @param memory ponter to memory block
 *
 * @retval 1 if @a memory has been allocated from @a home.
 * @retval 0 otherwise
1340 1341
 *
 * @since New in @VERSION_1_12_4.
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
 */
int su_in_home(su_home_t *home, void const *memory)
{
  su_alloc_t *sua;
  su_block_t *sub;
  int retval = 0;

  if (!home || !memory)
    return 0;

  sub = MEMLOCK(home);

  if (sub) {
    sua = su_block_find(sub, memory);

    retval = su_alloc_check(sub, sua);

    UNLOCK(home);
  }
  
  return retval;
}


Pekka Pessi's avatar
Pekka Pessi committed
1366 1367
/**Allocate and zero a memory block.
 *
1368
 * Allocates a memory block with a given size from
Pekka Pessi's avatar
Pekka Pessi committed
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
 * given memory home @a home and zeroes the allocated block.
 *
 *  @param home  pointer to memory pool object
 *  @param size  size of the memory block
 *
 * @note The memory home pointer @a home may be @c NULL. In that case, the
 * allocated memory block is not associated with any memory home, and it
 * must be freed by calling su_free() or free().
 *
 * @return
 * The function su_zalloc() returns a pointer to the allocated memory block,
 * or NULL upon an error.
 */
1382
void *su_zalloc(su_home_t *home, isize_t size)
Pekka Pessi's avatar
Pekka Pessi committed
1383
{
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
  void *data;

  assert (size >= 0);

  if (home) {
    data = sub_alloc(home, MEMLOCK(home), size, 1);
    UNLOCK(home);
  }
  else
    data = calloc(1, size);

  return data;
Pekka Pessi's avatar
Pekka Pessi committed
1396 1397 1398 1399
}

/** Allocate a structure
 *
1400
 * Allocates a structure with a given size, zeros
Pekka Pessi's avatar
Pekka Pessi committed
1401
 * it, and initializes the size field to the given size.  The size field
1402
 * is an int at the beginning of the structure. Note that it has type of int. 
Pekka Pessi's avatar
Pekka Pessi committed
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
 *
 * @param home  pointer to memory pool object
 * @param size  size of the structure
 *
 * @par Example
 * The structure is defined and allocated as follows:
 * @code
 *   struct test {
 *     int   tst_size;
 *     char *tst_name;
 *     void *tst_ptr[3];
 *   };
 * 
 *   struct test *t;
 *   ...
 *   t = su_salloc(home, sizeof (*t)); 
 *   assert(t && t->t_size == sizeof (*t));
1420
 *   
Pekka Pessi's avatar
Pekka Pessi committed
1421 1422
 * @endcode
 * After calling su_salloc() we get a pointer t to a struct test,
1423 1424
 * initialized to zero except the tst_size field, which is initialized to
 * sizeof (*t).
Pekka Pessi's avatar
Pekka Pessi committed
1425
 *
1426
 * @return A pointer to the allocated structure, or NULL upon an error.
Pekka Pessi's avatar
Pekka Pessi committed
1427
 */
1428
void *su_salloc(su_home_t *home, isize_t size)
Pekka Pessi's avatar
Pekka Pessi committed
1429 1430 1431 1432 1433 1434
{
  struct { int size; } *retval;

  if (size < sizeof (*retval))
    size = sizeof (*retval);

1435 1436
  if (size > INT_MAX)
    return (void)(errno = ENOMEM), NULL;
Pekka Pessi's avatar
Pekka Pessi committed
1437

1438 1439 1440
  if (home) {
    retval = sub_alloc(home, MEMLOCK(home), size, 1);
    UNLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
1441
  }
1442 1443 1444 1445
  else
    retval = calloc(1, size);

  if (retval)
1446
    retval->size = (int)size;
Pekka Pessi's avatar
Pekka Pessi committed
1447 1448 1449 1450

  return retval;
}

1451 1452 1453 1454 1455 1456
/** Check if a memory home is threadsafe */
int su_home_is_threadsafe(su_home_t const *home)
{
  return home && home->suh_lock;
}

Pekka Pessi's avatar
Pekka Pessi committed
1457 1458 1459
/** Obtain exclusive lock on home (if home is threadsafe). */
int su_home_mutex_lock(su_home_t *home)
{
1460
  if (home == NULL)
1461
    return su_seterrno(EFAULT);
Pekka Pessi's avatar
Pekka Pessi committed
1462

1463 1464 1465 1466 1467 1468 1469 1470
  if (home->suh_lock) {
    su_home_ref(home);
    su_home_mutex_locker(home->suh_lock);
  }
  else if (home->suh_blocks) {
    if (!su_home_ref(home))
      return -1;
  }
Pekka Pessi's avatar
Pekka Pessi committed
1471 1472 1473 1474 1475 1476 1477

  return 0;
}

/** Release exclusive lock on home (if home is threadsafe) */
int su_home_mutex_unlock(su_home_t *home)
{
1478
  if (home == NULL)
1479
    return su_seterrno(EFAULT);
Pekka Pessi's avatar
Pekka Pessi committed
1480

1481 1482 1483 1484 1485 1486 1487
  if (home->suh_lock) {
    su_home_mutex_unlocker(home->suh_lock);
    su_home_unref(home);
  }
  else if (home->suh_blocks) {
    su_home_unref(home);
  }
Pekka Pessi's avatar
Pekka Pessi committed
1488 1489 1490 1491

  return 0;
}

1492

Pekka Pessi's avatar
Pekka Pessi committed
1493 1494 1495
/** Initialize statistics structure */
void su_home_init_stats(su_home_t *home)
{
1496
  su_block_t *sub;
1497
  size_t size;
Pekka Pessi's avatar
Pekka Pessi committed
1498