]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bind9/lib/isc/mem.c
This commit was generated by cvs2svn to compensate for changes in r171322,
[FreeBSD/FreeBSD.git] / contrib / bind9 / lib / isc / mem.c
1 /*
2  * Copyright (C) 2004-2006  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 1997-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and 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.12 2006/12/08 05:07:59 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 }
695
696 /*
697  * Public.
698  */
699
700 isc_result_t
701 isc_mem_createx(size_t init_max_size, size_t target_size,
702                 isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg,
703                 isc_mem_t **ctxp)
704 {
705         return (isc_mem_createx2(init_max_size, target_size, memalloc, memfree,
706                                  arg, ctxp, ISC_MEMFLAG_DEFAULT));
707                                  
708 }
709
710 isc_result_t
711 isc_mem_createx2(size_t init_max_size, size_t target_size,
712                  isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg,
713                  isc_mem_t **ctxp, unsigned int flags)
714 {
715         isc_mem_t *ctx;
716         isc_result_t result;
717
718         REQUIRE(ctxp != NULL && *ctxp == NULL);
719         REQUIRE(memalloc != NULL);
720         REQUIRE(memfree != NULL);
721
722         INSIST((ALIGNMENT_SIZE & (ALIGNMENT_SIZE - 1)) == 0);
723
724         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
725
726         ctx = (memalloc)(arg, sizeof(*ctx));
727         if (ctx == NULL)
728                 return (ISC_R_NOMEMORY);
729
730         if ((flags & ISC_MEMFLAG_NOLOCK) == 0) {
731                 result = isc_mutex_init(&ctx->lock);
732                 if (result != ISC_R_SUCCESS) {
733                         (memfree)(arg, ctx);
734                         return (result);
735                 }
736         }
737
738         if (init_max_size == 0U)
739                 ctx->max_size = DEF_MAX_SIZE;
740         else
741                 ctx->max_size = init_max_size;
742         ctx->flags = flags;
743         ctx->references = 1;
744         ctx->quota = 0;
745         ctx->total = 0;
746         ctx->inuse = 0;
747         ctx->maxinuse = 0;
748         ctx->hi_water = 0;
749         ctx->lo_water = 0;
750         ctx->hi_called = ISC_FALSE;
751         ctx->water = NULL;
752         ctx->water_arg = NULL;
753         ctx->magic = MEM_MAGIC;
754         isc_ondestroy_init(&ctx->ondestroy);
755         ctx->memalloc = memalloc;
756         ctx->memfree = memfree;
757         ctx->arg = arg;
758         ctx->stats = NULL;
759         ctx->checkfree = ISC_TRUE;
760 #if ISC_MEM_TRACKLINES
761         ctx->debuglist = NULL;
762 #endif
763         ISC_LIST_INIT(ctx->pools);
764         ctx->freelists = NULL;
765         ctx->basic_blocks = NULL;
766         ctx->basic_table = NULL;
767         ctx->basic_table_count = 0;
768         ctx->basic_table_size = 0;
769         ctx->lowest = NULL;
770         ctx->highest = NULL;
771
772         ctx->stats = (memalloc)(arg,
773                                 (ctx->max_size+1) * sizeof(struct stats));
774         if (ctx->stats == NULL) {
775                 result = ISC_R_NOMEMORY;
776                 goto error;
777         }
778         memset(ctx->stats, 0, (ctx->max_size + 1) * sizeof(struct stats));
779
780         if ((flags & ISC_MEMFLAG_INTERNAL) != 0) {
781                 if (target_size == 0U)
782                         ctx->mem_target = DEF_MEM_TARGET;
783                 else
784                         ctx->mem_target = target_size;
785                 ctx->freelists = (memalloc)(arg, ctx->max_size *
786                                                  sizeof(element *));
787                 if (ctx->freelists == NULL) {
788                         result = ISC_R_NOMEMORY;
789                         goto error;
790                 }
791                 memset(ctx->freelists, 0,
792                        ctx->max_size * sizeof(element *));
793         }
794
795 #if ISC_MEM_TRACKLINES
796         if ((isc_mem_debugging & ISC_MEM_DEBUGRECORD) != 0) {
797                 unsigned int i;
798
799                 ctx->debuglist = (memalloc)(arg,
800                                       (ctx->max_size+1) * sizeof(debuglist_t));
801                 if (ctx->debuglist == NULL) {
802                         result = ISC_R_NOMEMORY;
803                         goto error;
804                 }
805                 for (i = 0; i <= ctx->max_size; i++)
806                         ISC_LIST_INIT(ctx->debuglist[i]);
807         }
808 #endif
809
810         ctx->memalloc_failures = 0;
811
812         LOCK(&lock);
813         ISC_LIST_INITANDAPPEND(contexts, ctx, link);
814         UNLOCK(&lock);
815
816         *ctxp = ctx;
817         return (ISC_R_SUCCESS);
818
819   error:
820         if (ctx != NULL) {
821                 if (ctx->stats != NULL)
822                         (memfree)(arg, ctx->stats);
823                 if (ctx->freelists != NULL)
824                         (memfree)(arg, ctx->freelists);
825 #if ISC_MEM_TRACKLINES
826                 if (ctx->debuglist != NULL)
827                         (ctx->memfree)(ctx->arg, ctx->debuglist);
828 #endif /* ISC_MEM_TRACKLINES */
829                 if ((ctx->flags & ISC_MEMFLAG_NOLOCK) == 0)
830                         DESTROYLOCK(&ctx->lock);
831                 (memfree)(arg, ctx);
832         }
833
834         return (result);
835 }
836
837 isc_result_t
838 isc_mem_create(size_t init_max_size, size_t target_size,
839                isc_mem_t **ctxp)
840 {
841         return (isc_mem_createx2(init_max_size, target_size,
842                                  default_memalloc, default_memfree, NULL,
843                                  ctxp, ISC_MEMFLAG_DEFAULT));
844 }
845
846 isc_result_t
847 isc_mem_create2(size_t init_max_size, size_t target_size,
848                 isc_mem_t **ctxp, unsigned int flags)
849 {
850         return (isc_mem_createx2(init_max_size, target_size,
851                                  default_memalloc, default_memfree, NULL,
852                                  ctxp, flags));
853 }
854
855 static void
856 destroy(isc_mem_t *ctx) {
857         unsigned int i;
858         isc_ondestroy_t ondest;
859
860         ctx->magic = 0;
861
862         LOCK(&lock);
863         ISC_LIST_UNLINK(contexts, ctx, link);
864         UNLOCK(&lock);
865
866         INSIST(ISC_LIST_EMPTY(ctx->pools));
867
868 #if ISC_MEM_TRACKLINES
869         if (ctx->debuglist != NULL) {
870                 if (ctx->checkfree) {
871                         for (i = 0; i <= ctx->max_size; i++) {
872                                 if (!ISC_LIST_EMPTY(ctx->debuglist[i]))
873                                         print_active(ctx, stderr);
874                                 INSIST(ISC_LIST_EMPTY(ctx->debuglist[i]));
875                         }
876                 } else {
877                         debuglink_t *dl;
878
879                         for (i = 0; i <= ctx->max_size; i++)
880                                 for (dl = ISC_LIST_HEAD(ctx->debuglist[i]);
881                                      dl != NULL;
882                                      dl = ISC_LIST_HEAD(ctx->debuglist[i])) {
883                                         ISC_LIST_UNLINK(ctx->debuglist[i],
884                                                         dl, link);
885                                         free(dl);
886                                 }
887                 }
888                 (ctx->memfree)(ctx->arg, ctx->debuglist);
889         }
890 #endif
891         INSIST(ctx->references == 0);
892
893         if (ctx->checkfree) {
894                 for (i = 0; i <= ctx->max_size; i++) {
895 #if ISC_MEM_TRACKLINES
896                         if (ctx->stats[i].gets != 0U)
897                                 print_active(ctx, stderr);
898 #endif
899                         INSIST(ctx->stats[i].gets == 0U);
900                 }
901         }
902
903         (ctx->memfree)(ctx->arg, ctx->stats);
904
905         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
906                 for (i = 0; i < ctx->basic_table_count; i++)
907                         (ctx->memfree)(ctx->arg, ctx->basic_table[i]);
908                 (ctx->memfree)(ctx->arg, ctx->freelists);
909                 (ctx->memfree)(ctx->arg, ctx->basic_table);
910         }
911
912         ondest = ctx->ondestroy;
913
914         if ((ctx->flags & ISC_MEMFLAG_NOLOCK) == 0)
915                 DESTROYLOCK(&ctx->lock);
916         (ctx->memfree)(ctx->arg, ctx);
917
918         isc_ondestroy_notify(&ondest, ctx);
919 }
920
921 void
922 isc_mem_attach(isc_mem_t *source, isc_mem_t **targetp) {
923         REQUIRE(VALID_CONTEXT(source));
924         REQUIRE(targetp != NULL && *targetp == NULL);
925
926         MCTXLOCK(source, &source->lock);
927         source->references++;
928         MCTXUNLOCK(source, &source->lock);
929
930         *targetp = source;
931 }
932
933 void
934 isc_mem_detach(isc_mem_t **ctxp) {
935         isc_mem_t *ctx;
936         isc_boolean_t want_destroy = ISC_FALSE;
937
938         REQUIRE(ctxp != NULL);
939         ctx = *ctxp;
940         REQUIRE(VALID_CONTEXT(ctx));
941
942         MCTXLOCK(ctx, &ctx->lock);
943         INSIST(ctx->references > 0);
944         ctx->references--;
945         if (ctx->references == 0)
946                 want_destroy = ISC_TRUE;
947         MCTXUNLOCK(ctx, &ctx->lock);
948
949         if (want_destroy)
950                 destroy(ctx);
951
952         *ctxp = NULL;
953 }
954
955 /*
956  * isc_mem_putanddetach() is the equivalent of:
957  *
958  * mctx = NULL;
959  * isc_mem_attach(ptr->mctx, &mctx);
960  * isc_mem_detach(&ptr->mctx);
961  * isc_mem_put(mctx, ptr, sizeof(*ptr);
962  * isc_mem_detach(&mctx);
963  */
964
965 void
966 isc__mem_putanddetach(isc_mem_t **ctxp, void *ptr, size_t size FLARG) {
967         isc_mem_t *ctx;
968         isc_boolean_t want_destroy = ISC_FALSE;
969         size_info *si;
970         size_t oldsize;
971
972         REQUIRE(ctxp != NULL);
973         ctx = *ctxp;
974         REQUIRE(VALID_CONTEXT(ctx));
975         REQUIRE(ptr != NULL);
976
977         /*
978          * Must be before mem_putunlocked() as ctxp is usually within
979          * [ptr..ptr+size).
980          */
981         *ctxp = NULL;
982
983         if ((isc_mem_debugging & (ISC_MEM_DEBUGSIZE|ISC_MEM_DEBUGCTX)) != 0) {
984                 if ((isc_mem_debugging & ISC_MEM_DEBUGSIZE) != 0) {
985                         si = &(((size_info *)ptr)[-1]);
986                         oldsize = si->u.size - ALIGNMENT_SIZE;
987                         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)
988                                 oldsize -= ALIGNMENT_SIZE;
989                         INSIST(oldsize == size);
990                 }
991                 isc__mem_free(ctx, ptr FLARG_PASS);
992
993                 MCTXLOCK(ctx, &ctx->lock);
994                 ctx->references--;
995                 if (ctx->references == 0)
996                         want_destroy = ISC_TRUE;
997                 MCTXUNLOCK(ctx, &ctx->lock);
998                 if (want_destroy)
999                         destroy(ctx);
1000
1001                 return;
1002         }
1003
1004         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1005                 MCTXLOCK(ctx, &ctx->lock);
1006                 mem_putunlocked(ctx, ptr, size);
1007         } else {
1008                 mem_put(ctx, ptr, size);
1009                 MCTXLOCK(ctx, &ctx->lock);
1010                 mem_putstats(ctx, ptr, size);
1011         }
1012
1013         DELETE_TRACE(ctx, ptr, size, file, line);
1014         INSIST(ctx->references > 0);
1015         ctx->references--;
1016         if (ctx->references == 0)
1017                 want_destroy = ISC_TRUE;
1018
1019         MCTXUNLOCK(ctx, &ctx->lock);
1020
1021         if (want_destroy)
1022                 destroy(ctx);
1023 }
1024
1025 void
1026 isc_mem_destroy(isc_mem_t **ctxp) {
1027         isc_mem_t *ctx;
1028
1029         /*
1030          * This routine provides legacy support for callers who use mctxs
1031          * without attaching/detaching.
1032          */
1033
1034         REQUIRE(ctxp != NULL);
1035         ctx = *ctxp;
1036         REQUIRE(VALID_CONTEXT(ctx));
1037
1038         MCTXLOCK(ctx, &ctx->lock);
1039 #if ISC_MEM_TRACKLINES
1040         if (ctx->references != 1)
1041                 print_active(ctx, stderr);
1042 #endif
1043         REQUIRE(ctx->references == 1);
1044         ctx->references--;
1045         MCTXUNLOCK(ctx, &ctx->lock);
1046
1047         destroy(ctx);
1048
1049         *ctxp = NULL;
1050 }
1051
1052 isc_result_t
1053 isc_mem_ondestroy(isc_mem_t *ctx, isc_task_t *task, isc_event_t **event) {
1054         isc_result_t res;
1055
1056         MCTXLOCK(ctx, &ctx->lock);
1057         res = isc_ondestroy_register(&ctx->ondestroy, task, event);
1058         MCTXUNLOCK(ctx, &ctx->lock);
1059
1060         return (res);
1061 }
1062
1063
1064 void *
1065 isc__mem_get(isc_mem_t *ctx, size_t size FLARG) {
1066         void *ptr;
1067         isc_boolean_t call_water = ISC_FALSE;
1068
1069         REQUIRE(VALID_CONTEXT(ctx));
1070
1071         if ((isc_mem_debugging & (ISC_MEM_DEBUGSIZE|ISC_MEM_DEBUGCTX)) != 0)
1072                 return (isc__mem_allocate(ctx, size FLARG_PASS));
1073
1074         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1075                 MCTXLOCK(ctx, &ctx->lock);
1076                 ptr = mem_getunlocked(ctx, size);
1077         } else {
1078                 ptr = mem_get(ctx, size);
1079                 MCTXLOCK(ctx, &ctx->lock);
1080                 if (ptr != NULL)
1081                         mem_getstats(ctx, size);
1082         }
1083
1084         ADD_TRACE(ctx, ptr, size, file, line);
1085         if (ctx->hi_water != 0U && !ctx->hi_called &&
1086             ctx->inuse > ctx->hi_water) {
1087                 ctx->hi_called = ISC_TRUE;
1088                 call_water = ISC_TRUE;
1089         }
1090         if (ctx->inuse > ctx->maxinuse) {
1091                 ctx->maxinuse = ctx->inuse;
1092                 if (ctx->hi_water != 0U && ctx->inuse > ctx->hi_water &&
1093                     (isc_mem_debugging & ISC_MEM_DEBUGUSAGE) != 0)
1094                         fprintf(stderr, "maxinuse = %lu\n",
1095                                 (unsigned long)ctx->inuse);
1096         }
1097         MCTXUNLOCK(ctx, &ctx->lock);
1098
1099         if (call_water)
1100                 (ctx->water)(ctx->water_arg, ISC_MEM_HIWATER);
1101
1102         return (ptr);
1103 }
1104
1105 void
1106 isc__mem_put(isc_mem_t *ctx, void *ptr, size_t size FLARG)
1107 {
1108         isc_boolean_t call_water = ISC_FALSE;
1109         size_info *si;
1110         size_t oldsize;
1111
1112         REQUIRE(VALID_CONTEXT(ctx));
1113         REQUIRE(ptr != NULL);
1114
1115         if ((isc_mem_debugging & (ISC_MEM_DEBUGSIZE|ISC_MEM_DEBUGCTX)) != 0) {
1116                 if ((isc_mem_debugging & ISC_MEM_DEBUGSIZE) != 0) {
1117                         si = &(((size_info *)ptr)[-1]);
1118                         oldsize = si->u.size - ALIGNMENT_SIZE;
1119                         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)
1120                                 oldsize -= ALIGNMENT_SIZE;
1121                         INSIST(oldsize == size);
1122                 }
1123                 isc__mem_free(ctx, ptr FLARG_PASS);
1124                 return;
1125         }
1126
1127         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1128                 MCTXLOCK(ctx, &ctx->lock);
1129                 mem_putunlocked(ctx, ptr, size);
1130         } else {
1131                 mem_put(ctx, ptr, size);
1132                 MCTXLOCK(ctx, &ctx->lock);
1133                 mem_putstats(ctx, ptr, size);
1134         }
1135
1136         DELETE_TRACE(ctx, ptr, size, file, line);
1137
1138         /*
1139          * The check against ctx->lo_water == 0 is for the condition
1140          * when the context was pushed over hi_water but then had
1141          * isc_mem_setwater() called with 0 for hi_water and lo_water.
1142          */
1143         if (ctx->hi_called && 
1144             (ctx->inuse < ctx->lo_water || ctx->lo_water == 0U)) {
1145                 ctx->hi_called = ISC_FALSE;
1146
1147                 if (ctx->water != NULL)
1148                         call_water = ISC_TRUE;
1149         }
1150         MCTXUNLOCK(ctx, &ctx->lock);
1151
1152         if (call_water)
1153                 (ctx->water)(ctx->water_arg, ISC_MEM_LOWATER);
1154 }
1155
1156 #if ISC_MEM_TRACKLINES
1157 static void
1158 print_active(isc_mem_t *mctx, FILE *out) {
1159         if (mctx->debuglist != NULL) {
1160                 debuglink_t *dl;
1161                 unsigned int i, j;
1162                 const char *format;
1163                 isc_boolean_t found;
1164
1165                 fprintf(out, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1166                                             ISC_MSG_DUMPALLOC,
1167                                             "Dump of all outstanding "
1168                                             "memory allocations:\n"));
1169                 found = ISC_FALSE;
1170                 format = isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1171                                         ISC_MSG_PTRFILELINE,
1172                                         "\tptr %p size %u file %s line %u\n");
1173                 for (i = 0; i <= mctx->max_size; i++) {
1174                         dl = ISC_LIST_HEAD(mctx->debuglist[i]);
1175                         
1176                         if (dl != NULL)
1177                                 found = ISC_TRUE;
1178
1179                         while (dl != NULL) {
1180                                 for (j = 0; j < DEBUGLIST_COUNT; j++)
1181                                         if (dl->ptr[j] != NULL)
1182                                                 fprintf(out, format,
1183                                                         dl->ptr[j],
1184                                                         dl->size[j],
1185                                                         dl->file[j],
1186                                                         dl->line[j]);
1187                                 dl = ISC_LIST_NEXT(dl, link);
1188                         }
1189                 }
1190                 if (!found)
1191                         fprintf(out, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1192                                                     ISC_MSG_NONE, "\tNone.\n"));
1193         }
1194 }
1195 #endif
1196
1197 /*
1198  * Print the stats[] on the stream "out" with suitable formatting.
1199  */
1200 void
1201 isc_mem_stats(isc_mem_t *ctx, FILE *out) {
1202         size_t i;
1203         const struct stats *s;
1204         const isc_mempool_t *pool;
1205
1206         REQUIRE(VALID_CONTEXT(ctx));
1207         MCTXLOCK(ctx, &ctx->lock);
1208
1209         for (i = 0; i <= ctx->max_size; i++) {
1210                 s = &ctx->stats[i];
1211
1212                 if (s->totalgets == 0U && s->gets == 0U)
1213                         continue;
1214                 fprintf(out, "%s%5lu: %11lu gets, %11lu rem",
1215                         (i == ctx->max_size) ? ">=" : "  ",
1216                         (unsigned long) i, s->totalgets, s->gets);
1217                 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0 &&
1218                     (s->blocks != 0U || s->freefrags != 0U))
1219                         fprintf(out, " (%lu bl, %lu ff)",
1220                                 s->blocks, s->freefrags);
1221                 fputc('\n', out);
1222         }
1223
1224         /*
1225          * Note that since a pool can be locked now, these stats might be
1226          * somewhat off if the pool is in active use at the time the stats
1227          * are dumped.  The link fields are protected by the isc_mem_t's
1228          * lock, however, so walking this list and extracting integers from
1229          * stats fields is always safe.
1230          */
1231         pool = ISC_LIST_HEAD(ctx->pools);
1232         if (pool != NULL) {
1233                 fprintf(out, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1234                                             ISC_MSG_POOLSTATS,
1235                                             "[Pool statistics]\n"));
1236                 fprintf(out, "%15s %10s %10s %10s %10s %10s %10s %10s %1s\n",
1237                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1238                                        ISC_MSG_POOLNAME, "name"),
1239                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1240                                        ISC_MSG_POOLSIZE, "size"),
1241                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1242                                        ISC_MSG_POOLMAXALLOC, "maxalloc"),
1243                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1244                                        ISC_MSG_POOLALLOCATED, "allocated"),
1245                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1246                                        ISC_MSG_POOLFREECOUNT, "freecount"),
1247                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1248                                        ISC_MSG_POOLFREEMAX, "freemax"),
1249                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1250                                        ISC_MSG_POOLFILLCOUNT, "fillcount"),
1251                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1252                                        ISC_MSG_POOLGETS, "gets"),
1253                         "L");
1254         }
1255         while (pool != NULL) {
1256                 fprintf(out, "%15s %10lu %10u %10u %10u %10u %10u %10u %s\n",
1257                         pool->name, (unsigned long) pool->size, pool->maxalloc,
1258                         pool->allocated, pool->freecount, pool->freemax,
1259                         pool->fillcount, pool->gets,
1260                         (pool->lock == NULL ? "N" : "Y"));
1261                 pool = ISC_LIST_NEXT(pool, link);
1262         }
1263
1264 #if ISC_MEM_TRACKLINES
1265         print_active(ctx, out);
1266 #endif
1267
1268         MCTXUNLOCK(ctx, &ctx->lock);
1269 }
1270
1271 /*
1272  * Replacements for malloc() and free() -- they implicitly remember the
1273  * size of the object allocated (with some additional overhead).
1274  */
1275
1276 static void *
1277 isc__mem_allocateunlocked(isc_mem_t *ctx, size_t size) {
1278         size_info *si;
1279
1280         size += ALIGNMENT_SIZE;
1281         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)
1282                 size += ALIGNMENT_SIZE;
1283
1284         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0)
1285                 si = mem_getunlocked(ctx, size);
1286         else
1287                 si = mem_get(ctx, size);
1288
1289         if (si == NULL)
1290                 return (NULL);
1291         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0) {
1292                 si->u.ctx = ctx;
1293                 si++;
1294         }
1295         si->u.size = size;
1296         return (&si[1]);
1297 }
1298
1299 void *
1300 isc__mem_allocate(isc_mem_t *ctx, size_t size FLARG) {
1301         size_info *si;
1302         isc_boolean_t call_water = ISC_FALSE;
1303
1304         REQUIRE(VALID_CONTEXT(ctx));
1305
1306         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1307                 MCTXLOCK(ctx, &ctx->lock);
1308                 si = isc__mem_allocateunlocked(ctx, size);
1309         } else {
1310                 si = isc__mem_allocateunlocked(ctx, size);
1311                 MCTXLOCK(ctx, &ctx->lock);
1312                 if (si != NULL)
1313                         mem_getstats(ctx, si[-1].u.size);
1314         }
1315
1316 #if ISC_MEM_TRACKLINES
1317         ADD_TRACE(ctx, si, si[-1].u.size, file, line);
1318 #endif
1319         if (ctx->hi_water != 0U && !ctx->hi_called &&
1320             ctx->inuse > ctx->hi_water) {
1321                 ctx->hi_called = ISC_TRUE;
1322                 call_water = ISC_TRUE;
1323         }
1324         if (ctx->inuse > ctx->maxinuse) {
1325                 ctx->maxinuse = ctx->inuse;
1326                 if (ctx->hi_water != 0U && ctx->inuse > ctx->hi_water &&
1327                     (isc_mem_debugging & ISC_MEM_DEBUGUSAGE) != 0)
1328                         fprintf(stderr, "maxinuse = %lu\n",
1329                                 (unsigned long)ctx->inuse);
1330         }
1331         MCTXUNLOCK(ctx, &ctx->lock);
1332
1333         if (call_water)
1334                 (ctx->water)(ctx->water_arg, ISC_MEM_HIWATER);
1335
1336         return (si);
1337 }
1338
1339 void
1340 isc__mem_free(isc_mem_t *ctx, void *ptr FLARG) {
1341         size_info *si;
1342         size_t size;
1343         isc_boolean_t call_water= ISC_FALSE;
1344
1345         REQUIRE(VALID_CONTEXT(ctx));
1346         REQUIRE(ptr != NULL);
1347
1348         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0) {
1349                 si = &(((size_info *)ptr)[-2]);
1350                 REQUIRE(si->u.ctx == ctx);
1351                 size = si[1].u.size;
1352         } else {
1353                 si = &(((size_info *)ptr)[-1]);
1354                 size = si->u.size;
1355         }
1356
1357         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1358                 MCTXLOCK(ctx, &ctx->lock);
1359                 mem_putunlocked(ctx, si, size);
1360         } else {
1361                 mem_put(ctx, si, size);
1362                 MCTXLOCK(ctx, &ctx->lock);
1363                 mem_putstats(ctx, si, size);
1364         }
1365
1366         DELETE_TRACE(ctx, ptr, size, file, line);
1367
1368         /*
1369          * The check against ctx->lo_water == 0 is for the condition
1370          * when the context was pushed over hi_water but then had
1371          * isc_mem_setwater() called with 0 for hi_water and lo_water.
1372          */
1373         if (ctx->hi_called && 
1374             (ctx->inuse < ctx->lo_water || ctx->lo_water == 0U)) {
1375                 ctx->hi_called = ISC_FALSE;
1376
1377                 if (ctx->water != NULL)
1378                         call_water = ISC_TRUE;
1379         }
1380         MCTXUNLOCK(ctx, &ctx->lock);
1381
1382         if (call_water)
1383                 (ctx->water)(ctx->water_arg, ISC_MEM_LOWATER);
1384 }
1385
1386
1387 /*
1388  * Other useful things.
1389  */
1390
1391 char *
1392 isc__mem_strdup(isc_mem_t *mctx, const char *s FLARG) {
1393         size_t len;
1394         char *ns;
1395
1396         REQUIRE(VALID_CONTEXT(mctx));
1397         REQUIRE(s != NULL);
1398
1399         len = strlen(s);
1400
1401         ns = isc__mem_allocate(mctx, len + 1 FLARG_PASS);
1402
1403         if (ns != NULL)
1404                 strncpy(ns, s, len + 1);
1405
1406         return (ns);
1407 }
1408
1409 void
1410 isc_mem_setdestroycheck(isc_mem_t *ctx, isc_boolean_t flag) {
1411         REQUIRE(VALID_CONTEXT(ctx));
1412         MCTXLOCK(ctx, &ctx->lock);
1413
1414         ctx->checkfree = flag;
1415
1416         MCTXUNLOCK(ctx, &ctx->lock);
1417 }
1418
1419 /*
1420  * Quotas
1421  */
1422
1423 void
1424 isc_mem_setquota(isc_mem_t *ctx, size_t quota) {
1425         REQUIRE(VALID_CONTEXT(ctx));
1426         MCTXLOCK(ctx, &ctx->lock);
1427
1428         ctx->quota = quota;
1429
1430         MCTXUNLOCK(ctx, &ctx->lock);
1431 }
1432
1433 size_t
1434 isc_mem_getquota(isc_mem_t *ctx) {
1435         size_t quota;
1436
1437         REQUIRE(VALID_CONTEXT(ctx));
1438         MCTXLOCK(ctx, &ctx->lock);
1439
1440         quota = ctx->quota;
1441
1442         MCTXUNLOCK(ctx, &ctx->lock);
1443
1444         return (quota);
1445 }
1446
1447 size_t
1448 isc_mem_inuse(isc_mem_t *ctx) {
1449         size_t inuse;
1450
1451         REQUIRE(VALID_CONTEXT(ctx));
1452         MCTXLOCK(ctx, &ctx->lock);
1453
1454         inuse = ctx->inuse;
1455
1456         MCTXUNLOCK(ctx, &ctx->lock);
1457
1458         return (inuse);
1459 }
1460
1461 void
1462 isc_mem_setwater(isc_mem_t *ctx, isc_mem_water_t water, void *water_arg,
1463                  size_t hiwater, size_t lowater)
1464 {
1465         isc_boolean_t callwater = ISC_FALSE;
1466         isc_mem_water_t oldwater;
1467         void *oldwater_arg;
1468
1469         REQUIRE(VALID_CONTEXT(ctx));
1470         REQUIRE(hiwater >= lowater);
1471
1472         MCTXLOCK(ctx, &ctx->lock);
1473         oldwater = ctx->water;
1474         oldwater_arg = ctx->water_arg;
1475         if (water == NULL) {
1476                 callwater = ctx->hi_called;
1477                 ctx->water = NULL;
1478                 ctx->water_arg = NULL;
1479                 ctx->hi_water = 0;
1480                 ctx->lo_water = 0;
1481                 ctx->hi_called = ISC_FALSE;
1482         } else {
1483                 if (ctx->hi_called &&
1484                     (ctx->water != water || ctx->water_arg != water_arg ||
1485                      ctx->inuse < lowater || lowater == 0U))
1486                         callwater = ISC_TRUE;
1487                 ctx->water = water;
1488                 ctx->water_arg = water_arg;
1489                 ctx->hi_water = hiwater;
1490                 ctx->lo_water = lowater;
1491                 ctx->hi_called = ISC_FALSE;
1492         }
1493         MCTXUNLOCK(ctx, &ctx->lock);
1494         
1495         if (callwater && oldwater != NULL)
1496                 (oldwater)(oldwater_arg, ISC_MEM_LOWATER);
1497 }
1498
1499 /*
1500  * Memory pool stuff
1501  */
1502
1503 isc_result_t
1504 isc_mempool_create(isc_mem_t *mctx, size_t size, isc_mempool_t **mpctxp) {
1505         isc_mempool_t *mpctx;
1506
1507         REQUIRE(VALID_CONTEXT(mctx));
1508         REQUIRE(size > 0U);
1509         REQUIRE(mpctxp != NULL && *mpctxp == NULL);
1510
1511         /*
1512          * Allocate space for this pool, initialize values, and if all works
1513          * well, attach to the memory context.
1514          */
1515         mpctx = isc_mem_get(mctx, sizeof(isc_mempool_t));
1516         if (mpctx == NULL)
1517                 return (ISC_R_NOMEMORY);
1518
1519         mpctx->magic = MEMPOOL_MAGIC;
1520         mpctx->lock = NULL;
1521         mpctx->mctx = mctx;
1522         mpctx->size = size;
1523         mpctx->maxalloc = UINT_MAX;
1524         mpctx->allocated = 0;
1525         mpctx->freecount = 0;
1526         mpctx->freemax = 1;
1527         mpctx->fillcount = 1;
1528         mpctx->gets = 0;
1529 #if ISC_MEMPOOL_NAMES
1530         mpctx->name[0] = 0;
1531 #endif
1532         mpctx->items = NULL;
1533
1534         *mpctxp = mpctx;
1535
1536         MCTXLOCK(mctx, &mctx->lock);
1537         ISC_LIST_INITANDAPPEND(mctx->pools, mpctx, link);
1538         MCTXUNLOCK(mctx, &mctx->lock);
1539
1540         return (ISC_R_SUCCESS);
1541 }
1542
1543 void
1544 isc_mempool_setname(isc_mempool_t *mpctx, const char *name) {
1545         REQUIRE(name != NULL);
1546
1547 #if ISC_MEMPOOL_NAMES
1548         if (mpctx->lock != NULL)
1549                 LOCK(mpctx->lock);
1550
1551         strncpy(mpctx->name, name, sizeof(mpctx->name) - 1);
1552         mpctx->name[sizeof(mpctx->name) - 1] = '\0';
1553
1554         if (mpctx->lock != NULL)
1555                 UNLOCK(mpctx->lock);
1556 #else
1557         UNUSED(mpctx);
1558         UNUSED(name);
1559 #endif
1560 }
1561
1562 void
1563 isc_mempool_destroy(isc_mempool_t **mpctxp) {
1564         isc_mempool_t *mpctx;
1565         isc_mem_t *mctx;
1566         isc_mutex_t *lock;
1567         element *item;
1568
1569         REQUIRE(mpctxp != NULL);
1570         mpctx = *mpctxp;
1571         REQUIRE(VALID_MEMPOOL(mpctx));
1572 #if ISC_MEMPOOL_NAMES
1573         if (mpctx->allocated > 0)
1574                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1575                                  "isc_mempool_destroy(): mempool %s "
1576                                  "leaked memory",
1577                                  mpctx->name);
1578 #endif
1579         REQUIRE(mpctx->allocated == 0);
1580
1581         mctx = mpctx->mctx;
1582
1583         lock = mpctx->lock;
1584
1585         if (lock != NULL)
1586                 LOCK(lock);
1587
1588         /*
1589          * Return any items on the free list
1590          */
1591         MCTXLOCK(mctx, &mctx->lock);
1592         while (mpctx->items != NULL) {
1593                 INSIST(mpctx->freecount > 0);
1594                 mpctx->freecount--;
1595                 item = mpctx->items;
1596                 mpctx->items = item->next;
1597
1598                 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1599                         mem_putunlocked(mctx, item, mpctx->size);
1600                 } else {
1601                         mem_put(mctx, item, mpctx->size);
1602                         mem_putstats(mctx, item, mpctx->size);
1603                 }
1604         }
1605         MCTXUNLOCK(mctx, &mctx->lock);
1606
1607         /*
1608          * Remove our linked list entry from the memory context.
1609          */
1610         MCTXLOCK(mctx, &mctx->lock);
1611         ISC_LIST_UNLINK(mctx->pools, mpctx, link);
1612         MCTXUNLOCK(mctx, &mctx->lock);
1613
1614         mpctx->magic = 0;
1615
1616         isc_mem_put(mpctx->mctx, mpctx, sizeof(isc_mempool_t));
1617
1618         if (lock != NULL)
1619                 UNLOCK(lock);
1620
1621         *mpctxp = NULL;
1622 }
1623
1624 void
1625 isc_mempool_associatelock(isc_mempool_t *mpctx, isc_mutex_t *lock) {
1626         REQUIRE(VALID_MEMPOOL(mpctx));
1627         REQUIRE(mpctx->lock == NULL);
1628         REQUIRE(lock != NULL);
1629
1630         mpctx->lock = lock;
1631 }
1632
1633 void *
1634 isc__mempool_get(isc_mempool_t *mpctx FLARG) {
1635         element *item;
1636         isc_mem_t *mctx;
1637         unsigned int i;
1638
1639         REQUIRE(VALID_MEMPOOL(mpctx));
1640
1641         mctx = mpctx->mctx;
1642
1643         if (mpctx->lock != NULL)
1644                 LOCK(mpctx->lock);
1645
1646         /*
1647          * Don't let the caller go over quota
1648          */
1649         if (mpctx->allocated >= mpctx->maxalloc) {
1650                 item = NULL;
1651                 goto out;
1652         }
1653
1654         /*
1655          * if we have a free list item, return the first here
1656          */
1657         item = mpctx->items;
1658         if (item != NULL) {
1659                 mpctx->items = item->next;
1660                 INSIST(mpctx->freecount > 0);
1661                 mpctx->freecount--;
1662                 mpctx->gets++;
1663                 mpctx->allocated++;
1664                 goto out;
1665         }
1666
1667         /*
1668          * We need to dip into the well.  Lock the memory context here and
1669          * fill up our free list.
1670          */
1671         MCTXLOCK(mctx, &mctx->lock);
1672         for (i = 0; i < mpctx->fillcount; i++) {
1673                 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1674                         item = mem_getunlocked(mctx, mpctx->size);
1675                 } else {
1676                         item = mem_get(mctx, mpctx->size);
1677                         if (item != NULL)
1678                                 mem_getstats(mctx, mpctx->size);
1679                 }
1680                 if (item == NULL)
1681                         break;
1682                 item->next = mpctx->items;
1683                 mpctx->items = item;
1684                 mpctx->freecount++;
1685         }
1686         MCTXUNLOCK(mctx, &mctx->lock);
1687
1688         /*
1689          * If we didn't get any items, return NULL.
1690          */
1691         item = mpctx->items;
1692         if (item == NULL)
1693                 goto out;
1694
1695         mpctx->items = item->next;
1696         mpctx->freecount--;
1697         mpctx->gets++;
1698         mpctx->allocated++;
1699
1700  out:
1701         if (mpctx->lock != NULL)
1702                 UNLOCK(mpctx->lock);
1703
1704 #if ISC_MEM_TRACKLINES
1705         if (item != NULL) {
1706                 MCTXLOCK(mctx, &mctx->lock);
1707                 ADD_TRACE(mctx, item, mpctx->size, file, line);
1708                 MCTXUNLOCK(mctx, &mctx->lock);
1709         }
1710 #endif /* ISC_MEM_TRACKLINES */
1711
1712         return (item);
1713 }
1714
1715 void
1716 isc__mempool_put(isc_mempool_t *mpctx, void *mem FLARG) {
1717         isc_mem_t *mctx;
1718         element *item;
1719
1720         REQUIRE(VALID_MEMPOOL(mpctx));
1721         REQUIRE(mem != NULL);
1722
1723         mctx = mpctx->mctx;
1724
1725         if (mpctx->lock != NULL)
1726                 LOCK(mpctx->lock);
1727
1728         INSIST(mpctx->allocated > 0);
1729         mpctx->allocated--;
1730
1731 #if ISC_MEM_TRACKLINES
1732         MCTXLOCK(mctx, &mctx->lock);
1733         DELETE_TRACE(mctx, mem, mpctx->size, file, line);
1734         MCTXUNLOCK(mctx, &mctx->lock);
1735 #endif /* ISC_MEM_TRACKLINES */
1736
1737         /*
1738          * If our free list is full, return this to the mctx directly.
1739          */
1740         if (mpctx->freecount >= mpctx->freemax) {
1741                 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1742                         MCTXLOCK(mctx, &mctx->lock);
1743                         mem_putunlocked(mctx, mem, mpctx->size);
1744                         MCTXUNLOCK(mctx, &mctx->lock);
1745                 } else {
1746                         mem_put(mctx, mem, mpctx->size);
1747                         MCTXLOCK(mctx, &mctx->lock);
1748                         mem_putstats(mctx, mem, mpctx->size);
1749                         MCTXUNLOCK(mctx, &mctx->lock);
1750                 }
1751                 if (mpctx->lock != NULL)
1752                         UNLOCK(mpctx->lock);
1753                 return;
1754         }
1755
1756         /*
1757          * Otherwise, attach it to our free list and bump the counter.
1758          */
1759         mpctx->freecount++;
1760         item = (element *)mem;
1761         item->next = mpctx->items;
1762         mpctx->items = item;
1763
1764         if (mpctx->lock != NULL)
1765                 UNLOCK(mpctx->lock);
1766 }
1767
1768 /*
1769  * Quotas
1770  */
1771
1772 void
1773 isc_mempool_setfreemax(isc_mempool_t *mpctx, unsigned int limit) {
1774         REQUIRE(VALID_MEMPOOL(mpctx));
1775
1776         if (mpctx->lock != NULL)
1777                 LOCK(mpctx->lock);
1778
1779         mpctx->freemax = limit;
1780
1781         if (mpctx->lock != NULL)
1782                 UNLOCK(mpctx->lock);
1783 }
1784
1785 unsigned int
1786 isc_mempool_getfreemax(isc_mempool_t *mpctx) {
1787         unsigned int freemax;
1788
1789         REQUIRE(VALID_MEMPOOL(mpctx));
1790
1791         if (mpctx->lock != NULL)
1792                 LOCK(mpctx->lock);
1793
1794         freemax = mpctx->freemax;
1795
1796         if (mpctx->lock != NULL)
1797                 UNLOCK(mpctx->lock);
1798
1799         return (freemax);
1800 }
1801
1802 unsigned int
1803 isc_mempool_getfreecount(isc_mempool_t *mpctx) {
1804         unsigned int freecount;
1805
1806         REQUIRE(VALID_MEMPOOL(mpctx));
1807
1808         if (mpctx->lock != NULL)
1809                 LOCK(mpctx->lock);
1810
1811         freecount = mpctx->freecount;
1812
1813         if (mpctx->lock != NULL)
1814                 UNLOCK(mpctx->lock);
1815
1816         return (freecount);
1817 }
1818
1819 void
1820 isc_mempool_setmaxalloc(isc_mempool_t *mpctx, unsigned int limit) {
1821         REQUIRE(limit > 0);
1822
1823         REQUIRE(VALID_MEMPOOL(mpctx));
1824
1825         if (mpctx->lock != NULL)
1826                 LOCK(mpctx->lock);
1827
1828         mpctx->maxalloc = limit;
1829
1830         if (mpctx->lock != NULL)
1831                 UNLOCK(mpctx->lock);
1832 }
1833
1834 unsigned int
1835 isc_mempool_getmaxalloc(isc_mempool_t *mpctx) {
1836         unsigned int maxalloc;
1837
1838         REQUIRE(VALID_MEMPOOL(mpctx));
1839
1840         if (mpctx->lock != NULL)
1841                 LOCK(mpctx->lock);
1842
1843         maxalloc = mpctx->maxalloc;
1844
1845         if (mpctx->lock != NULL)
1846                 UNLOCK(mpctx->lock);
1847
1848         return (maxalloc);
1849 }
1850
1851 unsigned int
1852 isc_mempool_getallocated(isc_mempool_t *mpctx) {
1853         unsigned int allocated;
1854
1855         REQUIRE(VALID_MEMPOOL(mpctx));
1856
1857         if (mpctx->lock != NULL)
1858                 LOCK(mpctx->lock);
1859
1860         allocated = mpctx->allocated;
1861
1862         if (mpctx->lock != NULL)
1863                 UNLOCK(mpctx->lock);
1864
1865         return (allocated);
1866 }
1867
1868 void
1869 isc_mempool_setfillcount(isc_mempool_t *mpctx, unsigned int limit) {
1870         REQUIRE(limit > 0);
1871         REQUIRE(VALID_MEMPOOL(mpctx));
1872
1873         if (mpctx->lock != NULL)
1874                 LOCK(mpctx->lock);
1875
1876         mpctx->fillcount = limit;
1877
1878         if (mpctx->lock != NULL)
1879                 UNLOCK(mpctx->lock);
1880 }
1881
1882 unsigned int
1883 isc_mempool_getfillcount(isc_mempool_t *mpctx) {
1884         unsigned int fillcount;
1885
1886         REQUIRE(VALID_MEMPOOL(mpctx));
1887
1888         if (mpctx->lock != NULL)
1889                 LOCK(mpctx->lock);
1890
1891         fillcount = mpctx->fillcount;
1892
1893         if (mpctx->lock != NULL)
1894                 UNLOCK(mpctx->lock);
1895
1896         return (fillcount);
1897 }
1898
1899 void
1900 isc_mem_printactive(isc_mem_t *ctx, FILE *file) {
1901
1902         REQUIRE(VALID_CONTEXT(ctx));
1903         REQUIRE(file != NULL);
1904
1905 #if !ISC_MEM_TRACKLINES
1906         UNUSED(ctx);
1907         UNUSED(file);
1908 #else
1909         print_active(ctx, file);
1910 #endif
1911 }
1912
1913 void
1914 isc_mem_printallactive(FILE *file) {
1915 #if !ISC_MEM_TRACKLINES
1916         UNUSED(file);
1917 #else
1918         isc_mem_t *ctx;
1919
1920         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
1921
1922         LOCK(&lock);
1923         for (ctx = ISC_LIST_HEAD(contexts);
1924              ctx != NULL;
1925              ctx = ISC_LIST_NEXT(ctx, link)) {
1926                 fprintf(file, "context: %p\n", ctx);
1927                 print_active(ctx, file);
1928         }
1929         UNLOCK(&lock);
1930 #endif
1931 }
1932
1933 void    
1934 isc_mem_checkdestroyed(FILE *file) {
1935
1936         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
1937
1938         LOCK(&lock);
1939         if (!ISC_LIST_EMPTY(contexts))  {
1940 #if ISC_MEM_TRACKLINES
1941                 isc_mem_t *ctx;
1942
1943                 for (ctx = ISC_LIST_HEAD(contexts);
1944                      ctx != NULL;
1945                      ctx = ISC_LIST_NEXT(ctx, link)) {
1946                         fprintf(file, "context: %p\n", ctx);
1947                         print_active(ctx, file);
1948                 }
1949                 fflush(file);
1950 #endif
1951                 INSIST(1);
1952         }
1953         UNLOCK(&lock);
1954 }