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