su_alloc.c 36.1 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 32 33 34 35 36 37 38 39
 * 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
 *
 */

/**@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
 */

#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
40 41 42
 * 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
43 44
 *
 * Typically, there is a @e home @e object which contains a su_home_t
45 46
 * structure in the beginning of the object (sort of inheritance from
 * su_home_t):
Pekka Pessi's avatar
Pekka Pessi committed
47 48 49 50 51 52 53 54
 * @code
 * struct context {
 *   su_home_t ctx_home[1];
 *   other_t  *ctx_stuff;
 *   ...
 * }
 * @endcode
 * 
55 56 57 58 59 60 61 62
 * 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
63 64 65 66
 * @code
 * struct context *ctx = su_home_clone(tophome, sizeof (struct context));
 * @endcode
 *
67 68
 * Note that the tophome has a reference to @a ctx structure; whenever
 * tophome is freed, the @a ctx is also freed.
69 70
 * 
 * You can also create an independent home object by passing NULL as @a
71
 * tophome argument. This is identical to the call to su_home_new().
Pekka Pessi's avatar
Pekka Pessi committed
72
 *
73
 * The memory allocations using @a ctx proceed then as follows:
Pekka Pessi's avatar
Pekka Pessi committed
74
 * @code
75
 *    zeroblock = su_zalloc(ctx->ctx_home, sizeof (*zeroblock));
Pekka Pessi's avatar
Pekka Pessi committed
76 77 78
 * @endcode
 *
 * The home memory pool - the home object and all the memory blocks
79
 * allocated using it - are freed when su_home_unref() is called:
Pekka Pessi's avatar
Pekka Pessi committed
80 81
 *
 * @code
82
 *    su_home_unref(ctx->ctx_home).
Pekka Pessi's avatar
Pekka Pessi committed
83 84
 * @endcode
 *
85 86 87 88 89 90 91 92
 * @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
 * count, su_home_unref() decreases. A newly allocated home object has
 * reference count of 1.
 *
93 94 95 96
 * @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.
97 98 99
 *
 * 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
100 101 102 103 104
 * @code
 *    su_free(tophome, ctx);
 * @endcode
 * 
 * @note 
105 106 107
 * The su_home_create() and su_home_destroy() are deprecated. The
 * function su_home_create() creates a home object with infinite reference
 * count. Likewise, su_home_init() does the same.
Pekka Pessi's avatar
Pekka Pessi committed
108
 *
109 110 111 112 113 114 115 116 117
 * @section su_home_desctructor_usage Destructors
 *
 * 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
 * stack-derived objects).
 *
Pekka Pessi's avatar
Pekka Pessi committed
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 146 147 148
 * @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
 * @c threadsafe by calling su_home_threadsafe() with the home pointer as
149
 * argument. The threadsafeness is not inherited by clones.
150 151 152
 *
 * The threadsafe home objects can be locked and unlocked with
 * su_home_mutex_lock() and su_home_mutex_unlock().
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
 *
 * @section su_alloc_preloading Preloading a Memory Home
 *
 * In some situations there is quite heavy overhead when using the global
 * heap allocator. The overhead caused by the large number of small
 * 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
 * preloaded memory area is then used to satisfy small enough allocations.
 * 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
 * initialized with su_home_auto() must be explicitly deinitialized with
 * su_home_deinit() when the program exits the scope where the stack frame
 * used in su_home_auto() was allocate.
 * 
Pekka Pessi's avatar
Pekka Pessi committed
176 177
 */

178 179 180 181
#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"
182

Pekka Pessi's avatar
Pekka Pessi committed
183 184 185 186 187 188 189 190 191 192
#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);

193 194 195 196
void (*su_home_mutex_locker)(void *mutex);
void (*su_home_mutex_unlocker)(void *mutex);

#define MEMLOCK(h)   \
Pekka Pessi's avatar
Pekka Pessi committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  (((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)
#define MEMCHECK_EXTRA sizeof (unsigned)
#endif

enum { 
  SUB_N = 31,			/**< Initial size */
213
  SUB_N_AUTO = 7,		/**< Initial size for autohome */
Pekka Pessi's avatar
Pekka Pessi committed
214 215 216 217 218 219 220 221 222 223
  SUB_P = 29			/**< Secondary probe.
				 * Secondary probe must be relative prime 
				 * with all sub_n values */
};		

#define ALIGNMENT (8)
#define ALIGN(n)  (((n) + (ALIGNMENT - 1)) & ~(ALIGNMENT - 1))
#define SIZEBITS (sizeof (unsigned) * 8 - 1)

typedef struct {
224 225 226
  unsigned long sua_size:SIZEBITS; /**< Size of the block */
  unsigned sua_home:1;		/**< Is this another home? */
  void    *sua_data;		/**< Data pointer */
Pekka Pessi's avatar
Pekka Pessi committed
227 228 229
} su_alloc_t;

struct su_block_s {
230
  su_home_t  *sub_parent;	/**< Parent home */
231 232
  char       *sub_preload;	/**< Preload area */
  su_home_stat_t *sub_stats;	/**< Statistics.. */
233
  void      (*sub_destructor)(void *); /**< Destructor function */
234
  unsigned    sub_ref;		/**< Reference count */
Pekka Pessi's avatar
Pekka Pessi committed
235 236
  unsigned    sub_used;		/**< Number of blocks allocated */
  unsigned    sub_n;		/**< Size of hash table  */
Pekka Pessi's avatar
Pekka Pessi committed
237 238 239

  unsigned    sub_prsize:16;	/**< Preload size */
  unsigned    sub_prused:16;	/**< Used from preload */
240
  unsigned    sub_auto:1;	/**< struct su_block_s is from stack! */
Pekka Pessi's avatar
Pekka Pessi committed
241 242 243
  unsigned    sub_preauto:1;	/**< Preload is from stack! */
  unsigned    sub_auto_all:1;	/**< Everything is from stack! */
  unsigned :0;
244

Pekka Pessi's avatar
Pekka Pessi committed
245 246 247 248 249
  su_alloc_t  sub_nodes[SUB_N];	/**< Pointers to data/lower blocks */
};

static void su_home_check_blocks(su_block_t const *b);

250 251 252 253
static void su_home_stats_alloc(su_block_t *, void *p, void *preload,
				unsigned size, int zero);
static void su_home_stats_free(su_block_t *sub, void *p, void *preload,
			       unsigned size);
Pekka Pessi's avatar
Pekka Pessi committed
254

255 256
static void _su_home_deinit(su_home_t *home);

Pekka Pessi's avatar
Pekka Pessi committed
257 258 259 260 261 262 263 264 265 266 267 268
#define SU_ALLOC_STATS 1

#if SU_ALLOC_STATS
unsigned count_su_block_find, count_su_block_find_loop;
unsigned size_su_block_find, used_su_block_find;
unsigned max_size_su_block_find, max_used_su_block_find;
unsigned su_block_find_collision, su_block_find_collision_used, 
  su_block_find_collision_size;
#endif

static inline su_alloc_t *su_block_find(su_block_t *b, void *p)
{
269
  unsigned h, h0, probe;
Pekka Pessi's avatar
Pekka Pessi committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

#if SU_ALLOC_STATS  
  unsigned collision = 0;

  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);

  h = h0 = ((unsigned long)p) % b->sub_n;

287 288
  probe = (b->sub_n > SUB_P) ? SUB_P : 1;

Pekka Pessi's avatar
Pekka Pessi committed
289 290 291
  do {
    if (b->sub_nodes[h].sua_data == p)
      return &b->sub_nodes[h];
292
    h += probe;
Pekka Pessi's avatar
Pekka Pessi committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    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;
}

static inline su_alloc_t *su_block_add(su_block_t *b, void *p)
{
309
  unsigned h, probe;
Pekka Pessi's avatar
Pekka Pessi committed
310 311 312 313 314

  assert(p != NULL);

  h = ((unsigned long)p) % b->sub_n;

315 316
  probe = (b->sub_n > SUB_P) ? SUB_P : 1;

Pekka Pessi's avatar
Pekka Pessi committed
317
  while (b->sub_nodes[h].sua_data) {
318
    h += probe;
Pekka Pessi's avatar
Pekka Pessi committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    if (h >= b->sub_n)
      h -= b->sub_n;
  }

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

  return &b->sub_nodes[h];
}

static inline int su_is_preloaded(su_block_t const *sub, char *data)
{
  return
    sub->sub_preload && 
    sub->sub_preload <= data && 
    sub->sub_preload + sub->sub_prsize > data;
}

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

/** Allocate the block hash table.
 *
 * The function su_hash_alloc() allocates a block hash table of @a n
 * elements.
 *
 * @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.
 */
366
static inline su_block_t *su_hash_alloc(int n)
Pekka Pessi's avatar
Pekka Pessi committed
367
{
368
  su_block_t *b = calloc(1, offsetof(su_block_t, sub_nodes[n]));
Pekka Pessi's avatar
Pekka Pessi committed
369

Pekka Pessi's avatar
Pekka Pessi committed
370
  if (b)
Pekka Pessi's avatar
Pekka Pessi committed
371 372 373 374 375
    b->sub_n = n;

  return b;
}

376 377
enum sub_zero { do_malloc, do_calloc, do_clone };

Pekka Pessi's avatar
Pekka Pessi committed
378 379
/** Allocate a memory block.
 *
380
 * Precondition: locked home
Pekka Pessi's avatar
Pekka Pessi committed
381
 *
382 383 384 385 386
 * @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
387 388
 *
 */
389 390 391 392
static 
void *sub_alloc(su_home_t *home, 
		su_block_t *sub,
		long size, 
393
		enum sub_zero zero)
Pekka Pessi's avatar
Pekka Pessi committed
394
{
Pekka Pessi's avatar
Pekka Pessi committed
395
  void *data, *preload = NULL;
396 397
  
  assert (size >= 0);
Pekka Pessi's avatar
Pekka Pessi committed
398 399

  if (sub == NULL || 3 * sub->sub_used > 2 * sub->sub_n) {
400
    /* Resize the hash table */
Pekka Pessi's avatar
Pekka Pessi committed
401 402 403 404 405 406 407 408
    int i, n, n2, used;
    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
409 410 411
#if 0
    printf("su_alloc(home = %p): realloc block hash of size %d\n", home, n2);
#endif
Pekka Pessi's avatar
Pekka Pessi committed
412

413 414
    if (!(b2 = su_hash_alloc(n2)))
      return NULL;
Pekka Pessi's avatar
Pekka Pessi committed
415 416 417 418 419 420 421 422

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

    if (sub) {
      b2->sub_parent = sub->sub_parent;
423
      b2->sub_ref = sub->sub_ref;
Pekka Pessi's avatar
Pekka Pessi committed
424 425 426
      b2->sub_preload = sub->sub_preload;
      b2->sub_prsize = sub->sub_prsize;
      b2->sub_prused = sub->sub_prused;
Pekka Pessi's avatar
Pekka Pessi committed
427
      b2->sub_preauto = sub->sub_preauto;
428
      b2->sub_destructor = sub->sub_destructor;
429
      /* auto_all is not copied! */
Pekka Pessi's avatar
Pekka Pessi committed
430 431 432
      b2->sub_stats = sub->sub_stats;
    }

433 434
    home->suh_blocks = b2;

Pekka Pessi's avatar
Pekka Pessi committed
435 436 437
    if (sub && !sub->sub_auto)
      free(sub);
    sub = b2;
Pekka Pessi's avatar
Pekka Pessi committed
438 439
  }

440
  if (size && sub && zero < do_clone &&
441
      sub->sub_preload && size <= sub->sub_prsize) {
442
    /* Use preloaded memory */
443
    size_t prused = sub->sub_prused + size + MEMCHECK_EXTRA; 
444 445
    prused = ALIGN(prused);
    if (prused <= sub->sub_prsize) {
Pekka Pessi's avatar
Pekka Pessi committed
446
      preload = (char *)sub->sub_preload + sub->sub_prused;
447
      sub->sub_prused = prused;
Pekka Pessi's avatar
Pekka Pessi committed
448 449
    }
  }
450

451
  if (preload && zero)
Pekka Pessi's avatar
Pekka Pessi committed
452
    data = memset(preload, 0, size);
453
  else if (preload)
Pekka Pessi's avatar
Pekka Pessi committed
454
    data = preload;
455 456
  else if (zero)
    data = calloc(1, size + MEMCHECK_EXTRA);
Pekka Pessi's avatar
Pekka Pessi committed
457 458 459 460
  else
    data = malloc(size + MEMCHECK_EXTRA);

  if (data) {
461 462
    su_alloc_t *sua;

Pekka Pessi's avatar
Pekka Pessi committed
463 464 465 466 467
#if MEMCHECK_EXTRA
    int term = -size;
    memcpy((char *)data + size, &term, sizeof (term));
#endif

468 469 470
    if (!preload)
      sub->sub_auto_all = 0;

471
    if (zero == do_clone) {
472
      /* Prepare cloned home */ 
473 474 475 476 477 478 479
      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;
480 481

      subhome->suh_size = size;
482
      subhome->suh_blocks->sub_parent = home;
483
      subhome->suh_blocks->sub_ref = 1;
484 485
    }

486 487
    /* OK, add the block to the hash table. */

488 489 490
    sua = su_block_add(sub, data); assert(sua);
    sua->sua_size = size;
    sua->sua_home = zero > 1;
Pekka Pessi's avatar
Pekka Pessi committed
491 492

    if (sub->sub_stats)
493
      su_home_stats_alloc(sub, data, preload, size, zero);
Pekka Pessi's avatar
Pekka Pessi committed
494 495
  }

496 497 498 499 500 501 502
  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
503
 * either when this home is destroyed.
504 505 506
 *
 * @param size    size of home object
 *
507
 * The memory home object allocated with su_home_new() can be reclaimed with
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
 * su_home_unref().
 *
 * @return
 * This function returns a pointer to an su_home_t object, or NULL upon
 * an error.
 */
void *su_home_new(int size)
{
  su_home_t *home;

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

  if (size < sizeof (*home))
    return NULL;

  home = calloc(1, size);
  if (home) {
525
    home->suh_size = size;
526 527 528 529 530 531 532 533 534 535 536
    home->suh_blocks = su_hash_alloc(SUB_N);
    if (home->suh_blocks)
      home->suh_blocks->sub_ref = 1;
    else
      free(home), home = NULL;
  }

  return home;
}

/** Create a new reference to a home object. */
537
void *su_home_ref(su_home_t const *home)
538 539 540 541 542 543 544 545 546 547 548 549 550 551
{
  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;
    }
    
    if (sub->sub_ref != UINT_MAX)
      sub->sub_ref++;
    UNLOCK(home);
  }
552 553
  else
    su_seterrno(EFAULT);
554

555
  return (void *)home;
556 557
}

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
/** Set destructor function */
SU_DLL int su_home_desctructor(su_home_t *home, void (*destructor)(void *))
{
  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;
}


578 579 580 581 582
/**Unreference a su_home_t object.
 *
 * The function su_home_unref() decrements the reference count on a home
 * object and destroys and frees it and the memory allocations using it.
 *
583 584 585 586 587 588
 * @param home memory pool object to be unreferences
 *
 * The function return values is 
 *
 * @retval 1 if object was freed
 * @retval 0 if object is still alive
589
 */
590
int su_home_unref(su_home_t *home)
591 592 593 594
{
  su_block_t *sub;

  if (home == NULL)
595
    return 0;
596 597 598 599 600

  sub = MEMLOCK(home);

  if (sub == NULL) {
    /* Xyzzy */
601
    return 0;
602 603 604
  }
  else if (sub->sub_ref == UINT_MAX) {
    UNLOCK(home);
605
    return 0;
606 607 608
  }
  else if (--sub->sub_ref > 0) {
    UNLOCK(home);
609 610 611 612 613 614 615
    return 0;
  }
  else if (sub->sub_parent) {
    su_home_t *parent = sub->sub_parent;
    UNLOCK(home);
    su_free(parent, home);
    return 1;
616 617 618 619 620
  }
  else {
    _su_home_deinit(home);
    free(home);
    /* UNLOCK(home); */
621
    return 1;
622 623 624 625 626 627 628 629
  }
}


/**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
630
 * home is destroyed or when the parent home is destroyed.
631 632 633 634 635 636 637
 *
 * 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
 *
638
 * The memory home object allocated with su_home_clone() can be freed with
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
 * su_home_unref().
 *
 * @return
 * This function returns a pointer to an su_home_t object, or NULL upon
 * an error.
 */
void *su_home_clone(su_home_t *parent, int size)
{
  su_home_t *home;

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

  if (size < sizeof (*home))
    return NULL;

  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.
 *
 * The function su_alloc() allocates a memory block of a given @a size.
 *
 * 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.
 */
void *su_alloc(su_home_t *home, int size)
{
  void *data;

  if (home) {
691
    data = sub_alloc(home, MEMLOCK(home), size, 0);
692 693 694 695
    UNLOCK(home);
  }
  else
    data = malloc(size);
Pekka Pessi's avatar
Pekka Pessi committed
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

  return data;
}

/**Free a memory block.
 *
 * The function su_free() 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).
 *
 * @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;
713
    su_block_t *sub = MEMLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
714 715 716 717 718 719

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

    if (su_alloc_check(sub, allocation)) {
720 721 722 723 724
      void *preloaded = NULL;

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

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

729 730 731 732 733 734 735 736 737 738 739
      if (allocation->sua_home) {
	su_home_t *subhome = data;
	su_block_t *sub = MEMLOCK(subhome);

	assert(sub->sub_ref != UINT_MAX);
	/* assert(sub->sub_ref > 0); */

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

	_su_home_deinit(subhome);
      }
Pekka Pessi's avatar
Pekka Pessi committed
740 741 742 743 744 745 746

#if MEMCHECK != 0
      memset(data, 0xaa, allocation->sua_size);
#endif

      memset(allocation, 0, sizeof (*allocation));
      sub->sub_used--;
747 748 749

      if (preloaded)
	data = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    }

    UNLOCK(home);
  }

  free(data);
}

/** Check home consistency.
 *
 * The function su_home_check() 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.
 *
 * @param home Pointer to a memory home.
 */
void su_home_check(su_home_t const *home)
{
#if MEMCHECK != 0
769
  su_block_t const *b = MEMLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

  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) {
    unsigned i, used;
    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++;
789
	if (b->sub_nodes[i].sua_home)
Pekka Pessi's avatar
Pekka Pessi committed
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
	  su_home_check((su_home_t *)b->sub_nodes[i].sua_data);
      }

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

/**
 * Create an su_home_t object.
 *
 * The function su_home_create() 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_destroy().
 *
 * @return This function returns a pointer to an @c su_home_t object, or @c
 * NULL upon an error. 
 *
 * @deprecated
 * Use su_home_clone() instead of su_home_create().
 */
su_home_t *su_home_create(void)
{
  su_home_t *home = su_salloc(NULL, sizeof (*home));

  if (home) {
    su_home_init(home);
  }

  return home;
}

/** Deinitialize a home object
 *
 *   The function su_home_destroy() frees a home object, and all memory
 *   blocks associated with it.
 *
 *   @param home pointer to a home object
 *
 * @deprecated
830
 * Use su_home_deinit() instead of su_home_destroy().
Pekka Pessi's avatar
Pekka Pessi committed
831 832 833 834 835 836 837 838 839
 */
void su_home_destroy(su_home_t *home)
{
  su_home_deinit(home);
  /* free(home); - what if this is cloned one? */
}

/** Initialize an su_home_t object.
 *
840
 * The function su_home_init() initializes an object derived from su_home_t.
Pekka Pessi's avatar
Pekka Pessi committed
841 842 843 844 845 846 847 848 849 850 851 852
 *
 * @param home pointer to home object
 *
 * @return
 *    The function su_home_init() returns 0 when successful,
 *    or -1 upon an error.
 */
int su_home_init(su_home_t *home)
{
  if (home == NULL)
    return -1;

853
  home->suh_blocks = su_hash_alloc(SUB_N);
Pekka Pessi's avatar
Pekka Pessi committed
854

855
  return 0;
Pekka Pessi's avatar
Pekka Pessi committed
856 857 858 859 860 861
}

/** Internal deinitialization */
static
void _su_home_deinit(su_home_t *home)
{
862
  if (home->suh_blocks) {
Pekka Pessi's avatar
Pekka Pessi committed
863 864 865
    unsigned i;
    su_block_t *b;

866
     if (home->suh_blocks->sub_destructor) {
867 868 869 870 871
      void (*destructor)(void *) = home->suh_blocks->sub_destructor;
      home->suh_blocks->sub_destructor = NULL;
      destructor(home);
    }

Pekka Pessi's avatar
Pekka Pessi committed
872 873 874 875 876 877
    b = home->suh_blocks;

    su_home_check_blocks(b);

    for (i = 0; i < b->sub_n; i++) {
      if (b->sub_nodes[i].sua_data) {
878 879
	if (b->sub_nodes[i].sua_home) {
	  su_home_t *subhome = b->sub_nodes[i].sua_data;
880 881 882 883 884 885 886 887 888 889
	  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);
890 891 892 893
	}
	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
894 895 896
      }
    }

Pekka Pessi's avatar
Pekka Pessi committed
897
    if (b->sub_preload && !b->sub_preauto)
Pekka Pessi's avatar
Pekka Pessi committed
898 899 900
      free(b->sub_preload);
    if (b->sub_stats)
      free(b->sub_stats);
Pekka Pessi's avatar
Pekka Pessi committed
901 902
    if (!b->sub_auto)
      free(b);
Pekka Pessi's avatar
Pekka Pessi committed
903 904 905 906

    home->suh_blocks = NULL;
  }

907
  home->suh_lock = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
908 909 910 911 912 913 914 915 916 917 918
}

/** Free memory blocks allocated through home.
 *
 * The function @c su_home_deinit() frees the memory blocks associated with
 * the home object.
 *
 * @param home pointer to home object
 */
void su_home_deinit(su_home_t *home)
{
919 920
  if (MEMLOCK(home)) {
    assert(home->suh_blocks && home->suh_blocks->sub_ref == 0);
Pekka Pessi's avatar
Pekka Pessi committed
921
    _su_home_deinit(home);
922 923
    /* UNLOCK(home); */
  }
Pekka Pessi's avatar
Pekka Pessi committed
924 925 926 927 928 929 930 931 932 933
}

/**Move allocations from a su_home_t object to another.
 *
 * The function su_home_move() 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.
 *
934
 * If @a src has destructor, it is called before starting to move.
935
 *
Pekka Pessi's avatar
Pekka Pessi committed
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
 * @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)
{
  unsigned i, n, n2, used;
  su_block_t *s, *d, *d2;

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

  if (dst) {
951
    s = MEMLOCK(src); d = MEMLOCK(dst);
Pekka Pessi's avatar
Pekka Pessi committed
952 953

    if (s && s->sub_n) {
954 955 956 957 958 959 960

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

Pekka Pessi's avatar
Pekka Pessi committed
961 962 963 964 965 966 967 968 969 970 971
      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;
972 973

	if (!(d2 = su_hash_alloc(n2))) {
Pekka Pessi's avatar
Pekka Pessi committed
974 975 976 977 978 979 980 981 982 983 984 985
	  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;
986
	  d2->sub_ref = d->sub_ref;
Pekka Pessi's avatar
Pekka Pessi committed
987 988 989
	  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
990
	  d2->sub_preauto = d->sub_preauto;
Pekka Pessi's avatar
Pekka Pessi committed
991 992 993
	  d2->sub_stats = d->sub_stats;
	}

Pekka Pessi's avatar
Pekka Pessi committed
994 995 996 997
	if (d && !d->sub_auto)
	  free(d);

	d = d2;
Pekka Pessi's avatar
Pekka Pessi committed
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
      }

      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 {
1018
    s = MEMLOCK(src); 
Pekka Pessi's avatar
Pekka Pessi committed
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

    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.
 *
1033
 * The function su_home_preload() preloads a memory home.
Pekka Pessi's avatar
Pekka Pessi committed
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
 */
void su_home_preload(su_home_t *home, int n, int isize)
{
  su_block_t *sub;

  if (home == NULL)
    return;

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

1045
  sub = MEMLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
  if (!sub->sub_preload) {
    int size;
    void *preload;

    size = n * ALIGN(isize);
    if (size > USHRT_MAX)
      size = USHRT_MAX & (ALIGNMENT - 1);

    preload = malloc(size);

    home->suh_blocks->sub_preload = preload;
    home->suh_blocks->sub_prsize = size;
  }
  UNLOCK(home);
}

Pekka Pessi's avatar
Pekka Pessi committed
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
/** Preload a memory home from stack.
 *
 * The function su_home_auto() initalizes a memory home using an area
 * allocated from stack. Poor mans alloca().
 */
su_home_t *su_home_auto(void *area, int size)
{
  su_home_t *home;
  su_block_t *sub;
  size_t homesize = ALIGN(sizeof *home);
1072
  size_t subsize = ALIGN(offsetof(su_block_t, sub_nodes[SUB_N_AUTO]));
1073
  size_t prepsize;
Pekka Pessi's avatar
Pekka Pessi committed
1074 1075 1076

  char *p = area;

1077 1078 1079
  prepsize = homesize + subsize + (ALIGN((intptr_t)p) - (intptr_t)p);

  if (area == NULL || size < prepsize)
Pekka Pessi's avatar
Pekka Pessi committed
1080 1081 1082 1083 1084 1085 1086 1087
    return NULL;

  home = memset(p, 0, homesize);
  home->suh_size = size;

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

1088
  sub->sub_n = SUB_N_AUTO;
1089 1090
  sub->sub_preload = p + prepsize;
  sub->sub_prsize = size - prepsize;
Pekka Pessi's avatar
Pekka Pessi committed
1091 1092 1093 1094 1095 1096 1097 1098
  sub->sub_preauto = 1;
  sub->sub_auto = 1;
  sub->sub_auto_all = 1;

  return home;
}


Pekka Pessi's avatar
Pekka Pessi committed
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
/** Reallocate a memory block.
 *
 *   The function su_realloc() allocates a memory block of @a size bytes.
 *   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
 *   This function returns a pointer to the allocated memory block or
 *   NULL if an error occurred.
 */
void *su_realloc(su_home_t *home, void *data, int size)
{
  void *ndata;
  su_alloc_t *sua;
  su_block_t *sub;
  int p;
  int term = -size;

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

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

1132
  sub = MEMLOCK(home);
1133 1134 1135 1136 1137 1138
  if (!data) {
    data = sub_alloc(home, sub, size, 0);
    UNLOCK(home);
    return data;
  }

Pekka Pessi's avatar
Pekka Pessi committed
1139 1140 1141 1142 1143
  sua = su_block_find(sub, data);

  if (!su_alloc_check(sub, sua))
    return UNLOCK(home);
  
1144 1145
  assert(!sua->sua_home);
  if (sua->sua_home)
Pekka Pessi's avatar
Pekka Pessi committed
1146 1147 1148 1149 1150 1151
    return UNLOCK(home);
  
  if (!su_is_preloaded(sub, data)) {
    ndata = realloc(data, size + MEMCHECK_EXTRA);
    if (ndata) {
      if (sub->sub_stats) {
1152 1153
	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
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
      }

#if MEMCHECK_EXTRA
      memcpy((char *)ndata + size, &term, sizeof (term));
#else
      (void)term;
#endif
      memset(sua, 0, sizeof *sua);
      sub->sub_used--;
      su_block_add(sub, ndata)->sua_size = size;
    }
    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) {
    int p2 = (char *)data - sub->sub_preload + size + MEMCHECK_EXTRA;
    p2 = ALIGN(p2);
    if (p2 <= sub->sub_prsize) {
      /* Extend/reduce existing preload */
1179 1180 1181 1182 1183
      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
1184 1185
      sub->sub_prused = p2;
      sua->sua_size = size;
1186

Pekka Pessi's avatar
Pekka Pessi committed
1187 1188 1189 1190 1191 1192 1193 1194 1195
#if MEMCHECK_EXTRA
      memcpy((char *)data + size, &term, sizeof (term));
#endif
      UNLOCK(home);
      return data;
    }
  }
  else if (size < sua->sua_size) {
    /* Reduce existing preload */
1196 1197 1198 1199
    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
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
#if MEMCHECK_EXTRA
    memcpy((char *)data + size, &term, sizeof (term));
#endif
    sua->sua_size = size;
    UNLOCK(home);
    return data;
  }

  ndata = malloc(size + MEMCHECK_EXTRA);

  if (ndata) {
1211
    if (p == sub->sub_prused) {
Pekka Pessi's avatar
Pekka Pessi committed
1212 1213
      /* Free preload */
      sub->sub_prused = (char *)data - home->suh_blocks->sub_preload;
1214 1215 1216
      if (sub->sub_stats)
	su_home_stats_free(sub, data, data, sua->sua_size);
    }
Pekka Pessi's avatar
Pekka Pessi committed
1217 1218 1219 1220 1221 1222
    
    memcpy(ndata, data, sua->sua_size < size ? sua->sua_size : size);
#if MEMCHECK_EXTRA
    memcpy((char *)ndata + size, &term, sizeof (term));
#endif

1223 1224
    if (sub->sub_stats)
      su_home_stats_alloc(sub, data, 0, size, 1);
Pekka Pessi's avatar
Pekka Pessi committed
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254

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

    su_block_add(sub, ndata)->sua_size = size;
  }

  UNLOCK(home);

  return ndata;
}


/**Allocate and zero a memory block.
 *
 * The function su_zalloc() allocates a memory block with a given size from
 * 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.
 */
void *su_zalloc(su_home_t *home, int  size)
{
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
  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
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
}

/** Allocate a structure
 *
 * The function su_salloc() allocates a structure with a given size, zeros
 * it, and initializes the size field to the given size.  The size field
 * is the first in the structure.
 *
 * @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));
 *   t->name
 * @endcode
 * After calling su_salloc() we get a pointer t to a struct test,
 * initialized to zero except the 
 *
 *
 * @return This function returns a pointer to the allocated structure, or
 * NULL upon an error.
 */
void *su_salloc(su_home_t *home, int size)
{
  struct { int size; } *retval;

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

1307
  assert (size >= 0);
Pekka Pessi's avatar
Pekka Pessi committed
1308

1309 1310 1311
  if (home) {
    retval = sub_alloc(home, MEMLOCK(home), size, 1);
    UNLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
1312
  }
1313 1314 1315 1316 1317
  else
    retval = calloc(1, size);

  if (retval)
    retval->size = size;
Pekka Pessi's avatar
Pekka Pessi committed
1318 1319 1320 1321

  return retval;
}

1322 1323 1324 1325 1326 1327
/** 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
1328 1329 1330
/** Obtain exclusive lock on home (if home is threadsafe). */
int su_home_mutex_lock(su_home_t *home)
{
1331
  if (home == NULL)
1332
    return su_seterrno(EFAULT);
Pekka Pessi's avatar
Pekka Pessi committed
1333

1334 1335 1336 1337 1338 1339 1340 1341
  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
1342 1343 1344 1345 1346 1347 1348

  return 0;
}

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

1352 1353 1354 1355 1356 1357 1358
  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
1359 1360 1361 1362 1363 1364 1365

  return 0;
}

/** Initialize statistics structure */
void su_home_init_stats(su_home_t *home)
{
1366
  su_block_t *sub;
Pekka Pessi's avatar
Pekka Pessi committed
1367 1368
  int size;

1369 1370 1371 1372 1373
  if (home == NULL)
    return;

  sub = home->suh_blocks;

Pekka Pessi's avatar
Pekka Pessi committed
1374
  if (!sub)
1375
    sub = home->suh_blocks = su_hash_alloc(SUB_N);
Pekka Pessi's avatar
Pekka Pessi committed
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
  if (!sub)
    return;

  if (!sub->sub_stats) {
    size = sizeof (*sub->sub_stats);
    sub->sub_stats = malloc(size);
    if (!sub->sub_stats)
      return;
  }
  else
    size = sub->sub_stats->hs_size;
  
  memset(sub->sub_stats, 0, size);
  sub->sub_stats->hs_size = size;
  sub->sub_stats->hs_blocksize = sub->sub_n;
}

/** Retrieve statistics from memory home.
 */
1395 1396 1397
void su_home_get_stats(su_home_t *home, int include_clones, 
		       su_home_stat_t hs[1],
		       int size)
Pekka Pessi's avatar
Pekka Pessi committed
1398
{
1399 1400 1401 1402
  su_block_t *sub;

  if (hs == NULL || size < (sizeof hs->hs_size))
    return;
Pekka Pessi's avatar
Pekka Pessi committed
1403 1404 1405

  memset(hs, 0, size);

1406
  sub = MEMLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
1407

1408 1409
  if (sub && sub->sub_stats) {
    int sub_size = sub->sub_stats->hs_size;
Pekka Pessi's avatar
Pekka Pessi committed
1410 1411
    if (sub_size > size)
      sub_size = size;
1412 1413 1414
    sub->sub_stats->hs_preload.hsp_size = sub->sub_prsize;
    sub->sub_stats->hs_preload.hsp_used = sub->sub_prused;
    memcpy(hs, sub->sub_stats, sub_size);
Pekka Pessi's avatar
Pekka Pessi committed
1415 1416
    hs->hs_size = size;
  }
1417 1418

  UNLOCK(home);
Pekka Pessi's avatar
Pekka Pessi committed
1419 1420 1421
}

static 
1422 1423
void su_home_stats_alloc(su_block_t *sub, void *p, void *preload,
			 unsigned size, int zero)
Pekka Pessi's avatar
Pekka Pessi committed
1424 1425 1426 1427 1428 1429 1430 1431
{
  su_home_stat_t *hs = sub->sub_stats;

  unsigned rsize = ALIGN(size);

  hs->hs_rehash += (sub->sub_n != hs->hs_blocksize);
  hs->hs_blocksize = sub->sub_n;

1432 1433 1434 1435 1436 1437 1438
  hs->hs_clones += zero > 1;

  if (preload) {
    hs->hs_allocs.hsa_preload++;
    return;
  }

Pekka Pessi's avatar
Pekka Pessi committed
1439 1440 1441 1442 1443
  hs->hs_allocs.hsa_number++;
  hs->hs_allocs.hsa_bytes += size;
  hs->hs_allocs.hsa_rbytes += rsize;
  if (hs->hs_allocs.hsa_rbytes > hs->hs_allocs.hsa_maxrbytes)
    hs->hs_allocs.hsa_maxrbytes = hs->hs_allocs.hsa_rbytes;
1444
  
Pekka Pessi's avatar
Pekka Pessi committed
1445 1446 1447 1448 1449 1450
  hs->hs_blocks.hsb_number++;
  hs->hs_blocks.hsb_bytes += size;
  hs->hs_blocks.hsb_rbytes += rsize;
}

static 
1451
void su_home_stats_free(su_block_t *sub, void *p, void *preload, unsigned size)
Pekka Pessi's avatar
Pekka Pessi committed
1452 1453 1454 1455 1456
{
  su_home_stat_t *hs = sub->sub_stats;

  unsigned rsize = ALIGN(size);

1457 1458 1459 1460 1461
  if (preload) {
    hs->hs_frees.hsf_preload++;
    return;
  }

Pekka Pessi's avatar
Pekka Pessi committed
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
  hs->hs_frees.hsf_number++;
  hs->hs_frees.hsf_bytes += size;
  hs->hs_frees.hsf_rbytes += rsize;

  hs->hs_blocks.hsb_number--;
  hs->hs_blocks.hsb_bytes -= size;
  hs->hs_blocks.hsb_rbytes -= rsize;
}

void su_home_stat_add(su_home_stat_t total[1], su_home_stat_t const hs[1])
{
  total->hs_clones               += hs->hs_clones;
  total->hs_rehash               += hs->hs_rehash;

  if (total->hs_blocksize < hs->hs_blocksize)
    total->hs_blocksize = hs->hs_blocksize;

  total->hs_allocs.hsa_number    += hs->hs_allocs.hsa_number;
  total->hs_allocs.hsa_bytes     += hs->hs_allocs.hsa_bytes;
  total->hs_allocs.hsa_rbytes    += hs->hs_allocs.hsa_rbytes;
  total->hs_allocs.hsa_maxrbytes += hs->hs_allocs.hsa_maxrbytes;

  total->hs_frees.hsf_number     += hs->hs_frees.hsf_number;
  total->hs_frees.hsf_bytes      += hs->hs_frees.hsf_bytes;
  total->hs_frees.hsf_rbytes     += hs->hs_frees.hsf_rbytes;

  total->hs_blocks.hsb_number    += hs->hs_blocks.hsb_number;
  total->hs_blocks.hsb_bytes     += hs->hs_blocks.hsb_bytes;
  total->hs_blocks.hsb_rbytes    += hs->hs_blocks.hsb_rbytes;
}