]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bind9/lib/isc/mem.c
This commit was generated by cvs2svn to compensate for changes in r177420,
[FreeBSD/FreeBSD.git] / contrib / bind9 / lib / isc / mem.c
1 /*
2  * Copyright (C) 2004-2007  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 1997-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* $Id: mem.c,v 1.116.18.18 2007/10/30 23:31:43 marka Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stddef.h>
27
28 #include <limits.h>
29
30 #include <isc/magic.h>
31 #include <isc/mem.h>
32 #include <isc/msgs.h>
33 #include <isc/once.h>
34 #include <isc/ondestroy.h>
35 #include <isc/string.h>
36
37 #include <isc/mutex.h>
38 #include <isc/util.h>
39
40 #define MCTXLOCK(m, l) if (((m)->flags & ISC_MEMFLAG_NOLOCK) == 0) LOCK(l)
41 #define MCTXUNLOCK(m, l) if (((m)->flags & ISC_MEMFLAG_NOLOCK) == 0) UNLOCK(l)
42
43 #ifndef ISC_MEM_DEBUGGING
44 #define ISC_MEM_DEBUGGING 0
45 #endif
46 LIBISC_EXTERNAL_DATA unsigned int isc_mem_debugging = ISC_MEM_DEBUGGING;
47
48 /*
49  * Constants.
50  */
51
52 #define DEF_MAX_SIZE            1100
53 #define DEF_MEM_TARGET          4096
54 #define ALIGNMENT_SIZE          8               /*%< must be a power of 2 */
55 #define NUM_BASIC_BLOCKS        64              /*%< must be > 1 */
56 #define TABLE_INCREMENT         1024
57 #define DEBUGLIST_COUNT         1024
58
59 /*
60  * Types.
61  */
62 #if ISC_MEM_TRACKLINES
63 typedef struct debuglink debuglink_t;
64 struct debuglink {
65         ISC_LINK(debuglink_t)   link;
66         const void             *ptr[DEBUGLIST_COUNT];
67         unsigned int            size[DEBUGLIST_COUNT];
68         const char             *file[DEBUGLIST_COUNT];
69         unsigned int            line[DEBUGLIST_COUNT];
70         unsigned int            count;
71 };
72
73 #define FLARG_PASS      , file, line
74 #define FLARG           , const char *file, int line
75 #else
76 #define FLARG_PASS
77 #define FLARG
78 #endif
79
80 typedef struct element element;
81 struct element {
82         element *               next;
83 };
84
85 typedef struct {
86         /*!
87          * This structure must be ALIGNMENT_SIZE bytes.
88          */
89         union {
90                 size_t          size;
91                 isc_mem_t       *ctx;
92                 char            bytes[ALIGNMENT_SIZE];
93         } u;
94 } size_info;
95
96 struct stats {
97         unsigned long           gets;
98         unsigned long           totalgets;
99         unsigned long           blocks;
100         unsigned long           freefrags;
101 };
102
103 #define MEM_MAGIC               ISC_MAGIC('M', 'e', 'm', 'C')
104 #define VALID_CONTEXT(c)        ISC_MAGIC_VALID(c, MEM_MAGIC)
105
106 #if ISC_MEM_TRACKLINES
107 typedef ISC_LIST(debuglink_t)   debuglist_t;
108 #endif
109
110 /* List of all active memory contexts. */
111
112 static ISC_LIST(isc_mem_t)      contexts;
113 static isc_once_t               once = ISC_ONCE_INIT;
114 static isc_mutex_t              lock;
115
116 struct isc_mem {
117         unsigned int            magic;
118         isc_ondestroy_t         ondestroy;
119         unsigned int            flags;
120         isc_mutex_t             lock;
121         isc_memalloc_t          memalloc;
122         isc_memfree_t           memfree;
123         void *                  arg;
124         size_t                  max_size;
125         isc_boolean_t           checkfree;
126         struct stats *          stats;
127         unsigned int            references;
128         size_t                  quota;
129         size_t                  total;
130         size_t                  inuse;
131         size_t                  maxinuse;
132         size_t                  hi_water;
133         size_t                  lo_water;
134         isc_boolean_t           hi_called;
135         isc_mem_water_t         water;
136         void *                  water_arg;
137         ISC_LIST(isc_mempool_t) pools;
138
139         /*  ISC_MEMFLAG_INTERNAL */
140         size_t                  mem_target;
141         element **              freelists;
142         element *               basic_blocks;
143         unsigned char **        basic_table;
144         unsigned int            basic_table_count;
145         unsigned int            basic_table_size;
146         unsigned char *         lowest;
147         unsigned char *         highest;
148
149 #if ISC_MEM_TRACKLINES
150         debuglist_t *           debuglist;
151 #endif
152
153         unsigned int            memalloc_failures;
154         ISC_LINK(isc_mem_t)     link;
155 };
156
157 #define MEMPOOL_MAGIC           ISC_MAGIC('M', 'E', 'M', 'p')
158 #define VALID_MEMPOOL(c)        ISC_MAGIC_VALID(c, MEMPOOL_MAGIC)
159
160 struct isc_mempool {
161         /* always unlocked */
162         unsigned int    magic;          /*%< magic number */
163         isc_mutex_t    *lock;           /*%< optional lock */
164         isc_mem_t      *mctx;           /*%< our memory context */
165         /*%< locked via the memory context's lock */
166         ISC_LINK(isc_mempool_t) link;   /*%< next pool in this mem context */
167         /*%< optionally locked from here down */
168         element        *items;          /*%< low water item list */
169         size_t          size;           /*%< size of each item on this pool */
170         unsigned int    maxalloc;       /*%< max number of items allowed */
171         unsigned int    allocated;      /*%< # of items currently given out */
172         unsigned int    freecount;      /*%< # of items on reserved list */
173         unsigned int    freemax;        /*%< # of items allowed on free list */
174         unsigned int    fillcount;      /*%< # of items to fetch on each fill */
175         /*%< Stats only. */
176         unsigned int    gets;           /*%< # of requests to this pool */
177         /*%< Debugging only. */
178 #if ISC_MEMPOOL_NAMES
179         char            name[16];       /*%< printed name in stats reports */
180 #endif
181 };
182
183 /*
184  * Private Inline-able.
185  */
186
187 #if ! ISC_MEM_TRACKLINES
188 #define ADD_TRACE(a, b, c, d, e)
189 #define DELETE_TRACE(a, b, c, d, e)
190 #else
191 #define ADD_TRACE(a, b, c, d, e) \
192         do { \
193                 if ((isc_mem_debugging & (ISC_MEM_DEBUGTRACE | \
194                                           ISC_MEM_DEBUGRECORD)) != 0 && \
195                      b != NULL) \
196                          add_trace_entry(a, b, c, d, e); \
197         } while (0)
198 #define DELETE_TRACE(a, b, c, d, e)     delete_trace_entry(a, b, c, d, e)
199
200 static void
201 print_active(isc_mem_t *ctx, FILE *out);
202
203 /*!
204  * mctx must be locked.
205  */
206 static inline void
207 add_trace_entry(isc_mem_t *mctx, const void *ptr, unsigned int size
208                 FLARG)
209 {
210         debuglink_t *dl;
211         unsigned int i;
212
213         if ((isc_mem_debugging & ISC_MEM_DEBUGTRACE) != 0)
214                 fprintf(stderr, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
215                                                ISC_MSG_ADDTRACE,
216                                                "add %p size %u "
217                                                "file %s line %u mctx %p\n"),
218                         ptr, size, file, line, mctx);
219
220         if (mctx->debuglist == NULL)
221                 return;
222
223         if (size > mctx->max_size)
224                 size = mctx->max_size;
225
226         dl = ISC_LIST_HEAD(mctx->debuglist[size]);
227         while (dl != NULL) {
228                 if (dl->count == DEBUGLIST_COUNT)
229                         goto next;
230                 for (i = 0; i < DEBUGLIST_COUNT; i++) {
231                         if (dl->ptr[i] == NULL) {
232                                 dl->ptr[i] = ptr;
233                                 dl->size[i] = size;
234                                 dl->file[i] = file;
235                                 dl->line[i] = line;
236                                 dl->count++;
237                                 return;
238                         }
239                 }
240         next:
241                 dl = ISC_LIST_NEXT(dl, link);
242         }
243
244         dl = malloc(sizeof(debuglink_t));
245         INSIST(dl != NULL);
246
247         ISC_LINK_INIT(dl, link);
248         for (i = 1; i < DEBUGLIST_COUNT; i++) {
249                 dl->ptr[i] = NULL;
250                 dl->size[i] = 0;
251                 dl->file[i] = NULL;
252                 dl->line[i] = 0;
253         }
254
255         dl->ptr[0] = ptr;
256         dl->size[0] = size;
257         dl->file[0] = file;
258         dl->line[0] = line;
259         dl->count = 1;
260
261         ISC_LIST_PREPEND(mctx->debuglist[size], dl, link);
262 }
263
264 static inline void
265 delete_trace_entry(isc_mem_t *mctx, const void *ptr, unsigned int size,
266                    const char *file, unsigned int line)
267 {
268         debuglink_t *dl;
269         unsigned int i;
270
271         if ((isc_mem_debugging & ISC_MEM_DEBUGTRACE) != 0)
272                 fprintf(stderr, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
273                                                ISC_MSG_DELTRACE,
274                                                "del %p size %u "
275                                                "file %s line %u mctx %p\n"),
276                         ptr, size, file, line, mctx);
277
278         if (mctx->debuglist == NULL)
279                 return;
280
281         if (size > mctx->max_size)
282                 size = mctx->max_size;
283
284         dl = ISC_LIST_HEAD(mctx->debuglist[size]);
285         while (dl != NULL) {
286                 for (i = 0; i < DEBUGLIST_COUNT; i++) {
287                         if (dl->ptr[i] == ptr) {
288                                 dl->ptr[i] = NULL;
289                                 dl->size[i] = 0;
290                                 dl->file[i] = NULL;
291                                 dl->line[i] = 0;
292
293                                 INSIST(dl->count > 0);
294                                 dl->count--;
295                                 if (dl->count == 0) {
296                                         ISC_LIST_UNLINK(mctx->debuglist[size],
297                                                         dl, link);
298                                         free(dl);
299                                 }
300                                 return;
301                         }
302                 }
303                 dl = ISC_LIST_NEXT(dl, link);
304         }
305
306         /*
307          * If we get here, we didn't find the item on the list.  We're
308          * screwed.
309          */
310         INSIST(dl != NULL);
311 }
312 #endif /* ISC_MEM_TRACKLINES */
313
314 static inline size_t
315 rmsize(size_t size) {
316         /*
317          * round down to ALIGNMENT_SIZE
318          */
319         return (size & (~(ALIGNMENT_SIZE - 1)));
320 }
321
322 static inline size_t
323 quantize(size_t size) {
324         /*!
325          * Round up the result in order to get a size big
326          * enough to satisfy the request and be aligned on ALIGNMENT_SIZE
327          * byte boundaries.
328          */
329
330         if (size == 0U)
331                 return (ALIGNMENT_SIZE);
332         return ((size + ALIGNMENT_SIZE - 1) & (~(ALIGNMENT_SIZE - 1)));
333 }
334
335 static inline isc_boolean_t
336 more_basic_blocks(isc_mem_t *ctx) {
337         void *new;
338         unsigned char *curr, *next;
339         unsigned char *first, *last;
340         unsigned char **table;
341         unsigned int table_size;
342         size_t increment;
343         int i;
344
345         /* Require: we hold the context lock. */
346
347         /*
348          * Did we hit the quota for this context?
349          */
350         increment = NUM_BASIC_BLOCKS * ctx->mem_target;
351         if (ctx->quota != 0U && ctx->total + increment > ctx->quota)
352                 return (ISC_FALSE);
353
354         INSIST(ctx->basic_table_count <= ctx->basic_table_size);
355         if (ctx->basic_table_count == ctx->basic_table_size) {
356                 table_size = ctx->basic_table_size + TABLE_INCREMENT;
357                 table = (ctx->memalloc)(ctx->arg,
358                                         table_size * sizeof(unsigned char *));
359                 if (table == NULL) {
360                         ctx->memalloc_failures++;
361                         return (ISC_FALSE);
362                 }
363                 if (ctx->basic_table_size != 0) {
364                         memcpy(table, ctx->basic_table,
365                                ctx->basic_table_size *
366                                sizeof(unsigned char *));
367                         (ctx->memfree)(ctx->arg, ctx->basic_table);
368                 }
369                 ctx->basic_table = table;
370                 ctx->basic_table_size = table_size;
371         }
372
373         new = (ctx->memalloc)(ctx->arg, NUM_BASIC_BLOCKS * ctx->mem_target);
374         if (new == NULL) {
375                 ctx->memalloc_failures++;
376                 return (ISC_FALSE);
377         }
378         ctx->total += increment;
379         ctx->basic_table[ctx->basic_table_count] = new;
380         ctx->basic_table_count++;
381
382         curr = new;
383         next = curr + ctx->mem_target;
384         for (i = 0; i < (NUM_BASIC_BLOCKS - 1); i++) {
385                 ((element *)curr)->next = (element *)next;
386                 curr = next;
387                 next += ctx->mem_target;
388         }
389         /*
390          * curr is now pointing at the last block in the
391          * array.
392          */
393         ((element *)curr)->next = NULL;
394         first = new;
395         last = first + NUM_BASIC_BLOCKS * ctx->mem_target - 1;
396         if (first < ctx->lowest || ctx->lowest == NULL)
397                 ctx->lowest = first;
398         if (last > ctx->highest)
399                 ctx->highest = last;
400         ctx->basic_blocks = new;
401
402         return (ISC_TRUE);
403 }
404
405 static inline isc_boolean_t
406 more_frags(isc_mem_t *ctx, size_t new_size) {
407         int i, frags;
408         size_t total_size;
409         void *new;
410         unsigned char *curr, *next;
411
412         /*!
413          * Try to get more fragments by chopping up a basic block.
414          */
415
416         if (ctx->basic_blocks == NULL) {
417                 if (!more_basic_blocks(ctx)) {
418                         /*
419                          * We can't get more memory from the OS, or we've
420                          * hit the quota for this context.
421                          */
422                         /*
423                          * XXXRTH  "At quota" notification here.
424                          */
425                         return (ISC_FALSE);
426                 }
427         }
428
429         total_size = ctx->mem_target;
430         new = ctx->basic_blocks;
431         ctx->basic_blocks = ctx->basic_blocks->next;
432         frags = total_size / new_size;
433         ctx->stats[new_size].blocks++;
434         ctx->stats[new_size].freefrags += frags;
435         /*
436          * Set up a linked-list of blocks of size
437          * "new_size".
438          */
439         curr = new;
440         next = curr + new_size;
441         total_size -= new_size;
442         for (i = 0; i < (frags - 1); i++) {
443                 ((element *)curr)->next = (element *)next;
444                 curr = next;
445                 next += new_size;
446                 total_size -= new_size;
447         }
448         /*
449          * Add the remaining fragment of the basic block to a free list.
450          */
451         total_size = rmsize(total_size);
452         if (total_size > 0U) {
453                 ((element *)next)->next = ctx->freelists[total_size];
454                 ctx->freelists[total_size] = (element *)next;
455                 ctx->stats[total_size].freefrags++;
456         }
457         /*
458          * curr is now pointing at the last block in the
459          * array.
460          */
461         ((element *)curr)->next = NULL;
462         ctx->freelists[new_size] = new;
463
464         return (ISC_TRUE);
465 }
466
467 static inline void *
468 mem_getunlocked(isc_mem_t *ctx, size_t size) {
469         size_t new_size = quantize(size);
470         void *ret;
471
472         if (size >= ctx->max_size || new_size >= ctx->max_size) {
473                 /*
474                  * memget() was called on something beyond our upper limit.
475                  */
476                 if (ctx->quota != 0U && ctx->total + size > ctx->quota) {
477                         ret = NULL;
478                         goto done;
479                 }
480                 ret = (ctx->memalloc)(ctx->arg, size);
481                 if (ret == NULL) {
482                         ctx->memalloc_failures++;
483                         goto done;
484                 }
485                 ctx->total += size;
486                 ctx->inuse += size;
487                 ctx->stats[ctx->max_size].gets++;
488                 ctx->stats[ctx->max_size].totalgets++;
489                 /*
490                  * If we don't set new_size to size, then the
491                  * ISC_MEM_FILL code might write over bytes we
492                  * don't own.
493                  */
494                 new_size = size;
495                 goto done;
496         }
497
498         /*
499          * If there are no blocks in the free list for this size, get a chunk
500          * of memory and then break it up into "new_size"-sized blocks, adding
501          * them to the free list.
502          */
503         if (ctx->freelists[new_size] == NULL && !more_frags(ctx, new_size))
504                 return (NULL);
505
506         /*
507          * The free list uses the "rounded-up" size "new_size".
508          */
509         ret = ctx->freelists[new_size];
510         ctx->freelists[new_size] = ctx->freelists[new_size]->next;
511
512         /*
513          * The stats[] uses the _actual_ "size" requested by the
514          * caller, with the caveat (in the code above) that "size" >= the
515          * max. size (max_size) ends up getting recorded as a call to
516          * max_size.
517          */
518         ctx->stats[size].gets++;
519         ctx->stats[size].totalgets++;
520         ctx->stats[new_size].freefrags--;
521         ctx->inuse += new_size;
522
523  done:
524
525 #if ISC_MEM_FILL
526         if (ret != NULL)
527                 memset(ret, 0xbe, new_size); /* Mnemonic for "beef". */
528 #endif
529
530         return (ret);
531 }
532
533 #if ISC_MEM_FILL && ISC_MEM_CHECKOVERRUN
534 static inline void
535 check_overrun(void *mem, size_t size, size_t new_size) {
536         unsigned char *cp;
537
538         cp = (unsigned char *)mem;
539         cp += size;
540         while (size < new_size) {
541                 INSIST(*cp == 0xbe);
542                 cp++;
543                 size++;
544         }
545 }
546 #endif
547
548 static inline void
549 mem_putunlocked(isc_mem_t *ctx, void *mem, size_t size) {
550         size_t new_size = quantize(size);
551
552         if (size == ctx->max_size || new_size >= ctx->max_size) {
553                 /*
554                  * memput() called on something beyond our upper limit.
555                  */
556 #if ISC_MEM_FILL
557                 memset(mem, 0xde, size); /* Mnemonic for "dead". */
558 #endif
559                 (ctx->memfree)(ctx->arg, mem);
560                 INSIST(ctx->stats[ctx->max_size].gets != 0U);
561                 ctx->stats[ctx->max_size].gets--;
562                 INSIST(size <= ctx->total);
563                 ctx->inuse -= size;
564                 ctx->total -= size;
565                 return;
566         }
567
568 #if ISC_MEM_FILL
569 #if ISC_MEM_CHECKOVERRUN
570         check_overrun(mem, size, new_size);
571 #endif
572         memset(mem, 0xde, new_size); /* Mnemonic for "dead". */
573 #endif
574
575         /*
576          * The free list uses the "rounded-up" size "new_size".
577          */
578         ((element *)mem)->next = ctx->freelists[new_size];
579         ctx->freelists[new_size] = (element *)mem;
580
581         /*
582          * The stats[] uses the _actual_ "size" requested by the
583          * caller, with the caveat (in the code above) that "size" >= the
584          * max. size (max_size) ends up getting recorded as a call to
585          * max_size.
586          */
587         INSIST(ctx->stats[size].gets != 0U);
588         ctx->stats[size].gets--;
589         ctx->stats[new_size].freefrags++;
590         ctx->inuse -= new_size;
591 }
592
593 /*!
594  * Perform a malloc, doing memory filling and overrun detection as necessary.
595  */
596 static inline void *
597 mem_get(isc_mem_t *ctx, size_t size) {
598         char *ret;
599
600 #if ISC_MEM_CHECKOVERRUN
601         size += 1;
602 #endif
603
604         ret = (ctx->memalloc)(ctx->arg, size);
605         if (ret == NULL)
606                 ctx->memalloc_failures++;       
607
608 #if ISC_MEM_FILL
609         if (ret != NULL)
610                 memset(ret, 0xbe, size); /* Mnemonic for "beef". */
611 #else
612 #  if ISC_MEM_CHECKOVERRUN
613         if (ret != NULL)
614                 ret[size-1] = 0xbe;
615 #  endif
616 #endif
617
618         return (ret);
619 }
620
621 /*!
622  * Perform a free, doing memory filling and overrun detection as necessary.
623  */
624 static inline void
625 mem_put(isc_mem_t *ctx, void *mem, size_t size) {
626 #if ISC_MEM_CHECKOVERRUN
627         INSIST(((unsigned char *)mem)[size] == 0xbe);
628 #endif
629 #if ISC_MEM_FILL
630         memset(mem, 0xde, size); /* Mnemonic for "dead". */
631 #else
632         UNUSED(size);
633 #endif
634         (ctx->memfree)(ctx->arg, mem);
635 }
636
637 /*!
638  * Update internal counters after a memory get.
639  */
640 static inline void
641 mem_getstats(isc_mem_t *ctx, size_t size) {
642         ctx->total += size;
643         ctx->inuse += size;
644
645         if (size > ctx->max_size) {
646                 ctx->stats[ctx->max_size].gets++;
647                 ctx->stats[ctx->max_size].totalgets++;
648         } else {
649                 ctx->stats[size].gets++;
650                 ctx->stats[size].totalgets++;
651         }
652 }
653
654 /*!
655  * Update internal counters after a memory put.
656  */
657 static inline void
658 mem_putstats(isc_mem_t *ctx, void *ptr, size_t size) {
659         UNUSED(ptr);
660
661         INSIST(ctx->inuse >= size);
662         ctx->inuse -= size;
663
664         if (size > ctx->max_size) {
665                 INSIST(ctx->stats[ctx->max_size].gets > 0U);
666                 ctx->stats[ctx->max_size].gets--;
667         } else {
668                 INSIST(ctx->stats[size].gets > 0U);
669                 ctx->stats[size].gets--;
670         }
671 }
672
673 /*
674  * Private.
675  */
676
677 static void *
678 default_memalloc(void *arg, size_t size) {
679         UNUSED(arg);
680         if (size == 0U)
681                 size = 1;
682         return (malloc(size));
683 }
684
685 static void
686 default_memfree(void *arg, void *ptr) {
687         UNUSED(arg);
688         free(ptr);
689 }
690
691 static void
692 initialize_action(void) {
693         RUNTIME_CHECK(isc_mutex_init(&lock) == ISC_R_SUCCESS);
694         ISC_LIST_INIT(contexts);
695 }
696
697 /*
698  * Public.
699  */
700
701 isc_result_t
702 isc_mem_createx(size_t init_max_size, size_t target_size,
703                 isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg,
704                 isc_mem_t **ctxp)
705 {
706         return (isc_mem_createx2(init_max_size, target_size, memalloc, memfree,
707                                  arg, ctxp, ISC_MEMFLAG_DEFAULT));
708                                  
709 }
710
711 isc_result_t
712 isc_mem_createx2(size_t init_max_size, size_t target_size,
713                  isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg,
714                  isc_mem_t **ctxp, unsigned int flags)
715 {
716         isc_mem_t *ctx;
717         isc_result_t result;
718
719         REQUIRE(ctxp != NULL && *ctxp == NULL);
720         REQUIRE(memalloc != NULL);
721         REQUIRE(memfree != NULL);
722
723         INSIST((ALIGNMENT_SIZE & (ALIGNMENT_SIZE - 1)) == 0);
724
725         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
726
727         ctx = (memalloc)(arg, sizeof(*ctx));
728         if (ctx == NULL)
729                 return (ISC_R_NOMEMORY);
730
731         if ((flags & ISC_MEMFLAG_NOLOCK) == 0) {
732                 result = isc_mutex_init(&ctx->lock);
733                 if (result != ISC_R_SUCCESS) {
734                         (memfree)(arg, ctx);
735                         return (result);
736                 }
737         }
738
739         if (init_max_size == 0U)
740                 ctx->max_size = DEF_MAX_SIZE;
741         else
742                 ctx->max_size = init_max_size;
743         ctx->flags = flags;
744         ctx->references = 1;
745         ctx->quota = 0;
746         ctx->total = 0;
747         ctx->inuse = 0;
748         ctx->maxinuse = 0;
749         ctx->hi_water = 0;
750         ctx->lo_water = 0;
751         ctx->hi_called = ISC_FALSE;
752         ctx->water = NULL;
753         ctx->water_arg = NULL;
754         ctx->magic = MEM_MAGIC;
755         isc_ondestroy_init(&ctx->ondestroy);
756         ctx->memalloc = memalloc;
757         ctx->memfree = memfree;
758         ctx->arg = arg;
759         ctx->stats = NULL;
760         ctx->checkfree = ISC_TRUE;
761 #if ISC_MEM_TRACKLINES
762         ctx->debuglist = NULL;
763 #endif
764         ISC_LIST_INIT(ctx->pools);
765         ctx->freelists = NULL;
766         ctx->basic_blocks = NULL;
767         ctx->basic_table = NULL;
768         ctx->basic_table_count = 0;
769         ctx->basic_table_size = 0;
770         ctx->lowest = NULL;
771         ctx->highest = NULL;
772
773         ctx->stats = (memalloc)(arg,
774                                 (ctx->max_size+1) * sizeof(struct stats));
775         if (ctx->stats == NULL) {
776                 result = ISC_R_NOMEMORY;
777                 goto error;
778         }
779         memset(ctx->stats, 0, (ctx->max_size + 1) * sizeof(struct stats));
780
781         if ((flags & ISC_MEMFLAG_INTERNAL) != 0) {
782                 if (target_size == 0U)
783                         ctx->mem_target = DEF_MEM_TARGET;
784                 else
785                         ctx->mem_target = target_size;
786                 ctx->freelists = (memalloc)(arg, ctx->max_size *
787                                                  sizeof(element *));
788                 if (ctx->freelists == NULL) {
789                         result = ISC_R_NOMEMORY;
790                         goto error;
791                 }
792                 memset(ctx->freelists, 0,
793                        ctx->max_size * sizeof(element *));
794         }
795
796 #if ISC_MEM_TRACKLINES
797         if ((isc_mem_debugging & ISC_MEM_DEBUGRECORD) != 0) {
798                 unsigned int i;
799
800                 ctx->debuglist = (memalloc)(arg,
801                                       (ctx->max_size+1) * sizeof(debuglist_t));
802                 if (ctx->debuglist == NULL) {
803                         result = ISC_R_NOMEMORY;
804                         goto error;
805                 }
806                 for (i = 0; i <= ctx->max_size; i++)
807                         ISC_LIST_INIT(ctx->debuglist[i]);
808         }
809 #endif
810
811         ctx->memalloc_failures = 0;
812
813         LOCK(&lock);
814         ISC_LIST_INITANDAPPEND(contexts, ctx, link);
815         UNLOCK(&lock);
816
817         *ctxp = ctx;
818         return (ISC_R_SUCCESS);
819
820   error:
821         if (ctx != NULL) {
822                 if (ctx->stats != NULL)
823                         (memfree)(arg, ctx->stats);
824                 if (ctx->freelists != NULL)
825                         (memfree)(arg, ctx->freelists);
826 #if ISC_MEM_TRACKLINES
827                 if (ctx->debuglist != NULL)
828                         (ctx->memfree)(ctx->arg, ctx->debuglist);
829 #endif /* ISC_MEM_TRACKLINES */
830                 if ((ctx->flags & ISC_MEMFLAG_NOLOCK) == 0)
831                         DESTROYLOCK(&ctx->lock);
832                 (memfree)(arg, ctx);
833         }
834
835         return (result);
836 }
837
838 isc_result_t
839 isc_mem_create(size_t init_max_size, size_t target_size,
840                isc_mem_t **ctxp)
841 {
842         return (isc_mem_createx2(init_max_size, target_size,
843                                  default_memalloc, default_memfree, NULL,
844                                  ctxp, ISC_MEMFLAG_DEFAULT));
845 }
846
847 isc_result_t
848 isc_mem_create2(size_t init_max_size, size_t target_size,
849                 isc_mem_t **ctxp, unsigned int flags)
850 {
851         return (isc_mem_createx2(init_max_size, target_size,
852                                  default_memalloc, default_memfree, NULL,
853                                  ctxp, flags));
854 }
855
856 static void
857 destroy(isc_mem_t *ctx) {
858         unsigned int i;
859         isc_ondestroy_t ondest;
860
861         ctx->magic = 0;
862
863         LOCK(&lock);
864         ISC_LIST_UNLINK(contexts, ctx, link);
865         UNLOCK(&lock);
866
867         INSIST(ISC_LIST_EMPTY(ctx->pools));
868
869 #if ISC_MEM_TRACKLINES
870         if (ctx->debuglist != NULL) {
871                 if (ctx->checkfree) {
872                         for (i = 0; i <= ctx->max_size; i++) {
873                                 if (!ISC_LIST_EMPTY(ctx->debuglist[i]))
874                                         print_active(ctx, stderr);
875                                 INSIST(ISC_LIST_EMPTY(ctx->debuglist[i]));
876                         }
877                 } else {
878                         debuglink_t *dl;
879
880                         for (i = 0; i <= ctx->max_size; i++)
881                                 for (dl = ISC_LIST_HEAD(ctx->debuglist[i]);
882                                      dl != NULL;
883                                      dl = ISC_LIST_HEAD(ctx->debuglist[i])) {
884                                         ISC_LIST_UNLINK(ctx->debuglist[i],
885                                                         dl, link);
886                                         free(dl);
887                                 }
888                 }
889                 (ctx->memfree)(ctx->arg, ctx->debuglist);
890         }
891 #endif
892         INSIST(ctx->references == 0);
893
894         if (ctx->checkfree) {
895                 for (i = 0; i <= ctx->max_size; i++) {
896 #if ISC_MEM_TRACKLINES
897                         if (ctx->stats[i].gets != 0U)
898                                 print_active(ctx, stderr);
899 #endif
900                         INSIST(ctx->stats[i].gets == 0U);
901                 }
902         }
903
904         (ctx->memfree)(ctx->arg, ctx->stats);
905
906         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
907                 for (i = 0; i < ctx->basic_table_count; i++)
908                         (ctx->memfree)(ctx->arg, ctx->basic_table[i]);
909                 (ctx->memfree)(ctx->arg, ctx->freelists);
910                 (ctx->memfree)(ctx->arg, ctx->basic_table);
911         }
912
913         ondest = ctx->ondestroy;
914
915         if ((ctx->flags & ISC_MEMFLAG_NOLOCK) == 0)
916                 DESTROYLOCK(&ctx->lock);
917         (ctx->memfree)(ctx->arg, ctx);
918
919         isc_ondestroy_notify(&ondest, ctx);
920 }
921
922 void
923 isc_mem_attach(isc_mem_t *source, isc_mem_t **targetp) {
924         REQUIRE(VALID_CONTEXT(source));
925         REQUIRE(targetp != NULL && *targetp == NULL);
926
927         MCTXLOCK(source, &source->lock);
928         source->references++;
929         MCTXUNLOCK(source, &source->lock);
930
931         *targetp = source;
932 }
933
934 void
935 isc_mem_detach(isc_mem_t **ctxp) {
936         isc_mem_t *ctx;
937         isc_boolean_t want_destroy = ISC_FALSE;
938
939         REQUIRE(ctxp != NULL);
940         ctx = *ctxp;
941         REQUIRE(VALID_CONTEXT(ctx));
942
943         MCTXLOCK(ctx, &ctx->lock);
944         INSIST(ctx->references > 0);
945         ctx->references--;
946         if (ctx->references == 0)
947                 want_destroy = ISC_TRUE;
948         MCTXUNLOCK(ctx, &ctx->lock);
949
950         if (want_destroy)
951                 destroy(ctx);
952
953         *ctxp = NULL;
954 }
955
956 /*
957  * isc_mem_putanddetach() is the equivalent of:
958  *
959  * mctx = NULL;
960  * isc_mem_attach(ptr->mctx, &mctx);
961  * isc_mem_detach(&ptr->mctx);
962  * isc_mem_put(mctx, ptr, sizeof(*ptr);
963  * isc_mem_detach(&mctx);
964  */
965
966 void
967 isc__mem_putanddetach(isc_mem_t **ctxp, void *ptr, size_t size FLARG) {
968         isc_mem_t *ctx;
969         isc_boolean_t want_destroy = ISC_FALSE;
970         size_info *si;
971         size_t oldsize;
972
973         REQUIRE(ctxp != NULL);
974         ctx = *ctxp;
975         REQUIRE(VALID_CONTEXT(ctx));
976         REQUIRE(ptr != NULL);
977
978         /*
979          * Must be before mem_putunlocked() as ctxp is usually within
980          * [ptr..ptr+size).
981          */
982         *ctxp = NULL;
983
984         if ((isc_mem_debugging & (ISC_MEM_DEBUGSIZE|ISC_MEM_DEBUGCTX)) != 0) {
985                 if ((isc_mem_debugging & ISC_MEM_DEBUGSIZE) != 0) {
986                         si = &(((size_info *)ptr)[-1]);
987                         oldsize = si->u.size - ALIGNMENT_SIZE;
988                         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)
989                                 oldsize -= ALIGNMENT_SIZE;
990                         INSIST(oldsize == size);
991                 }
992                 isc__mem_free(ctx, ptr FLARG_PASS);
993
994                 MCTXLOCK(ctx, &ctx->lock);
995                 ctx->references--;
996                 if (ctx->references == 0)
997                         want_destroy = ISC_TRUE;
998                 MCTXUNLOCK(ctx, &ctx->lock);
999                 if (want_destroy)
1000                         destroy(ctx);
1001
1002                 return;
1003         }
1004
1005         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1006                 MCTXLOCK(ctx, &ctx->lock);
1007                 mem_putunlocked(ctx, ptr, size);
1008         } else {
1009                 mem_put(ctx, ptr, size);
1010                 MCTXLOCK(ctx, &ctx->lock);
1011                 mem_putstats(ctx, ptr, size);
1012         }
1013
1014         DELETE_TRACE(ctx, ptr, size, file, line);
1015         INSIST(ctx->references > 0);
1016         ctx->references--;
1017         if (ctx->references == 0)
1018                 want_destroy = ISC_TRUE;
1019
1020         MCTXUNLOCK(ctx, &ctx->lock);
1021
1022         if (want_destroy)
1023                 destroy(ctx);
1024 }
1025
1026 void
1027 isc_mem_destroy(isc_mem_t **ctxp) {
1028         isc_mem_t *ctx;
1029
1030         /*
1031          * This routine provides legacy support for callers who use mctxs
1032          * without attaching/detaching.
1033          */
1034
1035         REQUIRE(ctxp != NULL);
1036         ctx = *ctxp;
1037         REQUIRE(VALID_CONTEXT(ctx));
1038
1039         MCTXLOCK(ctx, &ctx->lock);
1040 #if ISC_MEM_TRACKLINES
1041         if (ctx->references != 1)
1042                 print_active(ctx, stderr);
1043 #endif
1044         REQUIRE(ctx->references == 1);
1045         ctx->references--;
1046         MCTXUNLOCK(ctx, &ctx->lock);
1047
1048         destroy(ctx);
1049
1050         *ctxp = NULL;
1051 }
1052
1053 isc_result_t
1054 isc_mem_ondestroy(isc_mem_t *ctx, isc_task_t *task, isc_event_t **event) {
1055         isc_result_t res;
1056
1057         MCTXLOCK(ctx, &ctx->lock);
1058         res = isc_ondestroy_register(&ctx->ondestroy, task, event);
1059         MCTXUNLOCK(ctx, &ctx->lock);
1060
1061         return (res);
1062 }
1063
1064
1065 void *
1066 isc__mem_get(isc_mem_t *ctx, size_t size FLARG) {
1067         void *ptr;
1068         isc_boolean_t call_water = ISC_FALSE;
1069
1070         REQUIRE(VALID_CONTEXT(ctx));
1071
1072         if ((isc_mem_debugging & (ISC_MEM_DEBUGSIZE|ISC_MEM_DEBUGCTX)) != 0)
1073                 return (isc__mem_allocate(ctx, size FLARG_PASS));
1074
1075         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1076                 MCTXLOCK(ctx, &ctx->lock);
1077                 ptr = mem_getunlocked(ctx, size);
1078         } else {
1079                 ptr = mem_get(ctx, size);
1080                 MCTXLOCK(ctx, &ctx->lock);
1081                 if (ptr != NULL)
1082                         mem_getstats(ctx, size);
1083         }
1084
1085         ADD_TRACE(ctx, ptr, size, file, line);
1086         if (ctx->hi_water != 0U && !ctx->hi_called &&
1087             ctx->inuse > ctx->hi_water) {
1088                 ctx->hi_called = ISC_TRUE;
1089                 call_water = ISC_TRUE;
1090         }
1091         if (ctx->inuse > ctx->maxinuse) {
1092                 ctx->maxinuse = ctx->inuse;
1093                 if (ctx->hi_water != 0U && ctx->inuse > ctx->hi_water &&
1094                     (isc_mem_debugging & ISC_MEM_DEBUGUSAGE) != 0)
1095                         fprintf(stderr, "maxinuse = %lu\n",
1096                                 (unsigned long)ctx->inuse);
1097         }
1098         MCTXUNLOCK(ctx, &ctx->lock);
1099
1100         if (call_water)
1101                 (ctx->water)(ctx->water_arg, ISC_MEM_HIWATER);
1102
1103         return (ptr);
1104 }
1105
1106 void
1107 isc__mem_put(isc_mem_t *ctx, void *ptr, size_t size FLARG)
1108 {
1109         isc_boolean_t call_water = ISC_FALSE;
1110         size_info *si;
1111         size_t oldsize;
1112
1113         REQUIRE(VALID_CONTEXT(ctx));
1114         REQUIRE(ptr != NULL);
1115
1116         if ((isc_mem_debugging & (ISC_MEM_DEBUGSIZE|ISC_MEM_DEBUGCTX)) != 0) {
1117                 if ((isc_mem_debugging & ISC_MEM_DEBUGSIZE) != 0) {
1118                         si = &(((size_info *)ptr)[-1]);
1119                         oldsize = si->u.size - ALIGNMENT_SIZE;
1120                         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)
1121                                 oldsize -= ALIGNMENT_SIZE;
1122                         INSIST(oldsize == size);
1123                 }
1124                 isc__mem_free(ctx, ptr FLARG_PASS);
1125                 return;
1126         }
1127
1128         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1129                 MCTXLOCK(ctx, &ctx->lock);
1130                 mem_putunlocked(ctx, ptr, size);
1131         } else {
1132                 mem_put(ctx, ptr, size);
1133                 MCTXLOCK(ctx, &ctx->lock);
1134                 mem_putstats(ctx, ptr, size);
1135         }
1136
1137         DELETE_TRACE(ctx, ptr, size, file, line);
1138
1139         /*
1140          * The check against ctx->lo_water == 0 is for the condition
1141          * when the context was pushed over hi_water but then had
1142          * isc_mem_setwater() called with 0 for hi_water and lo_water.
1143          */
1144         if (ctx->hi_called && 
1145             (ctx->inuse < ctx->lo_water || ctx->lo_water == 0U)) {
1146                 ctx->hi_called = ISC_FALSE;
1147
1148                 if (ctx->water != NULL)
1149                         call_water = ISC_TRUE;
1150         }
1151         MCTXUNLOCK(ctx, &ctx->lock);
1152
1153         if (call_water)
1154                 (ctx->water)(ctx->water_arg, ISC_MEM_LOWATER);
1155 }
1156
1157 #if ISC_MEM_TRACKLINES
1158 static void
1159 print_active(isc_mem_t *mctx, FILE *out) {
1160         if (mctx->debuglist != NULL) {
1161                 debuglink_t *dl;
1162                 unsigned int i, j;
1163                 const char *format;
1164                 isc_boolean_t found;
1165
1166                 fprintf(out, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1167                                             ISC_MSG_DUMPALLOC,
1168                                             "Dump of all outstanding "
1169                                             "memory allocations:\n"));
1170                 found = ISC_FALSE;
1171                 format = isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1172                                         ISC_MSG_PTRFILELINE,
1173                                         "\tptr %p size %u file %s line %u\n");
1174                 for (i = 0; i <= mctx->max_size; i++) {
1175                         dl = ISC_LIST_HEAD(mctx->debuglist[i]);
1176                         
1177                         if (dl != NULL)
1178                                 found = ISC_TRUE;
1179
1180                         while (dl != NULL) {
1181                                 for (j = 0; j < DEBUGLIST_COUNT; j++)
1182                                         if (dl->ptr[j] != NULL)
1183                                                 fprintf(out, format,
1184                                                         dl->ptr[j],
1185                                                         dl->size[j],
1186                                                         dl->file[j],
1187                                                         dl->line[j]);
1188                                 dl = ISC_LIST_NEXT(dl, link);
1189                         }
1190                 }
1191                 if (!found)
1192                         fprintf(out, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1193                                                     ISC_MSG_NONE, "\tNone.\n"));
1194         }
1195 }
1196 #endif
1197
1198 /*
1199  * Print the stats[] on the stream "out" with suitable formatting.
1200  */
1201 void
1202 isc_mem_stats(isc_mem_t *ctx, FILE *out) {
1203         size_t i;
1204         const struct stats *s;
1205         const isc_mempool_t *pool;
1206
1207         REQUIRE(VALID_CONTEXT(ctx));
1208         MCTXLOCK(ctx, &ctx->lock);
1209
1210         for (i = 0; i <= ctx->max_size; i++) {
1211                 s = &ctx->stats[i];
1212
1213                 if (s->totalgets == 0U && s->gets == 0U)
1214                         continue;
1215                 fprintf(out, "%s%5lu: %11lu gets, %11lu rem",
1216                         (i == ctx->max_size) ? ">=" : "  ",
1217                         (unsigned long) i, s->totalgets, s->gets);
1218                 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0 &&
1219                     (s->blocks != 0U || s->freefrags != 0U))
1220                         fprintf(out, " (%lu bl, %lu ff)",
1221                                 s->blocks, s->freefrags);
1222                 fputc('\n', out);
1223         }
1224
1225         /*
1226          * Note that since a pool can be locked now, these stats might be
1227          * somewhat off if the pool is in active use at the time the stats
1228          * are dumped.  The link fields are protected by the isc_mem_t's
1229          * lock, however, so walking this list and extracting integers from
1230          * stats fields is always safe.
1231          */
1232         pool = ISC_LIST_HEAD(ctx->pools);
1233         if (pool != NULL) {
1234                 fprintf(out, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1235                                             ISC_MSG_POOLSTATS,
1236                                             "[Pool statistics]\n"));
1237                 fprintf(out, "%15s %10s %10s %10s %10s %10s %10s %10s %1s\n",
1238                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1239                                        ISC_MSG_POOLNAME, "name"),
1240                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1241                                        ISC_MSG_POOLSIZE, "size"),
1242                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1243                                        ISC_MSG_POOLMAXALLOC, "maxalloc"),
1244                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1245                                        ISC_MSG_POOLALLOCATED, "allocated"),
1246                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1247                                        ISC_MSG_POOLFREECOUNT, "freecount"),
1248                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1249                                        ISC_MSG_POOLFREEMAX, "freemax"),
1250                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1251                                        ISC_MSG_POOLFILLCOUNT, "fillcount"),
1252                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1253                                        ISC_MSG_POOLGETS, "gets"),
1254                         "L");
1255         }
1256         while (pool != NULL) {
1257                 fprintf(out, "%15s %10lu %10u %10u %10u %10u %10u %10u %s\n",
1258                         pool->name, (unsigned long) pool->size, pool->maxalloc,
1259                         pool->allocated, pool->freecount, pool->freemax,
1260                         pool->fillcount, pool->gets,
1261                         (pool->lock == NULL ? "N" : "Y"));
1262                 pool = ISC_LIST_NEXT(pool, link);
1263         }
1264
1265 #if ISC_MEM_TRACKLINES
1266         print_active(ctx, out);
1267 #endif
1268
1269         MCTXUNLOCK(ctx, &ctx->lock);
1270 }
1271
1272 /*
1273  * Replacements for malloc() and free() -- they implicitly remember the
1274  * size of the object allocated (with some additional overhead).
1275  */
1276
1277 static void *
1278 isc__mem_allocateunlocked(isc_mem_t *ctx, size_t size) {
1279         size_info *si;
1280
1281         size += ALIGNMENT_SIZE;
1282         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)
1283                 size += ALIGNMENT_SIZE;
1284
1285         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0)
1286                 si = mem_getunlocked(ctx, size);
1287         else
1288                 si = mem_get(ctx, size);
1289
1290         if (si == NULL)
1291                 return (NULL);
1292         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0) {
1293                 si->u.ctx = ctx;
1294                 si++;
1295         }
1296         si->u.size = size;
1297         return (&si[1]);
1298 }
1299
1300 void *
1301 isc__mem_allocate(isc_mem_t *ctx, size_t size FLARG) {
1302         size_info *si;
1303         isc_boolean_t call_water = ISC_FALSE;
1304
1305         REQUIRE(VALID_CONTEXT(ctx));
1306
1307         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1308                 MCTXLOCK(ctx, &ctx->lock);
1309                 si = isc__mem_allocateunlocked(ctx, size);
1310         } else {
1311                 si = isc__mem_allocateunlocked(ctx, size);
1312                 MCTXLOCK(ctx, &ctx->lock);
1313                 if (si != NULL)
1314                         mem_getstats(ctx, si[-1].u.size);
1315         }
1316
1317 #if ISC_MEM_TRACKLINES
1318         ADD_TRACE(ctx, si, si[-1].u.size, file, line);
1319 #endif
1320         if (ctx->hi_water != 0U && !ctx->hi_called &&
1321             ctx->inuse > ctx->hi_water) {
1322                 ctx->hi_called = ISC_TRUE;
1323                 call_water = ISC_TRUE;
1324         }
1325         if (ctx->inuse > ctx->maxinuse) {
1326                 ctx->maxinuse = ctx->inuse;
1327                 if (ctx->hi_water != 0U && ctx->inuse > ctx->hi_water &&
1328                     (isc_mem_debugging & ISC_MEM_DEBUGUSAGE) != 0)
1329                         fprintf(stderr, "maxinuse = %lu\n",
1330                                 (unsigned long)ctx->inuse);
1331         }
1332         MCTXUNLOCK(ctx, &ctx->lock);
1333
1334         if (call_water)
1335                 (ctx->water)(ctx->water_arg, ISC_MEM_HIWATER);
1336
1337         return (si);
1338 }
1339
1340 void
1341 isc__mem_free(isc_mem_t *ctx, void *ptr FLARG) {
1342         size_info *si;
1343         size_t size;
1344         isc_boolean_t call_water= ISC_FALSE;
1345
1346         REQUIRE(VALID_CONTEXT(ctx));
1347         REQUIRE(ptr != NULL);
1348
1349         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0) {
1350                 si = &(((size_info *)ptr)[-2]);
1351                 REQUIRE(si->u.ctx == ctx);
1352                 size = si[1].u.size;
1353         } else {
1354                 si = &(((size_info *)ptr)[-1]);
1355                 size = si->u.size;
1356         }
1357
1358         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1359                 MCTXLOCK(ctx, &ctx->lock);
1360                 mem_putunlocked(ctx, si, size);
1361         } else {
1362                 mem_put(ctx, si, size);
1363                 MCTXLOCK(ctx, &ctx->lock);
1364                 mem_putstats(ctx, si, size);
1365         }
1366
1367         DELETE_TRACE(ctx, ptr, size, file, line);
1368
1369         /*
1370          * The check against ctx->lo_water == 0 is for the condition
1371          * when the context was pushed over hi_water but then had
1372          * isc_mem_setwater() called with 0 for hi_water and lo_water.
1373          */
1374         if (ctx->hi_called && 
1375             (ctx->inuse < ctx->lo_water || ctx->lo_water == 0U)) {
1376                 ctx->hi_called = ISC_FALSE;
1377
1378                 if (ctx->water != NULL)
1379                         call_water = ISC_TRUE;
1380         }
1381         MCTXUNLOCK(ctx, &ctx->lock);
1382
1383         if (call_water)
1384                 (ctx->water)(ctx->water_arg, ISC_MEM_LOWATER);
1385 }
1386
1387
1388 /*
1389  * Other useful things.
1390  */
1391
1392 char *
1393 isc__mem_strdup(isc_mem_t *mctx, const char *s FLARG) {
1394         size_t len;
1395         char *ns;
1396
1397         REQUIRE(VALID_CONTEXT(mctx));
1398         REQUIRE(s != NULL);
1399
1400         len = strlen(s);
1401
1402         ns = isc__mem_allocate(mctx, len + 1 FLARG_PASS);
1403
1404         if (ns != NULL)
1405                 strncpy(ns, s, len + 1);
1406
1407         return (ns);
1408 }
1409
1410 void
1411 isc_mem_setdestroycheck(isc_mem_t *ctx, isc_boolean_t flag) {
1412         REQUIRE(VALID_CONTEXT(ctx));
1413         MCTXLOCK(ctx, &ctx->lock);
1414
1415         ctx->checkfree = flag;
1416
1417         MCTXUNLOCK(ctx, &ctx->lock);
1418 }
1419
1420 /*
1421  * Quotas
1422  */
1423
1424 void
1425 isc_mem_setquota(isc_mem_t *ctx, size_t quota) {
1426         REQUIRE(VALID_CONTEXT(ctx));
1427         MCTXLOCK(ctx, &ctx->lock);
1428
1429         ctx->quota = quota;
1430
1431         MCTXUNLOCK(ctx, &ctx->lock);
1432 }
1433
1434 size_t
1435 isc_mem_getquota(isc_mem_t *ctx) {
1436         size_t quota;
1437
1438         REQUIRE(VALID_CONTEXT(ctx));
1439         MCTXLOCK(ctx, &ctx->lock);
1440
1441         quota = ctx->quota;
1442
1443         MCTXUNLOCK(ctx, &ctx->lock);
1444
1445         return (quota);
1446 }
1447
1448 size_t
1449 isc_mem_inuse(isc_mem_t *ctx) {
1450         size_t inuse;
1451
1452         REQUIRE(VALID_CONTEXT(ctx));
1453         MCTXLOCK(ctx, &ctx->lock);
1454
1455         inuse = ctx->inuse;
1456
1457         MCTXUNLOCK(ctx, &ctx->lock);
1458
1459         return (inuse);
1460 }
1461
1462 void
1463 isc_mem_setwater(isc_mem_t *ctx, isc_mem_water_t water, void *water_arg,
1464                  size_t hiwater, size_t lowater)
1465 {
1466         isc_boolean_t callwater = ISC_FALSE;
1467         isc_mem_water_t oldwater;
1468         void *oldwater_arg;
1469
1470         REQUIRE(VALID_CONTEXT(ctx));
1471         REQUIRE(hiwater >= lowater);
1472
1473         MCTXLOCK(ctx, &ctx->lock);
1474         oldwater = ctx->water;
1475         oldwater_arg = ctx->water_arg;
1476         if (water == NULL) {
1477                 callwater = ctx->hi_called;
1478                 ctx->water = NULL;
1479                 ctx->water_arg = NULL;
1480                 ctx->hi_water = 0;
1481                 ctx->lo_water = 0;
1482                 ctx->hi_called = ISC_FALSE;
1483         } else {
1484                 if (ctx->hi_called &&
1485                     (ctx->water != water || ctx->water_arg != water_arg ||
1486                      ctx->inuse < lowater || lowater == 0U))
1487                         callwater = ISC_TRUE;
1488                 ctx->water = water;
1489                 ctx->water_arg = water_arg;
1490                 ctx->hi_water = hiwater;
1491                 ctx->lo_water = lowater;
1492                 ctx->hi_called = ISC_FALSE;
1493         }
1494         MCTXUNLOCK(ctx, &ctx->lock);
1495         
1496         if (callwater && oldwater != NULL)
1497                 (oldwater)(oldwater_arg, ISC_MEM_LOWATER);
1498 }
1499
1500 /*
1501  * Memory pool stuff
1502  */
1503
1504 isc_result_t
1505 isc_mempool_create(isc_mem_t *mctx, size_t size, isc_mempool_t **mpctxp) {
1506         isc_mempool_t *mpctx;
1507
1508         REQUIRE(VALID_CONTEXT(mctx));
1509         REQUIRE(size > 0U);
1510         REQUIRE(mpctxp != NULL && *mpctxp == NULL);
1511
1512         /*
1513          * Allocate space for this pool, initialize values, and if all works
1514          * well, attach to the memory context.
1515          */
1516         mpctx = isc_mem_get(mctx, sizeof(isc_mempool_t));
1517         if (mpctx == NULL)
1518                 return (ISC_R_NOMEMORY);
1519
1520         mpctx->magic = MEMPOOL_MAGIC;
1521         mpctx->lock = NULL;
1522         mpctx->mctx = mctx;
1523         mpctx->size = size;
1524         mpctx->maxalloc = UINT_MAX;
1525         mpctx->allocated = 0;
1526         mpctx->freecount = 0;
1527         mpctx->freemax = 1;
1528         mpctx->fillcount = 1;
1529         mpctx->gets = 0;
1530 #if ISC_MEMPOOL_NAMES
1531         mpctx->name[0] = 0;
1532 #endif
1533         mpctx->items = NULL;
1534
1535         *mpctxp = mpctx;
1536
1537         MCTXLOCK(mctx, &mctx->lock);
1538         ISC_LIST_INITANDAPPEND(mctx->pools, mpctx, link);
1539         MCTXUNLOCK(mctx, &mctx->lock);
1540
1541         return (ISC_R_SUCCESS);
1542 }
1543
1544 void
1545 isc_mempool_setname(isc_mempool_t *mpctx, const char *name) {
1546         REQUIRE(name != NULL);
1547
1548 #if ISC_MEMPOOL_NAMES
1549         if (mpctx->lock != NULL)
1550                 LOCK(mpctx->lock);
1551
1552         strncpy(mpctx->name, name, sizeof(mpctx->name) - 1);
1553         mpctx->name[sizeof(mpctx->name) - 1] = '\0';
1554
1555         if (mpctx->lock != NULL)
1556                 UNLOCK(mpctx->lock);
1557 #else
1558         UNUSED(mpctx);
1559         UNUSED(name);
1560 #endif
1561 }
1562
1563 void
1564 isc_mempool_destroy(isc_mempool_t **mpctxp) {
1565         isc_mempool_t *mpctx;
1566         isc_mem_t *mctx;
1567         isc_mutex_t *lock;
1568         element *item;
1569
1570         REQUIRE(mpctxp != NULL);
1571         mpctx = *mpctxp;
1572         REQUIRE(VALID_MEMPOOL(mpctx));
1573 #if ISC_MEMPOOL_NAMES
1574         if (mpctx->allocated > 0)
1575                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1576                                  "isc_mempool_destroy(): mempool %s "
1577                                  "leaked memory",
1578                                  mpctx->name);
1579 #endif
1580         REQUIRE(mpctx->allocated == 0);
1581
1582         mctx = mpctx->mctx;
1583
1584         lock = mpctx->lock;
1585
1586         if (lock != NULL)
1587                 LOCK(lock);
1588
1589         /*
1590          * Return any items on the free list
1591          */
1592         MCTXLOCK(mctx, &mctx->lock);
1593         while (mpctx->items != NULL) {
1594                 INSIST(mpctx->freecount > 0);
1595                 mpctx->freecount--;
1596                 item = mpctx->items;
1597                 mpctx->items = item->next;
1598
1599                 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1600                         mem_putunlocked(mctx, item, mpctx->size);
1601                 } else {
1602                         mem_put(mctx, item, mpctx->size);
1603                         mem_putstats(mctx, item, mpctx->size);
1604                 }
1605         }
1606         MCTXUNLOCK(mctx, &mctx->lock);
1607
1608         /*
1609          * Remove our linked list entry from the memory context.
1610          */
1611         MCTXLOCK(mctx, &mctx->lock);
1612         ISC_LIST_UNLINK(mctx->pools, mpctx, link);
1613         MCTXUNLOCK(mctx, &mctx->lock);
1614
1615         mpctx->magic = 0;
1616
1617         isc_mem_put(mpctx->mctx, mpctx, sizeof(isc_mempool_t));
1618
1619         if (lock != NULL)
1620                 UNLOCK(lock);
1621
1622         *mpctxp = NULL;
1623 }
1624
1625 void
1626 isc_mempool_associatelock(isc_mempool_t *mpctx, isc_mutex_t *lock) {
1627         REQUIRE(VALID_MEMPOOL(mpctx));
1628         REQUIRE(mpctx->lock == NULL);
1629         REQUIRE(lock != NULL);
1630
1631         mpctx->lock = lock;
1632 }
1633
1634 void *
1635 isc__mempool_get(isc_mempool_t *mpctx FLARG) {
1636         element *item;
1637         isc_mem_t *mctx;
1638         unsigned int i;
1639
1640         REQUIRE(VALID_MEMPOOL(mpctx));
1641
1642         mctx = mpctx->mctx;
1643
1644         if (mpctx->lock != NULL)
1645                 LOCK(mpctx->lock);
1646
1647         /*
1648          * Don't let the caller go over quota
1649          */
1650         if (mpctx->allocated >= mpctx->maxalloc) {
1651                 item = NULL;
1652                 goto out;
1653         }
1654
1655         /*
1656          * if we have a free list item, return the first here
1657          */
1658         item = mpctx->items;
1659         if (item != NULL) {
1660                 mpctx->items = item->next;
1661                 INSIST(mpctx->freecount > 0);
1662                 mpctx->freecount--;
1663                 mpctx->gets++;
1664                 mpctx->allocated++;
1665                 goto out;
1666         }
1667
1668         /*
1669          * We need to dip into the well.  Lock the memory context here and
1670          * fill up our free list.
1671          */
1672         MCTXLOCK(mctx, &mctx->lock);
1673         for (i = 0; i < mpctx->fillcount; i++) {
1674                 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1675                         item = mem_getunlocked(mctx, mpctx->size);
1676                 } else {
1677                         item = mem_get(mctx, mpctx->size);
1678                         if (item != NULL)
1679                                 mem_getstats(mctx, mpctx->size);
1680                 }
1681                 if (item == NULL)
1682                         break;
1683                 item->next = mpctx->items;
1684                 mpctx->items = item;
1685                 mpctx->freecount++;
1686         }
1687         MCTXUNLOCK(mctx, &mctx->lock);
1688
1689         /*
1690          * If we didn't get any items, return NULL.
1691          */
1692         item = mpctx->items;
1693         if (item == NULL)
1694                 goto out;
1695
1696         mpctx->items = item->next;
1697         mpctx->freecount--;
1698         mpctx->gets++;
1699         mpctx->allocated++;
1700
1701  out:
1702         if (mpctx->lock != NULL)
1703                 UNLOCK(mpctx->lock);
1704
1705 #if ISC_MEM_TRACKLINES
1706         if (item != NULL) {
1707                 MCTXLOCK(mctx, &mctx->lock);
1708                 ADD_TRACE(mctx, item, mpctx->size, file, line);
1709                 MCTXUNLOCK(mctx, &mctx->lock);
1710         }
1711 #endif /* ISC_MEM_TRACKLINES */
1712
1713         return (item);
1714 }
1715
1716 void
1717 isc__mempool_put(isc_mempool_t *mpctx, void *mem FLARG) {
1718         isc_mem_t *mctx;
1719         element *item;
1720
1721         REQUIRE(VALID_MEMPOOL(mpctx));
1722         REQUIRE(mem != NULL);
1723
1724         mctx = mpctx->mctx;
1725
1726         if (mpctx->lock != NULL)
1727                 LOCK(mpctx->lock);
1728
1729         INSIST(mpctx->allocated > 0);
1730         mpctx->allocated--;
1731
1732 #if ISC_MEM_TRACKLINES
1733         MCTXLOCK(mctx, &mctx->lock);
1734         DELETE_TRACE(mctx, mem, mpctx->size, file, line);
1735         MCTXUNLOCK(mctx, &mctx->lock);
1736 #endif /* ISC_MEM_TRACKLINES */
1737
1738         /*
1739          * If our free list is full, return this to the mctx directly.
1740          */
1741         if (mpctx->freecount >= mpctx->freemax) {
1742                 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1743                         MCTXLOCK(mctx, &mctx->lock);
1744                         mem_putunlocked(mctx, mem, mpctx->size);
1745                         MCTXUNLOCK(mctx, &mctx->lock);
1746                 } else {
1747                         mem_put(mctx, mem, mpctx->size);
1748                         MCTXLOCK(mctx, &mctx->lock);
1749                         mem_putstats(mctx, mem, mpctx->size);
1750                         MCTXUNLOCK(mctx, &mctx->lock);
1751                 }
1752                 if (mpctx->lock != NULL)
1753                         UNLOCK(mpctx->lock);
1754                 return;
1755         }
1756
1757         /*
1758          * Otherwise, attach it to our free list and bump the counter.
1759          */
1760         mpctx->freecount++;
1761         item = (element *)mem;
1762         item->next = mpctx->items;
1763         mpctx->items = item;
1764
1765         if (mpctx->lock != NULL)
1766                 UNLOCK(mpctx->lock);
1767 }
1768
1769 /*
1770  * Quotas
1771  */
1772
1773 void
1774 isc_mempool_setfreemax(isc_mempool_t *mpctx, unsigned int limit) {
1775         REQUIRE(VALID_MEMPOOL(mpctx));
1776
1777         if (mpctx->lock != NULL)
1778                 LOCK(mpctx->lock);
1779
1780         mpctx->freemax = limit;
1781
1782         if (mpctx->lock != NULL)
1783                 UNLOCK(mpctx->lock);
1784 }
1785
1786 unsigned int
1787 isc_mempool_getfreemax(isc_mempool_t *mpctx) {
1788         unsigned int freemax;
1789
1790         REQUIRE(VALID_MEMPOOL(mpctx));
1791
1792         if (mpctx->lock != NULL)
1793                 LOCK(mpctx->lock);
1794
1795         freemax = mpctx->freemax;
1796
1797         if (mpctx->lock != NULL)
1798                 UNLOCK(mpctx->lock);
1799
1800         return (freemax);
1801 }
1802
1803 unsigned int
1804 isc_mempool_getfreecount(isc_mempool_t *mpctx) {
1805         unsigned int freecount;
1806
1807         REQUIRE(VALID_MEMPOOL(mpctx));
1808
1809         if (mpctx->lock != NULL)
1810                 LOCK(mpctx->lock);
1811
1812         freecount = mpctx->freecount;
1813
1814         if (mpctx->lock != NULL)
1815                 UNLOCK(mpctx->lock);
1816
1817         return (freecount);
1818 }
1819
1820 void
1821 isc_mempool_setmaxalloc(isc_mempool_t *mpctx, unsigned int limit) {
1822         REQUIRE(limit > 0);
1823
1824         REQUIRE(VALID_MEMPOOL(mpctx));
1825
1826         if (mpctx->lock != NULL)
1827                 LOCK(mpctx->lock);
1828
1829         mpctx->maxalloc = limit;
1830
1831         if (mpctx->lock != NULL)
1832                 UNLOCK(mpctx->lock);
1833 }
1834
1835 unsigned int
1836 isc_mempool_getmaxalloc(isc_mempool_t *mpctx) {
1837         unsigned int maxalloc;
1838
1839         REQUIRE(VALID_MEMPOOL(mpctx));
1840
1841         if (mpctx->lock != NULL)
1842                 LOCK(mpctx->lock);
1843
1844         maxalloc = mpctx->maxalloc;
1845
1846         if (mpctx->lock != NULL)
1847                 UNLOCK(mpctx->lock);
1848
1849         return (maxalloc);
1850 }
1851
1852 unsigned int
1853 isc_mempool_getallocated(isc_mempool_t *mpctx) {
1854         unsigned int allocated;
1855
1856         REQUIRE(VALID_MEMPOOL(mpctx));
1857
1858         if (mpctx->lock != NULL)
1859                 LOCK(mpctx->lock);
1860
1861         allocated = mpctx->allocated;
1862
1863         if (mpctx->lock != NULL)
1864                 UNLOCK(mpctx->lock);
1865
1866         return (allocated);
1867 }
1868
1869 void
1870 isc_mempool_setfillcount(isc_mempool_t *mpctx, unsigned int limit) {
1871         REQUIRE(limit > 0);
1872         REQUIRE(VALID_MEMPOOL(mpctx));
1873
1874         if (mpctx->lock != NULL)
1875                 LOCK(mpctx->lock);
1876
1877         mpctx->fillcount = limit;
1878
1879         if (mpctx->lock != NULL)
1880                 UNLOCK(mpctx->lock);
1881 }
1882
1883 unsigned int
1884 isc_mempool_getfillcount(isc_mempool_t *mpctx) {
1885         unsigned int fillcount;
1886
1887         REQUIRE(VALID_MEMPOOL(mpctx));
1888
1889         if (mpctx->lock != NULL)
1890                 LOCK(mpctx->lock);
1891
1892         fillcount = mpctx->fillcount;
1893
1894         if (mpctx->lock != NULL)
1895                 UNLOCK(mpctx->lock);
1896
1897         return (fillcount);
1898 }
1899
1900 void
1901 isc_mem_printactive(isc_mem_t *ctx, FILE *file) {
1902
1903         REQUIRE(VALID_CONTEXT(ctx));
1904         REQUIRE(file != NULL);
1905
1906 #if !ISC_MEM_TRACKLINES
1907         UNUSED(ctx);
1908         UNUSED(file);
1909 #else
1910         print_active(ctx, file);
1911 #endif
1912 }
1913
1914 void
1915 isc_mem_printallactive(FILE *file) {
1916 #if !ISC_MEM_TRACKLINES
1917         UNUSED(file);
1918 #else
1919         isc_mem_t *ctx;
1920
1921         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
1922
1923         LOCK(&lock);
1924         for (ctx = ISC_LIST_HEAD(contexts);
1925              ctx != NULL;
1926              ctx = ISC_LIST_NEXT(ctx, link)) {
1927                 fprintf(file, "context: %p\n", ctx);
1928                 print_active(ctx, file);
1929         }
1930         UNLOCK(&lock);
1931 #endif
1932 }
1933
1934 void    
1935 isc_mem_checkdestroyed(FILE *file) {
1936
1937         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
1938
1939         LOCK(&lock);
1940         if (!ISC_LIST_EMPTY(contexts))  {
1941 #if ISC_MEM_TRACKLINES
1942                 isc_mem_t *ctx;
1943
1944                 for (ctx = ISC_LIST_HEAD(contexts);
1945                      ctx != NULL;
1946                      ctx = ISC_LIST_NEXT(ctx, link)) {
1947                         fprintf(file, "context: %p\n", ctx);
1948                         print_active(ctx, file);
1949                 }
1950                 fflush(file);
1951 #endif
1952                 INSIST(0);
1953         }
1954         UNLOCK(&lock);
1955 }