update to 9.7.1-P2
[tridge/bind9.git] / lib / isc / mem.c
1 /*
2  * Copyright (C) 2004-2010  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.153.104.3 2010/05/12 00:49:31 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 #include <isc/mutex.h>
37 #include <isc/print.h>
38 #include <isc/util.h>
39 #include <isc/xml.h>
40
41 #define MCTXLOCK(m, l) if (((m)->flags & ISC_MEMFLAG_NOLOCK) == 0) LOCK(l)
42 #define MCTXUNLOCK(m, l) if (((m)->flags & ISC_MEMFLAG_NOLOCK) == 0) UNLOCK(l)
43
44 #ifndef ISC_MEM_DEBUGGING
45 #define ISC_MEM_DEBUGGING 0
46 #endif
47 LIBISC_EXTERNAL_DATA unsigned int isc_mem_debugging = ISC_MEM_DEBUGGING;
48
49 /*
50  * Constants.
51  */
52
53 #define DEF_MAX_SIZE            1100
54 #define DEF_MEM_TARGET          4096
55 #define ALIGNMENT_SIZE          8U              /*%< must be a power of 2 */
56 #define NUM_BASIC_BLOCKS        64              /*%< must be > 1 */
57 #define TABLE_INCREMENT         1024
58 #define DEBUGLIST_COUNT         1024
59
60 /*
61  * Types.
62  */
63 typedef struct isc__mem isc__mem_t;
64 typedef struct isc__mempool isc__mempool_t;
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, unsigned 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                 isc__mem_t      *ctx;
96                 char            bytes[ALIGNMENT_SIZE];
97         } u;
98 } size_info;
99
100 struct stats {
101         unsigned long           gets;
102         unsigned long           totalgets;
103         unsigned long           blocks;
104         unsigned long           freefrags;
105 };
106
107 #define MEM_MAGIC               ISC_MAGIC('M', 'e', 'm', 'C')
108 #define VALID_CONTEXT(c)        ISC_MAGIC_VALID(c, MEM_MAGIC)
109
110 #if ISC_MEM_TRACKLINES
111 typedef ISC_LIST(debuglink_t)   debuglist_t;
112 #endif
113
114 /* List of all active memory contexts. */
115
116 static ISC_LIST(isc__mem_t)     contexts;
117 static isc_once_t               once = ISC_ONCE_INIT;
118 static isc_mutex_t              lock;
119
120 /*%
121  * Total size of lost memory due to a bug of external library.
122  * Locked by the global lock.
123  */
124 static isc_uint64_t             totallost;
125
126 struct isc__mem {
127         isc_mem_t               common;
128         isc_ondestroy_t         ondestroy;
129         unsigned int            flags;
130         isc_mutex_t             lock;
131         isc_memalloc_t          memalloc;
132         isc_memfree_t           memfree;
133         void *                  arg;
134         size_t                  max_size;
135         isc_boolean_t           checkfree;
136         struct stats *          stats;
137         unsigned int            references;
138         char                    name[16];
139         void *                  tag;
140         size_t                  quota;
141         size_t                  total;
142         size_t                  inuse;
143         size_t                  maxinuse;
144         size_t                  hi_water;
145         size_t                  lo_water;
146         isc_boolean_t           hi_called;
147         isc_mem_water_t         water;
148         void *                  water_arg;
149         ISC_LIST(isc__mempool_t) pools;
150         unsigned int            poolcnt;
151
152         /*  ISC_MEMFLAG_INTERNAL */
153         size_t                  mem_target;
154         element **              freelists;
155         element *               basic_blocks;
156         unsigned char **        basic_table;
157         unsigned int            basic_table_count;
158         unsigned int            basic_table_size;
159         unsigned char *         lowest;
160         unsigned char *         highest;
161
162 #if ISC_MEM_TRACKLINES
163         debuglist_t *           debuglist;
164         unsigned int            debuglistcnt;
165 #endif
166
167         unsigned int            memalloc_failures;
168         ISC_LINK(isc__mem_t)    link;
169 };
170
171 #define MEMPOOL_MAGIC           ISC_MAGIC('M', 'E', 'M', 'p')
172 #define VALID_MEMPOOL(c)        ISC_MAGIC_VALID(c, MEMPOOL_MAGIC)
173
174 struct isc__mempool {
175         /* always unlocked */
176         isc_mempool_t   common;         /*%< common header of mempool's */
177         isc_mutex_t    *lock;           /*%< optional lock */
178         isc__mem_t      *mctx;          /*%< our memory context */
179         /*%< locked via the memory context's lock */
180         ISC_LINK(isc__mempool_t)        link;   /*%< next pool in this mem context */
181         /*%< optionally locked from here down */
182         element        *items;          /*%< low water item list */
183         size_t          size;           /*%< size of each item on this pool */
184         unsigned int    maxalloc;       /*%< max number of items allowed */
185         unsigned int    allocated;      /*%< # of items currently given out */
186         unsigned int    freecount;      /*%< # of items on reserved list */
187         unsigned int    freemax;        /*%< # of items allowed on free list */
188         unsigned int    fillcount;      /*%< # of items to fetch on each fill */
189         /*%< Stats only. */
190         unsigned int    gets;           /*%< # of requests to this pool */
191         /*%< Debugging only. */
192 #if ISC_MEMPOOL_NAMES
193         char            name[16];       /*%< printed name in stats reports */
194 #endif
195 };
196
197 /*
198  * Private Inline-able.
199  */
200
201 #if ! ISC_MEM_TRACKLINES
202 #define ADD_TRACE(a, b, c, d, e)
203 #define DELETE_TRACE(a, b, c, d, e)
204 #else
205 #define ADD_TRACE(a, b, c, d, e) \
206         do { \
207                 if ((isc_mem_debugging & (ISC_MEM_DEBUGTRACE | \
208                                           ISC_MEM_DEBUGRECORD)) != 0 && \
209                      b != NULL) \
210                          add_trace_entry(a, b, c, d, e); \
211         } while (0)
212 #define DELETE_TRACE(a, b, c, d, e)     delete_trace_entry(a, b, c, d, e)
213
214 static void
215 print_active(isc__mem_t *ctx, FILE *out);
216
217 /*%
218  * The following can be either static or public, depending on build environment.
219  */
220
221 #ifdef BIND9
222 #define ISC_MEMFUNC_SCOPE
223 #else
224 #define ISC_MEMFUNC_SCOPE static
225 #endif
226
227 ISC_MEMFUNC_SCOPE isc_result_t
228 isc__mem_createx(size_t init_max_size, size_t target_size,
229                  isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg,
230                  isc_mem_t **ctxp);
231 ISC_MEMFUNC_SCOPE isc_result_t
232 isc__mem_createx2(size_t init_max_size, size_t target_size,
233                   isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg,
234                   isc_mem_t **ctxp, unsigned int flags);
235 ISC_MEMFUNC_SCOPE isc_result_t
236 isc__mem_create(size_t init_max_size, size_t target_size, isc_mem_t **ctxp);
237 ISC_MEMFUNC_SCOPE isc_result_t
238 isc__mem_create2(size_t init_max_size, size_t target_size,
239                  isc_mem_t **ctxp, unsigned int flags);
240 ISC_MEMFUNC_SCOPE void
241 isc__mem_attach(isc_mem_t *source, isc_mem_t **targetp);
242 ISC_MEMFUNC_SCOPE void
243 isc__mem_detach(isc_mem_t **ctxp);
244 ISC_MEMFUNC_SCOPE void
245 isc___mem_putanddetach(isc_mem_t **ctxp, void *ptr, size_t size FLARG);
246 ISC_MEMFUNC_SCOPE void
247 isc__mem_destroy(isc_mem_t **ctxp);
248 ISC_MEMFUNC_SCOPE isc_result_t
249 isc__mem_ondestroy(isc_mem_t *ctx, isc_task_t *task, isc_event_t **event);
250 ISC_MEMFUNC_SCOPE void *
251 isc___mem_get(isc_mem_t *ctx, size_t size FLARG);
252 ISC_MEMFUNC_SCOPE void
253 isc___mem_put(isc_mem_t *ctx, void *ptr, size_t size FLARG);
254 ISC_MEMFUNC_SCOPE void
255 isc__mem_stats(isc_mem_t *ctx, FILE *out);
256 ISC_MEMFUNC_SCOPE void *
257 isc___mem_allocate(isc_mem_t *ctx, size_t size FLARG);
258 ISC_MEMFUNC_SCOPE void *
259 isc___mem_reallocate(isc_mem_t *ctx, void *ptr, size_t size FLARG);
260 ISC_MEMFUNC_SCOPE void
261 isc___mem_free(isc_mem_t *ctx, void *ptr FLARG);
262 ISC_MEMFUNC_SCOPE char *
263 isc___mem_strdup(isc_mem_t *mctx, const char *s FLARG);
264 ISC_MEMFUNC_SCOPE void
265 isc__mem_setdestroycheck(isc_mem_t *ctx, isc_boolean_t flag);
266 ISC_MEMFUNC_SCOPE void
267 isc__mem_setquota(isc_mem_t *ctx, size_t quota);
268 ISC_MEMFUNC_SCOPE size_t
269 isc__mem_getquota(isc_mem_t *ctx);
270 ISC_MEMFUNC_SCOPE size_t
271 isc__mem_inuse(isc_mem_t *ctx);
272 ISC_MEMFUNC_SCOPE void
273 isc__mem_setwater(isc_mem_t *ctx, isc_mem_water_t water, void *water_arg,
274                   size_t hiwater, size_t lowater);
275 ISC_MEMFUNC_SCOPE void
276 isc__mem_waterack(isc_mem_t *ctx0, int flag);
277 ISC_MEMFUNC_SCOPE void
278 isc__mem_setname(isc_mem_t *ctx, const char *name, void *tag);
279 ISC_MEMFUNC_SCOPE const char *
280 isc__mem_getname(isc_mem_t *ctx);
281 ISC_MEMFUNC_SCOPE void *
282 isc__mem_gettag(isc_mem_t *ctx);
283 ISC_MEMFUNC_SCOPE isc_result_t
284 isc__mempool_create(isc_mem_t *mctx, size_t size, isc_mempool_t **mpctxp);
285 ISC_MEMFUNC_SCOPE void
286 isc__mempool_setname(isc_mempool_t *mpctx, const char *name);
287 ISC_MEMFUNC_SCOPE void
288 isc__mempool_destroy(isc_mempool_t **mpctxp);
289 ISC_MEMFUNC_SCOPE void
290 isc__mempool_associatelock(isc_mempool_t *mpctx, isc_mutex_t *lock);
291 ISC_MEMFUNC_SCOPE void *
292 isc___mempool_get(isc_mempool_t *mpctx FLARG);
293 ISC_MEMFUNC_SCOPE void
294 isc___mempool_put(isc_mempool_t *mpctx, void *mem FLARG);
295 ISC_MEMFUNC_SCOPE void
296 isc__mempool_setfreemax(isc_mempool_t *mpctx, unsigned int limit);
297 ISC_MEMFUNC_SCOPE unsigned int
298 isc__mempool_getfreemax(isc_mempool_t *mpctx);
299 ISC_MEMFUNC_SCOPE unsigned int
300 isc__mempool_getfreecount(isc_mempool_t *mpctx);
301 ISC_MEMFUNC_SCOPE void
302 isc__mempool_setmaxalloc(isc_mempool_t *mpctx, unsigned int limit);
303 ISC_MEMFUNC_SCOPE unsigned int
304 isc__mempool_getmaxalloc(isc_mempool_t *mpctx);
305 ISC_MEMFUNC_SCOPE unsigned int
306 isc__mempool_getallocated(isc_mempool_t *mpctx);
307 ISC_MEMFUNC_SCOPE void
308 isc__mempool_setfillcount(isc_mempool_t *mpctx, unsigned int limit);
309 ISC_MEMFUNC_SCOPE unsigned int
310 isc__mempool_getfillcount(isc_mempool_t *mpctx);
311 #ifdef BIND9
312 ISC_MEMFUNC_SCOPE void
313 isc__mem_printactive(isc_mem_t *ctx0, FILE *file);
314 ISC_MEMFUNC_SCOPE void
315 isc__mem_printallactive(FILE *file);
316 ISC_MEMFUNC_SCOPE void
317 isc__mem_checkdestroyed(FILE *file);
318 ISC_MEMFUNC_SCOPE unsigned int
319 isc__mem_references(isc_mem_t *ctx0);
320 #endif
321
322 static struct isc__memmethods {
323         isc_memmethods_t methods;
324
325         /*%
326          * The following are defined just for avoiding unused static functions.
327          */
328 #ifndef BIND9
329         void *createx, *create, *create2, *ondestroy, *stats,
330                 *setquota, *getquota, *setname, *getname, *gettag;
331 #endif
332 } memmethods = {
333         {
334                 isc__mem_attach,
335                 isc__mem_detach,
336                 isc__mem_destroy,
337                 isc___mem_get,
338                 isc___mem_put,
339                 isc___mem_putanddetach,
340                 isc___mem_allocate,
341                 isc___mem_reallocate,
342                 isc___mem_strdup,
343                 isc___mem_free,
344                 isc__mem_setdestroycheck,
345                 isc__mem_setwater,
346                 isc__mem_waterack,
347                 isc__mem_inuse,
348                 isc__mempool_create
349         }
350 #ifndef BIND9
351         ,
352         (void *)isc__mem_createx, (void *)isc__mem_create,
353         (void *)isc__mem_create2, (void *)isc__mem_ondestroy,
354         (void *)isc__mem_stats, (void *)isc__mem_setquota,
355         (void *)isc__mem_getquota, (void *)isc__mem_setname,
356         (void *)isc__mem_getname, (void *)isc__mem_gettag
357 #endif
358 };
359
360 static struct isc__mempoolmethods {
361         isc_mempoolmethods_t methods;
362
363         /*%
364          * The following are defined just for avoiding unused static functions.
365          */
366 #ifndef BIND9
367         void *getfreemax, *getfreecount, *getmaxalloc, *getfillcount;
368 #endif
369 } mempoolmethods = {
370         {
371                 isc__mempool_destroy,
372                 isc___mempool_get,
373                 isc___mempool_put,
374                 isc__mempool_getallocated,
375                 isc__mempool_setmaxalloc,
376                 isc__mempool_setfreemax,
377                 isc__mempool_setname,
378                 isc__mempool_associatelock,
379                 isc__mempool_setfillcount
380         }
381 #ifndef BIND9
382         ,
383         (void *)isc__mempool_getfreemax, (void *)isc__mempool_getfreecount,
384         (void *)isc__mempool_getmaxalloc, (void *)isc__mempool_getfillcount
385 #endif
386 };
387
388 /*!
389  * mctx must be locked.
390  */
391 static inline void
392 add_trace_entry(isc__mem_t *mctx, const void *ptr, unsigned int size
393                 FLARG)
394 {
395         debuglink_t *dl;
396         unsigned int i;
397         unsigned int mysize = size;
398
399         if ((isc_mem_debugging & ISC_MEM_DEBUGTRACE) != 0)
400                 fprintf(stderr, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
401                                                ISC_MSG_ADDTRACE,
402                                                "add %p size %u "
403                                                "file %s line %u mctx %p\n"),
404                         ptr, size, file, line, mctx);
405
406         if (mctx->debuglist == NULL)
407                 return;
408
409         if (mysize > mctx->max_size)
410                 mysize = mctx->max_size;
411
412         dl = ISC_LIST_HEAD(mctx->debuglist[mysize]);
413         while (dl != NULL) {
414                 if (dl->count == DEBUGLIST_COUNT)
415                         goto next;
416                 for (i = 0; i < DEBUGLIST_COUNT; i++) {
417                         if (dl->ptr[i] == NULL) {
418                                 dl->ptr[i] = ptr;
419                                 dl->size[i] = size;
420                                 dl->file[i] = file;
421                                 dl->line[i] = line;
422                                 dl->count++;
423                                 return;
424                         }
425                 }
426         next:
427                 dl = ISC_LIST_NEXT(dl, link);
428         }
429
430         dl = malloc(sizeof(debuglink_t));
431         INSIST(dl != NULL);
432
433         ISC_LINK_INIT(dl, link);
434         for (i = 1; i < DEBUGLIST_COUNT; i++) {
435                 dl->ptr[i] = NULL;
436                 dl->size[i] = 0;
437                 dl->file[i] = NULL;
438                 dl->line[i] = 0;
439         }
440
441         dl->ptr[0] = ptr;
442         dl->size[0] = size;
443         dl->file[0] = file;
444         dl->line[0] = line;
445         dl->count = 1;
446
447         ISC_LIST_PREPEND(mctx->debuglist[mysize], dl, link);
448         mctx->debuglistcnt++;
449 }
450
451 static inline void
452 delete_trace_entry(isc__mem_t *mctx, const void *ptr, unsigned int size,
453                    const char *file, unsigned int line)
454 {
455         debuglink_t *dl;
456         unsigned int i;
457
458         if ((isc_mem_debugging & ISC_MEM_DEBUGTRACE) != 0)
459                 fprintf(stderr, isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
460                                                ISC_MSG_DELTRACE,
461                                                "del %p size %u "
462                                                "file %s line %u mctx %p\n"),
463                         ptr, size, file, line, mctx);
464
465         if (mctx->debuglist == NULL)
466                 return;
467
468         if (size > mctx->max_size)
469                 size = mctx->max_size;
470
471         dl = ISC_LIST_HEAD(mctx->debuglist[size]);
472         while (dl != NULL) {
473                 for (i = 0; i < DEBUGLIST_COUNT; i++) {
474                         if (dl->ptr[i] == ptr) {
475                                 dl->ptr[i] = NULL;
476                                 dl->size[i] = 0;
477                                 dl->file[i] = NULL;
478                                 dl->line[i] = 0;
479
480                                 INSIST(dl->count > 0);
481                                 dl->count--;
482                                 if (dl->count == 0) {
483                                         ISC_LIST_UNLINK(mctx->debuglist[size],
484                                                         dl, link);
485                                         free(dl);
486                                 }
487                                 return;
488                         }
489                 }
490                 dl = ISC_LIST_NEXT(dl, link);
491         }
492
493         /*
494          * If we get here, we didn't find the item on the list.  We're
495          * screwed.
496          */
497         INSIST(dl != NULL);
498 }
499 #endif /* ISC_MEM_TRACKLINES */
500
501 static inline size_t
502 rmsize(size_t size) {
503         /*
504          * round down to ALIGNMENT_SIZE
505          */
506         return (size & (~(ALIGNMENT_SIZE - 1)));
507 }
508
509 static inline size_t
510 quantize(size_t size) {
511         /*!
512          * Round up the result in order to get a size big
513          * enough to satisfy the request and be aligned on ALIGNMENT_SIZE
514          * byte boundaries.
515          */
516
517         if (size == 0U)
518                 return (ALIGNMENT_SIZE);
519         return ((size + ALIGNMENT_SIZE - 1) & (~(ALIGNMENT_SIZE - 1)));
520 }
521
522 static inline isc_boolean_t
523 more_basic_blocks(isc__mem_t *ctx) {
524         void *new;
525         unsigned char *curr, *next;
526         unsigned char *first, *last;
527         unsigned char **table;
528         unsigned int table_size;
529         size_t increment;
530         int i;
531
532         /* Require: we hold the context lock. */
533
534         /*
535          * Did we hit the quota for this context?
536          */
537         increment = NUM_BASIC_BLOCKS * ctx->mem_target;
538         if (ctx->quota != 0U && ctx->total + increment > ctx->quota)
539                 return (ISC_FALSE);
540
541         INSIST(ctx->basic_table_count <= ctx->basic_table_size);
542         if (ctx->basic_table_count == ctx->basic_table_size) {
543                 table_size = ctx->basic_table_size + TABLE_INCREMENT;
544                 table = (ctx->memalloc)(ctx->arg,
545                                         table_size * sizeof(unsigned char *));
546                 if (table == NULL) {
547                         ctx->memalloc_failures++;
548                         return (ISC_FALSE);
549                 }
550                 if (ctx->basic_table_size != 0) {
551                         memcpy(table, ctx->basic_table,
552                                ctx->basic_table_size *
553                                sizeof(unsigned char *));
554                         (ctx->memfree)(ctx->arg, ctx->basic_table);
555                 }
556                 ctx->basic_table = table;
557                 ctx->basic_table_size = table_size;
558         }
559
560         new = (ctx->memalloc)(ctx->arg, NUM_BASIC_BLOCKS * ctx->mem_target);
561         if (new == NULL) {
562                 ctx->memalloc_failures++;
563                 return (ISC_FALSE);
564         }
565         ctx->total += increment;
566         ctx->basic_table[ctx->basic_table_count] = new;
567         ctx->basic_table_count++;
568
569         curr = new;
570         next = curr + ctx->mem_target;
571         for (i = 0; i < (NUM_BASIC_BLOCKS - 1); i++) {
572                 ((element *)curr)->next = (element *)next;
573                 curr = next;
574                 next += ctx->mem_target;
575         }
576         /*
577          * curr is now pointing at the last block in the
578          * array.
579          */
580         ((element *)curr)->next = NULL;
581         first = new;
582         last = first + NUM_BASIC_BLOCKS * ctx->mem_target - 1;
583         if (first < ctx->lowest || ctx->lowest == NULL)
584                 ctx->lowest = first;
585         if (last > ctx->highest)
586                 ctx->highest = last;
587         ctx->basic_blocks = new;
588
589         return (ISC_TRUE);
590 }
591
592 static inline isc_boolean_t
593 more_frags(isc__mem_t *ctx, size_t new_size) {
594         int i, frags;
595         size_t total_size;
596         void *new;
597         unsigned char *curr, *next;
598
599         /*!
600          * Try to get more fragments by chopping up a basic block.
601          */
602
603         if (ctx->basic_blocks == NULL) {
604                 if (!more_basic_blocks(ctx)) {
605                         /*
606                          * We can't get more memory from the OS, or we've
607                          * hit the quota for this context.
608                          */
609                         /*
610                          * XXXRTH  "At quota" notification here.
611                          */
612                         return (ISC_FALSE);
613                 }
614         }
615
616         total_size = ctx->mem_target;
617         new = ctx->basic_blocks;
618         ctx->basic_blocks = ctx->basic_blocks->next;
619         frags = total_size / new_size;
620         ctx->stats[new_size].blocks++;
621         ctx->stats[new_size].freefrags += frags;
622         /*
623          * Set up a linked-list of blocks of size
624          * "new_size".
625          */
626         curr = new;
627         next = curr + new_size;
628         total_size -= new_size;
629         for (i = 0; i < (frags - 1); i++) {
630                 ((element *)curr)->next = (element *)next;
631                 curr = next;
632                 next += new_size;
633                 total_size -= new_size;
634         }
635         /*
636          * Add the remaining fragment of the basic block to a free list.
637          */
638         total_size = rmsize(total_size);
639         if (total_size > 0U) {
640                 ((element *)next)->next = ctx->freelists[total_size];
641                 ctx->freelists[total_size] = (element *)next;
642                 ctx->stats[total_size].freefrags++;
643         }
644         /*
645          * curr is now pointing at the last block in the
646          * array.
647          */
648         ((element *)curr)->next = NULL;
649         ctx->freelists[new_size] = new;
650
651         return (ISC_TRUE);
652 }
653
654 static inline void *
655 mem_getunlocked(isc__mem_t *ctx, size_t size) {
656         size_t new_size = quantize(size);
657         void *ret;
658
659         if (size >= ctx->max_size || new_size >= ctx->max_size) {
660                 /*
661                  * memget() was called on something beyond our upper limit.
662                  */
663                 if (ctx->quota != 0U && ctx->total + size > ctx->quota) {
664                         ret = NULL;
665                         goto done;
666                 }
667                 ret = (ctx->memalloc)(ctx->arg, size);
668                 if (ret == NULL) {
669                         ctx->memalloc_failures++;
670                         goto done;
671                 }
672                 ctx->total += size;
673                 ctx->inuse += size;
674                 ctx->stats[ctx->max_size].gets++;
675                 ctx->stats[ctx->max_size].totalgets++;
676                 /*
677                  * If we don't set new_size to size, then the
678                  * ISC_MEM_FILL code might write over bytes we
679                  * don't own.
680                  */
681                 new_size = size;
682                 goto done;
683         }
684
685         /*
686          * If there are no blocks in the free list for this size, get a chunk
687          * of memory and then break it up into "new_size"-sized blocks, adding
688          * them to the free list.
689          */
690         if (ctx->freelists[new_size] == NULL && !more_frags(ctx, new_size))
691                 return (NULL);
692
693         /*
694          * The free list uses the "rounded-up" size "new_size".
695          */
696         ret = ctx->freelists[new_size];
697         ctx->freelists[new_size] = ctx->freelists[new_size]->next;
698
699         /*
700          * The stats[] uses the _actual_ "size" requested by the
701          * caller, with the caveat (in the code above) that "size" >= the
702          * max. size (max_size) ends up getting recorded as a call to
703          * max_size.
704          */
705         ctx->stats[size].gets++;
706         ctx->stats[size].totalgets++;
707         ctx->stats[new_size].freefrags--;
708         ctx->inuse += new_size;
709
710  done:
711
712 #if ISC_MEM_FILL
713         if (ret != NULL)
714                 memset(ret, 0xbe, new_size); /* Mnemonic for "beef". */
715 #endif
716
717         return (ret);
718 }
719
720 #if ISC_MEM_FILL && ISC_MEM_CHECKOVERRUN
721 static inline void
722 check_overrun(void *mem, size_t size, size_t new_size) {
723         unsigned char *cp;
724
725         cp = (unsigned char *)mem;
726         cp += size;
727         while (size < new_size) {
728                 INSIST(*cp == 0xbe);
729                 cp++;
730                 size++;
731         }
732 }
733 #endif
734
735 static inline void
736 mem_putunlocked(isc__mem_t *ctx, void *mem, size_t size) {
737         size_t new_size = quantize(size);
738
739         if (size == ctx->max_size || new_size >= ctx->max_size) {
740                 /*
741                  * memput() called on something beyond our upper limit.
742                  */
743 #if ISC_MEM_FILL
744                 memset(mem, 0xde, size); /* Mnemonic for "dead". */
745 #endif
746                 (ctx->memfree)(ctx->arg, mem);
747                 INSIST(ctx->stats[ctx->max_size].gets != 0U);
748                 ctx->stats[ctx->max_size].gets--;
749                 INSIST(size <= ctx->total);
750                 ctx->inuse -= size;
751                 ctx->total -= size;
752                 return;
753         }
754
755 #if ISC_MEM_FILL
756 #if ISC_MEM_CHECKOVERRUN
757         check_overrun(mem, size, new_size);
758 #endif
759         memset(mem, 0xde, new_size); /* Mnemonic for "dead". */
760 #endif
761
762         /*
763          * The free list uses the "rounded-up" size "new_size".
764          */
765         ((element *)mem)->next = ctx->freelists[new_size];
766         ctx->freelists[new_size] = (element *)mem;
767
768         /*
769          * The stats[] uses the _actual_ "size" requested by the
770          * caller, with the caveat (in the code above) that "size" >= the
771          * max. size (max_size) ends up getting recorded as a call to
772          * max_size.
773          */
774         INSIST(ctx->stats[size].gets != 0U);
775         ctx->stats[size].gets--;
776         ctx->stats[new_size].freefrags++;
777         ctx->inuse -= new_size;
778 }
779
780 /*!
781  * Perform a malloc, doing memory filling and overrun detection as necessary.
782  */
783 static inline void *
784 mem_get(isc__mem_t *ctx, size_t size) {
785         char *ret;
786
787 #if ISC_MEM_CHECKOVERRUN
788         size += 1;
789 #endif
790
791         ret = (ctx->memalloc)(ctx->arg, size);
792         if (ret == NULL)
793                 ctx->memalloc_failures++;
794
795 #if ISC_MEM_FILL
796         if (ret != NULL)
797                 memset(ret, 0xbe, size); /* Mnemonic for "beef". */
798 #else
799 #  if ISC_MEM_CHECKOVERRUN
800         if (ret != NULL)
801                 ret[size-1] = 0xbe;
802 #  endif
803 #endif
804
805         return (ret);
806 }
807
808 /*!
809  * Perform a free, doing memory filling and overrun detection as necessary.
810  */
811 static inline void
812 mem_put(isc__mem_t *ctx, void *mem, size_t size) {
813 #if ISC_MEM_CHECKOVERRUN
814         INSIST(((unsigned char *)mem)[size] == 0xbe);
815 #endif
816 #if ISC_MEM_FILL
817         memset(mem, 0xde, size); /* Mnemonic for "dead". */
818 #else
819         UNUSED(size);
820 #endif
821         (ctx->memfree)(ctx->arg, mem);
822 }
823
824 /*!
825  * Update internal counters after a memory get.
826  */
827 static inline void
828 mem_getstats(isc__mem_t *ctx, size_t size) {
829         ctx->total += size;
830         ctx->inuse += size;
831
832         if (size > ctx->max_size) {
833                 ctx->stats[ctx->max_size].gets++;
834                 ctx->stats[ctx->max_size].totalgets++;
835         } else {
836                 ctx->stats[size].gets++;
837                 ctx->stats[size].totalgets++;
838         }
839 }
840
841 /*!
842  * Update internal counters after a memory put.
843  */
844 static inline void
845 mem_putstats(isc__mem_t *ctx, void *ptr, size_t size) {
846         UNUSED(ptr);
847
848         INSIST(ctx->inuse >= size);
849         ctx->inuse -= size;
850
851         if (size > ctx->max_size) {
852                 INSIST(ctx->stats[ctx->max_size].gets > 0U);
853                 ctx->stats[ctx->max_size].gets--;
854         } else {
855                 INSIST(ctx->stats[size].gets > 0U);
856                 ctx->stats[size].gets--;
857         }
858 }
859
860 /*
861  * Private.
862  */
863
864 static void *
865 default_memalloc(void *arg, size_t size) {
866         UNUSED(arg);
867         if (size == 0U)
868                 size = 1;
869         return (malloc(size));
870 }
871
872 static void
873 default_memfree(void *arg, void *ptr) {
874         UNUSED(arg);
875         free(ptr);
876 }
877
878 static void
879 initialize_action(void) {
880         RUNTIME_CHECK(isc_mutex_init(&lock) == ISC_R_SUCCESS);
881         ISC_LIST_INIT(contexts);
882         totallost = 0;
883 }
884
885 /*
886  * Public.
887  */
888
889 ISC_MEMFUNC_SCOPE isc_result_t
890 isc__mem_createx(size_t init_max_size, size_t target_size,
891                  isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg,
892                  isc_mem_t **ctxp)
893 {
894         return (isc__mem_createx2(init_max_size, target_size, memalloc, memfree,
895                                   arg, ctxp, ISC_MEMFLAG_DEFAULT));
896
897 }
898
899 ISC_MEMFUNC_SCOPE isc_result_t
900 isc__mem_createx2(size_t init_max_size, size_t target_size,
901                   isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg,
902                   isc_mem_t **ctxp, unsigned int flags)
903 {
904         isc__mem_t *ctx;
905         isc_result_t result;
906
907         REQUIRE(ctxp != NULL && *ctxp == NULL);
908         REQUIRE(memalloc != NULL);
909         REQUIRE(memfree != NULL);
910
911         INSIST((ALIGNMENT_SIZE & (ALIGNMENT_SIZE - 1)) == 0);
912
913         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
914
915         ctx = (memalloc)(arg, sizeof(*ctx));
916         if (ctx == NULL)
917                 return (ISC_R_NOMEMORY);
918
919         if ((flags & ISC_MEMFLAG_NOLOCK) == 0) {
920                 result = isc_mutex_init(&ctx->lock);
921                 if (result != ISC_R_SUCCESS) {
922                         (memfree)(arg, ctx);
923                         return (result);
924                 }
925         }
926
927         if (init_max_size == 0U)
928                 ctx->max_size = DEF_MAX_SIZE;
929         else
930                 ctx->max_size = init_max_size;
931         ctx->flags = flags;
932         ctx->references = 1;
933         memset(ctx->name, 0, sizeof(ctx->name));
934         ctx->tag = NULL;
935         ctx->quota = 0;
936         ctx->total = 0;
937         ctx->inuse = 0;
938         ctx->maxinuse = 0;
939         ctx->hi_water = 0;
940         ctx->lo_water = 0;
941         ctx->hi_called = ISC_FALSE;
942         ctx->water = NULL;
943         ctx->water_arg = NULL;
944         ctx->common.impmagic = MEM_MAGIC;
945         ctx->common.magic = ISCAPI_MCTX_MAGIC;
946         ctx->common.methods = (isc_memmethods_t *)&memmethods;
947         isc_ondestroy_init(&ctx->ondestroy);
948         ctx->memalloc = memalloc;
949         ctx->memfree = memfree;
950         ctx->arg = arg;
951         ctx->stats = NULL;
952         ctx->checkfree = ISC_TRUE;
953 #if ISC_MEM_TRACKLINES
954         ctx->debuglist = NULL;
955         ctx->debuglistcnt = 0;
956 #endif
957         ISC_LIST_INIT(ctx->pools);
958         ctx->poolcnt = 0;
959         ctx->freelists = NULL;
960         ctx->basic_blocks = NULL;
961         ctx->basic_table = NULL;
962         ctx->basic_table_count = 0;
963         ctx->basic_table_size = 0;
964         ctx->lowest = NULL;
965         ctx->highest = NULL;
966
967         ctx->stats = (memalloc)(arg,
968                                 (ctx->max_size+1) * sizeof(struct stats));
969         if (ctx->stats == NULL) {
970                 result = ISC_R_NOMEMORY;
971                 goto error;
972         }
973         memset(ctx->stats, 0, (ctx->max_size + 1) * sizeof(struct stats));
974
975         if ((flags & ISC_MEMFLAG_INTERNAL) != 0) {
976                 if (target_size == 0U)
977                         ctx->mem_target = DEF_MEM_TARGET;
978                 else
979                         ctx->mem_target = target_size;
980                 ctx->freelists = (memalloc)(arg, ctx->max_size *
981                                                  sizeof(element *));
982                 if (ctx->freelists == NULL) {
983                         result = ISC_R_NOMEMORY;
984                         goto error;
985                 }
986                 memset(ctx->freelists, 0,
987                        ctx->max_size * sizeof(element *));
988         }
989
990 #if ISC_MEM_TRACKLINES
991         if ((isc_mem_debugging & ISC_MEM_DEBUGRECORD) != 0) {
992                 unsigned int i;
993
994                 ctx->debuglist = (memalloc)(arg,
995                                       (ctx->max_size+1) * sizeof(debuglist_t));
996                 if (ctx->debuglist == NULL) {
997                         result = ISC_R_NOMEMORY;
998                         goto error;
999                 }
1000                 for (i = 0; i <= ctx->max_size; i++)
1001                         ISC_LIST_INIT(ctx->debuglist[i]);
1002         }
1003 #endif
1004
1005         ctx->memalloc_failures = 0;
1006
1007         LOCK(&lock);
1008         ISC_LIST_INITANDAPPEND(contexts, ctx, link);
1009         UNLOCK(&lock);
1010
1011         *ctxp = (isc_mem_t *)ctx;
1012         return (ISC_R_SUCCESS);
1013
1014   error:
1015         if (ctx != NULL) {
1016                 if (ctx->stats != NULL)
1017                         (memfree)(arg, ctx->stats);
1018                 if (ctx->freelists != NULL)
1019                         (memfree)(arg, ctx->freelists);
1020 #if ISC_MEM_TRACKLINES
1021                 if (ctx->debuglist != NULL)
1022                         (ctx->memfree)(ctx->arg, ctx->debuglist);
1023 #endif /* ISC_MEM_TRACKLINES */
1024                 if ((ctx->flags & ISC_MEMFLAG_NOLOCK) == 0)
1025                         DESTROYLOCK(&ctx->lock);
1026                 (memfree)(arg, ctx);
1027         }
1028
1029         return (result);
1030 }
1031
1032 ISC_MEMFUNC_SCOPE isc_result_t
1033 isc__mem_create(size_t init_max_size, size_t target_size, isc_mem_t **ctxp) {
1034         return (isc__mem_createx2(init_max_size, target_size,
1035                                   default_memalloc, default_memfree, NULL,
1036                                   ctxp, ISC_MEMFLAG_DEFAULT));
1037 }
1038
1039 ISC_MEMFUNC_SCOPE isc_result_t
1040 isc__mem_create2(size_t init_max_size, size_t target_size,
1041                  isc_mem_t **ctxp, unsigned int flags)
1042 {
1043         return (isc__mem_createx2(init_max_size, target_size,
1044                                   default_memalloc, default_memfree, NULL,
1045                                   ctxp, flags));
1046 }
1047
1048 static void
1049 destroy(isc__mem_t *ctx) {
1050         unsigned int i;
1051         isc_ondestroy_t ondest;
1052
1053         LOCK(&lock);
1054         ISC_LIST_UNLINK(contexts, ctx, link);
1055         totallost += ctx->inuse;
1056         UNLOCK(&lock);
1057
1058         ctx->common.impmagic = 0;
1059         ctx->common.magic = 0;
1060
1061         INSIST(ISC_LIST_EMPTY(ctx->pools));
1062
1063 #if ISC_MEM_TRACKLINES
1064         if (ctx->debuglist != NULL) {
1065                 if (ctx->checkfree) {
1066                         for (i = 0; i <= ctx->max_size; i++) {
1067                                 if (!ISC_LIST_EMPTY(ctx->debuglist[i]))
1068                                         print_active(ctx, stderr);
1069                                 INSIST(ISC_LIST_EMPTY(ctx->debuglist[i]));
1070                         }
1071                 } else {
1072                         debuglink_t *dl;
1073
1074                         for (i = 0; i <= ctx->max_size; i++)
1075                                 for (dl = ISC_LIST_HEAD(ctx->debuglist[i]);
1076                                      dl != NULL;
1077                                      dl = ISC_LIST_HEAD(ctx->debuglist[i])) {
1078                                         ISC_LIST_UNLINK(ctx->debuglist[i],
1079                                                         dl, link);
1080                                         free(dl);
1081                                 }
1082                 }
1083                 (ctx->memfree)(ctx->arg, ctx->debuglist);
1084         }
1085 #endif
1086         INSIST(ctx->references == 0);
1087
1088         if (ctx->checkfree) {
1089                 for (i = 0; i <= ctx->max_size; i++) {
1090 #if ISC_MEM_TRACKLINES
1091                         if (ctx->stats[i].gets != 0U)
1092                                 print_active(ctx, stderr);
1093 #endif
1094                         INSIST(ctx->stats[i].gets == 0U);
1095                 }
1096         }
1097
1098         (ctx->memfree)(ctx->arg, ctx->stats);
1099
1100         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1101                 for (i = 0; i < ctx->basic_table_count; i++)
1102                         (ctx->memfree)(ctx->arg, ctx->basic_table[i]);
1103                 (ctx->memfree)(ctx->arg, ctx->freelists);
1104                 if (ctx->basic_table != NULL)
1105                         (ctx->memfree)(ctx->arg, ctx->basic_table);
1106         }
1107
1108         ondest = ctx->ondestroy;
1109
1110         if ((ctx->flags & ISC_MEMFLAG_NOLOCK) == 0)
1111                 DESTROYLOCK(&ctx->lock);
1112         (ctx->memfree)(ctx->arg, ctx);
1113
1114         isc_ondestroy_notify(&ondest, ctx);
1115 }
1116
1117 ISC_MEMFUNC_SCOPE void
1118 isc__mem_attach(isc_mem_t *source0, isc_mem_t **targetp) {
1119         isc__mem_t *source = (isc__mem_t *)source0;
1120
1121         REQUIRE(VALID_CONTEXT(source));
1122         REQUIRE(targetp != NULL && *targetp == NULL);
1123
1124         MCTXLOCK(source, &source->lock);
1125         source->references++;
1126         MCTXUNLOCK(source, &source->lock);
1127
1128         *targetp = (isc_mem_t *)source;
1129 }
1130
1131 ISC_MEMFUNC_SCOPE void
1132 isc__mem_detach(isc_mem_t **ctxp) {
1133         isc__mem_t *ctx;
1134         isc_boolean_t want_destroy = ISC_FALSE;
1135
1136         REQUIRE(ctxp != NULL);
1137         ctx = (isc__mem_t *)*ctxp;
1138         REQUIRE(VALID_CONTEXT(ctx));
1139
1140         MCTXLOCK(ctx, &ctx->lock);
1141         INSIST(ctx->references > 0);
1142         ctx->references--;
1143         if (ctx->references == 0)
1144                 want_destroy = ISC_TRUE;
1145         MCTXUNLOCK(ctx, &ctx->lock);
1146
1147         if (want_destroy)
1148                 destroy(ctx);
1149
1150         *ctxp = NULL;
1151 }
1152
1153 /*
1154  * isc_mem_putanddetach() is the equivalent of:
1155  *
1156  * mctx = NULL;
1157  * isc_mem_attach(ptr->mctx, &mctx);
1158  * isc_mem_detach(&ptr->mctx);
1159  * isc_mem_put(mctx, ptr, sizeof(*ptr);
1160  * isc_mem_detach(&mctx);
1161  */
1162
1163 ISC_MEMFUNC_SCOPE void
1164 isc___mem_putanddetach(isc_mem_t **ctxp, void *ptr, size_t size FLARG) {
1165         isc__mem_t *ctx;
1166         isc_boolean_t want_destroy = ISC_FALSE;
1167         size_info *si;
1168         size_t oldsize;
1169
1170         REQUIRE(ctxp != NULL);
1171         ctx = (isc__mem_t *)*ctxp;
1172         REQUIRE(VALID_CONTEXT(ctx));
1173         REQUIRE(ptr != NULL);
1174
1175         /*
1176          * Must be before mem_putunlocked() as ctxp is usually within
1177          * [ptr..ptr+size).
1178          */
1179         *ctxp = NULL;
1180
1181         if ((isc_mem_debugging & (ISC_MEM_DEBUGSIZE|ISC_MEM_DEBUGCTX)) != 0) {
1182                 if ((isc_mem_debugging & ISC_MEM_DEBUGSIZE) != 0) {
1183                         si = &(((size_info *)ptr)[-1]);
1184                         oldsize = si->u.size - ALIGNMENT_SIZE;
1185                         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)
1186                                 oldsize -= ALIGNMENT_SIZE;
1187                         INSIST(oldsize == size);
1188                 }
1189                 isc_mem_free((isc_mem_t *)ctx, ptr);
1190
1191                 MCTXLOCK(ctx, &ctx->lock);
1192                 ctx->references--;
1193                 if (ctx->references == 0)
1194                         want_destroy = ISC_TRUE;
1195                 MCTXUNLOCK(ctx, &ctx->lock);
1196                 if (want_destroy)
1197                         destroy(ctx);
1198
1199                 return;
1200         }
1201
1202         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1203                 MCTXLOCK(ctx, &ctx->lock);
1204                 mem_putunlocked(ctx, ptr, size);
1205         } else {
1206                 mem_put(ctx, ptr, size);
1207                 MCTXLOCK(ctx, &ctx->lock);
1208                 mem_putstats(ctx, ptr, size);
1209         }
1210
1211         DELETE_TRACE(ctx, ptr, size, file, line);
1212         INSIST(ctx->references > 0);
1213         ctx->references--;
1214         if (ctx->references == 0)
1215                 want_destroy = ISC_TRUE;
1216
1217         MCTXUNLOCK(ctx, &ctx->lock);
1218
1219         if (want_destroy)
1220                 destroy(ctx);
1221 }
1222
1223 ISC_MEMFUNC_SCOPE void
1224 isc__mem_destroy(isc_mem_t **ctxp) {
1225         isc__mem_t *ctx;
1226
1227         /*
1228          * This routine provides legacy support for callers who use mctxs
1229          * without attaching/detaching.
1230          */
1231
1232         REQUIRE(ctxp != NULL);
1233         ctx = (isc__mem_t *)*ctxp;
1234         REQUIRE(VALID_CONTEXT(ctx));
1235
1236         MCTXLOCK(ctx, &ctx->lock);
1237 #if ISC_MEM_TRACKLINES
1238         if (ctx->references != 1)
1239                 print_active(ctx, stderr);
1240 #endif
1241         REQUIRE(ctx->references == 1);
1242         ctx->references--;
1243         MCTXUNLOCK(ctx, &ctx->lock);
1244
1245         destroy(ctx);
1246
1247         *ctxp = NULL;
1248 }
1249
1250 ISC_MEMFUNC_SCOPE isc_result_t
1251 isc__mem_ondestroy(isc_mem_t *ctx0, isc_task_t *task, isc_event_t **event) {
1252         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1253         isc_result_t res;
1254
1255         MCTXLOCK(ctx, &ctx->lock);
1256         res = isc_ondestroy_register(&ctx->ondestroy, task, event);
1257         MCTXUNLOCK(ctx, &ctx->lock);
1258
1259         return (res);
1260 }
1261
1262 ISC_MEMFUNC_SCOPE void *
1263 isc___mem_get(isc_mem_t *ctx0, size_t size FLARG) {
1264         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1265         void *ptr;
1266         isc_boolean_t call_water = ISC_FALSE;
1267
1268         REQUIRE(VALID_CONTEXT(ctx));
1269
1270         if ((isc_mem_debugging & (ISC_MEM_DEBUGSIZE|ISC_MEM_DEBUGCTX)) != 0)
1271                 return (isc_mem_allocate((isc_mem_t *)ctx, size));
1272
1273         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1274                 MCTXLOCK(ctx, &ctx->lock);
1275                 ptr = mem_getunlocked(ctx, size);
1276         } else {
1277                 ptr = mem_get(ctx, size);
1278                 MCTXLOCK(ctx, &ctx->lock);
1279                 if (ptr != NULL)
1280                         mem_getstats(ctx, size);
1281         }
1282
1283         ADD_TRACE(ctx, ptr, size, file, line);
1284         if (ctx->hi_water != 0U && !ctx->hi_called &&
1285             ctx->inuse > ctx->hi_water) {
1286                 call_water = ISC_TRUE;
1287         }
1288         if (ctx->inuse > ctx->maxinuse) {
1289                 ctx->maxinuse = ctx->inuse;
1290                 if (ctx->hi_water != 0U && ctx->inuse > ctx->hi_water &&
1291                     (isc_mem_debugging & ISC_MEM_DEBUGUSAGE) != 0)
1292                         fprintf(stderr, "maxinuse = %lu\n",
1293                                 (unsigned long)ctx->inuse);
1294         }
1295         MCTXUNLOCK(ctx, &ctx->lock);
1296
1297         if (call_water)
1298                 (ctx->water)(ctx->water_arg, ISC_MEM_HIWATER);
1299
1300         return (ptr);
1301 }
1302
1303 ISC_MEMFUNC_SCOPE void
1304 isc___mem_put(isc_mem_t *ctx0, void *ptr, size_t size FLARG) {
1305         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1306         isc_boolean_t call_water = ISC_FALSE;
1307         size_info *si;
1308         size_t oldsize;
1309
1310         REQUIRE(VALID_CONTEXT(ctx));
1311         REQUIRE(ptr != NULL);
1312
1313         if ((isc_mem_debugging & (ISC_MEM_DEBUGSIZE|ISC_MEM_DEBUGCTX)) != 0) {
1314                 if ((isc_mem_debugging & ISC_MEM_DEBUGSIZE) != 0) {
1315                         si = &(((size_info *)ptr)[-1]);
1316                         oldsize = si->u.size - ALIGNMENT_SIZE;
1317                         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)
1318                                 oldsize -= ALIGNMENT_SIZE;
1319                         INSIST(oldsize == size);
1320                 }
1321                 isc_mem_free((isc_mem_t *)ctx, ptr);
1322                 return;
1323         }
1324
1325         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1326                 MCTXLOCK(ctx, &ctx->lock);
1327                 mem_putunlocked(ctx, ptr, size);
1328         } else {
1329                 mem_put(ctx, ptr, size);
1330                 MCTXLOCK(ctx, &ctx->lock);
1331                 mem_putstats(ctx, ptr, size);
1332         }
1333
1334         DELETE_TRACE(ctx, ptr, size, file, line);
1335
1336         /*
1337          * The check against ctx->lo_water == 0 is for the condition
1338          * when the context was pushed over hi_water but then had
1339          * isc_mem_setwater() called with 0 for hi_water and lo_water.
1340          */
1341         if (ctx->hi_called &&
1342             (ctx->inuse < ctx->lo_water || ctx->lo_water == 0U)) {
1343                 if (ctx->water != NULL)
1344                         call_water = ISC_TRUE;
1345         }
1346         MCTXUNLOCK(ctx, &ctx->lock);
1347
1348         if (call_water)
1349                 (ctx->water)(ctx->water_arg, ISC_MEM_LOWATER);
1350 }
1351
1352 ISC_MEMFUNC_SCOPE void
1353 isc__mem_waterack(isc_mem_t *ctx0, int flag) {
1354         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1355
1356         REQUIRE(VALID_CONTEXT(ctx));
1357
1358         MCTXLOCK(ctx, &ctx->lock);
1359         if (flag == ISC_MEM_LOWATER)
1360                 ctx->hi_called = ISC_FALSE;
1361         else if (flag == ISC_MEM_HIWATER)
1362                 ctx->hi_called = ISC_TRUE;
1363         MCTXUNLOCK(ctx, &ctx->lock);
1364 }
1365
1366 #if ISC_MEM_TRACKLINES
1367 static void
1368 print_active(isc__mem_t *mctx, FILE *out) {
1369         if (mctx->debuglist != NULL) {
1370                 debuglink_t *dl;
1371                 unsigned int i, j;
1372                 const char *format;
1373                 isc_boolean_t found;
1374
1375                 fprintf(out, "%s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1376                                             ISC_MSG_DUMPALLOC,
1377                                             "Dump of all outstanding "
1378                                             "memory allocations:\n"));
1379                 found = ISC_FALSE;
1380                 format = isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1381                                         ISC_MSG_PTRFILELINE,
1382                                         "\tptr %p size %u file %s line %u\n");
1383                 for (i = 0; i <= mctx->max_size; i++) {
1384                         dl = ISC_LIST_HEAD(mctx->debuglist[i]);
1385
1386                         if (dl != NULL)
1387                                 found = ISC_TRUE;
1388
1389                         while (dl != NULL) {
1390                                 for (j = 0; j < DEBUGLIST_COUNT; j++)
1391                                         if (dl->ptr[j] != NULL)
1392                                                 fprintf(out, format,
1393                                                         dl->ptr[j],
1394                                                         dl->size[j],
1395                                                         dl->file[j],
1396                                                         dl->line[j]);
1397                                 dl = ISC_LIST_NEXT(dl, link);
1398                         }
1399                 }
1400                 if (!found)
1401                         fprintf(out, "%s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1402                                                     ISC_MSG_NONE, "\tNone.\n"));
1403         }
1404 }
1405 #endif
1406
1407 /*
1408  * Print the stats[] on the stream "out" with suitable formatting.
1409  */
1410 ISC_MEMFUNC_SCOPE void
1411 isc__mem_stats(isc_mem_t *ctx0, FILE *out) {
1412         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1413         size_t i;
1414         const struct stats *s;
1415         const isc__mempool_t *pool;
1416
1417         REQUIRE(VALID_CONTEXT(ctx));
1418         MCTXLOCK(ctx, &ctx->lock);
1419
1420         for (i = 0; i <= ctx->max_size; i++) {
1421                 s = &ctx->stats[i];
1422
1423                 if (s->totalgets == 0U && s->gets == 0U)
1424                         continue;
1425                 fprintf(out, "%s%5lu: %11lu gets, %11lu rem",
1426                         (i == ctx->max_size) ? ">=" : "  ",
1427                         (unsigned long) i, s->totalgets, s->gets);
1428                 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0 &&
1429                     (s->blocks != 0U || s->freefrags != 0U))
1430                         fprintf(out, " (%lu bl, %lu ff)",
1431                                 s->blocks, s->freefrags);
1432                 fputc('\n', out);
1433         }
1434
1435         /*
1436          * Note that since a pool can be locked now, these stats might be
1437          * somewhat off if the pool is in active use at the time the stats
1438          * are dumped.  The link fields are protected by the isc_mem_t's
1439          * lock, however, so walking this list and extracting integers from
1440          * stats fields is always safe.
1441          */
1442         pool = ISC_LIST_HEAD(ctx->pools);
1443         if (pool != NULL) {
1444                 fprintf(out, "%s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1445                                             ISC_MSG_POOLSTATS,
1446                                             "[Pool statistics]\n"));
1447                 fprintf(out, "%15s %10s %10s %10s %10s %10s %10s %10s %1s\n",
1448                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1449                                        ISC_MSG_POOLNAME, "name"),
1450                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1451                                        ISC_MSG_POOLSIZE, "size"),
1452                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1453                                        ISC_MSG_POOLMAXALLOC, "maxalloc"),
1454                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1455                                        ISC_MSG_POOLALLOCATED, "allocated"),
1456                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1457                                        ISC_MSG_POOLFREECOUNT, "freecount"),
1458                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1459                                        ISC_MSG_POOLFREEMAX, "freemax"),
1460                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1461                                        ISC_MSG_POOLFILLCOUNT, "fillcount"),
1462                         isc_msgcat_get(isc_msgcat, ISC_MSGSET_MEM,
1463                                        ISC_MSG_POOLGETS, "gets"),
1464                         "L");
1465         }
1466         while (pool != NULL) {
1467                 fprintf(out, "%15s %10lu %10u %10u %10u %10u %10u %10u %s\n",
1468                         pool->name, (unsigned long) pool->size, pool->maxalloc,
1469                         pool->allocated, pool->freecount, pool->freemax,
1470                         pool->fillcount, pool->gets,
1471                         (pool->lock == NULL ? "N" : "Y"));
1472                 pool = ISC_LIST_NEXT(pool, link);
1473         }
1474
1475 #if ISC_MEM_TRACKLINES
1476         print_active(ctx, out);
1477 #endif
1478
1479         MCTXUNLOCK(ctx, &ctx->lock);
1480 }
1481
1482 /*
1483  * Replacements for malloc() and free() -- they implicitly remember the
1484  * size of the object allocated (with some additional overhead).
1485  */
1486
1487 static void *
1488 isc__mem_allocateunlocked(isc_mem_t *ctx0, size_t size) {
1489         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1490         size_info *si;
1491
1492         size += ALIGNMENT_SIZE;
1493         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)
1494                 size += ALIGNMENT_SIZE;
1495
1496         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0)
1497                 si = mem_getunlocked(ctx, size);
1498         else
1499                 si = mem_get(ctx, size);
1500
1501         if (si == NULL)
1502                 return (NULL);
1503         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0) {
1504                 si->u.ctx = ctx;
1505                 si++;
1506         }
1507         si->u.size = size;
1508         return (&si[1]);
1509 }
1510
1511 ISC_MEMFUNC_SCOPE void *
1512 isc___mem_allocate(isc_mem_t *ctx0, size_t size FLARG) {
1513         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1514         size_info *si;
1515         isc_boolean_t call_water = ISC_FALSE;
1516
1517         REQUIRE(VALID_CONTEXT(ctx));
1518
1519         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1520                 MCTXLOCK(ctx, &ctx->lock);
1521                 si = isc__mem_allocateunlocked((isc_mem_t *)ctx, size);
1522         } else {
1523                 si = isc__mem_allocateunlocked((isc_mem_t *)ctx, size);
1524                 MCTXLOCK(ctx, &ctx->lock);
1525                 if (si != NULL)
1526                         mem_getstats(ctx, si[-1].u.size);
1527         }
1528
1529 #if ISC_MEM_TRACKLINES
1530         ADD_TRACE(ctx, si, si[-1].u.size, file, line);
1531 #endif
1532         if (ctx->hi_water != 0U && !ctx->hi_called &&
1533             ctx->inuse > ctx->hi_water) {
1534                 ctx->hi_called = ISC_TRUE;
1535                 call_water = ISC_TRUE;
1536         }
1537         if (ctx->inuse > ctx->maxinuse) {
1538                 ctx->maxinuse = ctx->inuse;
1539                 if (ctx->hi_water != 0U && ctx->inuse > ctx->hi_water &&
1540                     (isc_mem_debugging & ISC_MEM_DEBUGUSAGE) != 0)
1541                         fprintf(stderr, "maxinuse = %lu\n",
1542                                 (unsigned long)ctx->inuse);
1543         }
1544         MCTXUNLOCK(ctx, &ctx->lock);
1545
1546         if (call_water)
1547                 (ctx->water)(ctx->water_arg, ISC_MEM_HIWATER);
1548
1549         return (si);
1550 }
1551
1552 ISC_MEMFUNC_SCOPE void *
1553 isc___mem_reallocate(isc_mem_t *ctx0, void *ptr, size_t size FLARG) {
1554         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1555         void *new_ptr = NULL;
1556         size_t oldsize, copysize;
1557
1558         REQUIRE(VALID_CONTEXT(ctx));
1559
1560         /*
1561          * This function emulates the realloc(3) standard library function:
1562          * - if size > 0, allocate new memory; and if ptr is non NULL, copy
1563          *   as much of the old contents to the new buffer and free the old one.
1564          *   Note that when allocation fails the original pointer is intact;
1565          *   the caller must free it.
1566          * - if size is 0 and ptr is non NULL, simply free the given ptr.
1567          * - this function returns:
1568          *     pointer to the newly allocated memory, or
1569          *     NULL if allocation fails or doesn't happen.
1570          */
1571         if (size > 0U) {
1572                 new_ptr = isc__mem_allocate(ctx0, size FLARG_PASS);
1573                 if (new_ptr != NULL && ptr != NULL) {
1574                         oldsize = (((size_info *)ptr)[-1]).u.size;
1575                         INSIST(oldsize >= ALIGNMENT_SIZE);
1576                         oldsize -= ALIGNMENT_SIZE;
1577                         copysize = oldsize > size ? size : oldsize;
1578                         memcpy(new_ptr, ptr, copysize);
1579                         isc__mem_free(ctx0, ptr FLARG_PASS);
1580                 }
1581         } else if (ptr != NULL)
1582                 isc__mem_free(ctx0, ptr FLARG_PASS);
1583
1584         return (new_ptr);
1585 }
1586
1587 ISC_MEMFUNC_SCOPE void
1588 isc___mem_free(isc_mem_t *ctx0, void *ptr FLARG) {
1589         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1590         size_info *si;
1591         size_t size;
1592         isc_boolean_t call_water= ISC_FALSE;
1593
1594         REQUIRE(VALID_CONTEXT(ctx));
1595         REQUIRE(ptr != NULL);
1596
1597         if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0) {
1598                 si = &(((size_info *)ptr)[-2]);
1599                 REQUIRE(si->u.ctx == ctx);
1600                 size = si[1].u.size;
1601         } else {
1602                 si = &(((size_info *)ptr)[-1]);
1603                 size = si->u.size;
1604         }
1605
1606         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1607                 MCTXLOCK(ctx, &ctx->lock);
1608                 mem_putunlocked(ctx, si, size);
1609         } else {
1610                 mem_put(ctx, si, size);
1611                 MCTXLOCK(ctx, &ctx->lock);
1612                 mem_putstats(ctx, si, size);
1613         }
1614
1615         DELETE_TRACE(ctx, ptr, size, file, line);
1616
1617         /*
1618          * The check against ctx->lo_water == 0 is for the condition
1619          * when the context was pushed over hi_water but then had
1620          * isc_mem_setwater() called with 0 for hi_water and lo_water.
1621          */
1622         if (ctx->hi_called &&
1623             (ctx->inuse < ctx->lo_water || ctx->lo_water == 0U)) {
1624                 ctx->hi_called = ISC_FALSE;
1625
1626                 if (ctx->water != NULL)
1627                         call_water = ISC_TRUE;
1628         }
1629         MCTXUNLOCK(ctx, &ctx->lock);
1630
1631         if (call_water)
1632                 (ctx->water)(ctx->water_arg, ISC_MEM_LOWATER);
1633 }
1634
1635
1636 /*
1637  * Other useful things.
1638  */
1639
1640 ISC_MEMFUNC_SCOPE char *
1641 isc___mem_strdup(isc_mem_t *mctx0, const char *s FLARG) {
1642         isc__mem_t *mctx = (isc__mem_t *)mctx0;
1643         size_t len;
1644         char *ns;
1645
1646         REQUIRE(VALID_CONTEXT(mctx));
1647         REQUIRE(s != NULL);
1648
1649         len = strlen(s);
1650
1651         ns = isc___mem_allocate((isc_mem_t *)mctx, len + 1 FLARG_PASS);
1652
1653         if (ns != NULL)
1654                 strncpy(ns, s, len + 1);
1655
1656         return (ns);
1657 }
1658
1659 ISC_MEMFUNC_SCOPE void
1660 isc__mem_setdestroycheck(isc_mem_t *ctx0, isc_boolean_t flag) {
1661         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1662
1663         REQUIRE(VALID_CONTEXT(ctx));
1664         MCTXLOCK(ctx, &ctx->lock);
1665
1666         ctx->checkfree = flag;
1667
1668         MCTXUNLOCK(ctx, &ctx->lock);
1669 }
1670
1671 /*
1672  * Quotas
1673  */
1674
1675 ISC_MEMFUNC_SCOPE void
1676 isc__mem_setquota(isc_mem_t *ctx0, size_t quota) {
1677         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1678
1679         REQUIRE(VALID_CONTEXT(ctx));
1680         MCTXLOCK(ctx, &ctx->lock);
1681
1682         ctx->quota = quota;
1683
1684         MCTXUNLOCK(ctx, &ctx->lock);
1685 }
1686
1687 ISC_MEMFUNC_SCOPE size_t
1688 isc__mem_getquota(isc_mem_t *ctx0) {
1689         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1690         size_t quota;
1691
1692         REQUIRE(VALID_CONTEXT(ctx));
1693         MCTXLOCK(ctx, &ctx->lock);
1694
1695         quota = ctx->quota;
1696
1697         MCTXUNLOCK(ctx, &ctx->lock);
1698
1699         return (quota);
1700 }
1701
1702 ISC_MEMFUNC_SCOPE size_t
1703 isc__mem_inuse(isc_mem_t *ctx0) {
1704         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1705         size_t inuse;
1706
1707         REQUIRE(VALID_CONTEXT(ctx));
1708         MCTXLOCK(ctx, &ctx->lock);
1709
1710         inuse = ctx->inuse;
1711
1712         MCTXUNLOCK(ctx, &ctx->lock);
1713
1714         return (inuse);
1715 }
1716
1717 ISC_MEMFUNC_SCOPE void
1718 isc__mem_setwater(isc_mem_t *ctx0, isc_mem_water_t water, void *water_arg,
1719                  size_t hiwater, size_t lowater)
1720 {
1721         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1722         isc_boolean_t callwater = ISC_FALSE;
1723         isc_mem_water_t oldwater;
1724         void *oldwater_arg;
1725
1726         REQUIRE(VALID_CONTEXT(ctx));
1727         REQUIRE(hiwater >= lowater);
1728
1729         MCTXLOCK(ctx, &ctx->lock);
1730         oldwater = ctx->water;
1731         oldwater_arg = ctx->water_arg;
1732         if (water == NULL) {
1733                 callwater = ctx->hi_called;
1734                 ctx->water = NULL;
1735                 ctx->water_arg = NULL;
1736                 ctx->hi_water = 0;
1737                 ctx->lo_water = 0;
1738                 ctx->hi_called = ISC_FALSE;
1739         } else {
1740                 if (ctx->hi_called &&
1741                     (ctx->water != water || ctx->water_arg != water_arg ||
1742                      ctx->inuse < lowater || lowater == 0U))
1743                         callwater = ISC_TRUE;
1744                 ctx->water = water;
1745                 ctx->water_arg = water_arg;
1746                 ctx->hi_water = hiwater;
1747                 ctx->lo_water = lowater;
1748                 ctx->hi_called = ISC_FALSE;
1749         }
1750         MCTXUNLOCK(ctx, &ctx->lock);
1751
1752         if (callwater && oldwater != NULL)
1753                 (oldwater)(oldwater_arg, ISC_MEM_LOWATER);
1754 }
1755
1756 ISC_MEMFUNC_SCOPE void
1757 isc__mem_setname(isc_mem_t *ctx0, const char *name, void *tag) {
1758         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1759
1760         REQUIRE(VALID_CONTEXT(ctx));
1761
1762         LOCK(&ctx->lock);
1763         memset(ctx->name, 0, sizeof(ctx->name));
1764         strncpy(ctx->name, name, sizeof(ctx->name) - 1);
1765         ctx->tag = tag;
1766         UNLOCK(&ctx->lock);
1767 }
1768
1769 ISC_MEMFUNC_SCOPE const char *
1770 isc__mem_getname(isc_mem_t *ctx0) {
1771         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1772
1773         REQUIRE(VALID_CONTEXT(ctx));
1774
1775         return (ctx->name);
1776 }
1777
1778 ISC_MEMFUNC_SCOPE void *
1779 isc__mem_gettag(isc_mem_t *ctx0) {
1780         isc__mem_t *ctx = (isc__mem_t *)ctx0;
1781
1782         REQUIRE(VALID_CONTEXT(ctx));
1783
1784         return (ctx->tag);
1785 }
1786
1787 /*
1788  * Memory pool stuff
1789  */
1790
1791 ISC_MEMFUNC_SCOPE isc_result_t
1792 isc__mempool_create(isc_mem_t *mctx0, size_t size, isc_mempool_t **mpctxp) {
1793         isc__mem_t *mctx = (isc__mem_t *)mctx0;
1794         isc__mempool_t *mpctx;
1795
1796         REQUIRE(VALID_CONTEXT(mctx));
1797         REQUIRE(size > 0U);
1798         REQUIRE(mpctxp != NULL && *mpctxp == NULL);
1799
1800         /*
1801          * Allocate space for this pool, initialize values, and if all works
1802          * well, attach to the memory context.
1803          */
1804         mpctx = isc_mem_get((isc_mem_t *)mctx, sizeof(isc__mempool_t));
1805         if (mpctx == NULL)
1806                 return (ISC_R_NOMEMORY);
1807
1808         mpctx->common.methods = (isc_mempoolmethods_t *)&mempoolmethods;
1809         mpctx->common.impmagic = MEMPOOL_MAGIC;
1810         mpctx->common.magic = ISCAPI_MPOOL_MAGIC;
1811         mpctx->lock = NULL;
1812         mpctx->mctx = mctx;
1813         mpctx->size = size;
1814         mpctx->maxalloc = UINT_MAX;
1815         mpctx->allocated = 0;
1816         mpctx->freecount = 0;
1817         mpctx->freemax = 1;
1818         mpctx->fillcount = 1;
1819         mpctx->gets = 0;
1820 #if ISC_MEMPOOL_NAMES
1821         mpctx->name[0] = 0;
1822 #endif
1823         mpctx->items = NULL;
1824
1825         *mpctxp = (isc_mempool_t *)mpctx;
1826
1827         MCTXLOCK(mctx, &mctx->lock);
1828         ISC_LIST_INITANDAPPEND(mctx->pools, mpctx, link);
1829         mctx->poolcnt++;
1830         MCTXUNLOCK(mctx, &mctx->lock);
1831
1832         return (ISC_R_SUCCESS);
1833 }
1834
1835 ISC_MEMFUNC_SCOPE void
1836 isc__mempool_setname(isc_mempool_t *mpctx0, const char *name) {
1837         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1838
1839         REQUIRE(name != NULL);
1840         REQUIRE(VALID_MEMPOOL(mpctx));
1841
1842 #if ISC_MEMPOOL_NAMES
1843         if (mpctx->lock != NULL)
1844                 LOCK(mpctx->lock);
1845
1846         strncpy(mpctx->name, name, sizeof(mpctx->name) - 1);
1847         mpctx->name[sizeof(mpctx->name) - 1] = '\0';
1848
1849         if (mpctx->lock != NULL)
1850                 UNLOCK(mpctx->lock);
1851 #else
1852         UNUSED(mpctx);
1853         UNUSED(name);
1854 #endif
1855 }
1856
1857 ISC_MEMFUNC_SCOPE void
1858 isc__mempool_destroy(isc_mempool_t **mpctxp) {
1859         isc__mempool_t *mpctx;
1860         isc__mem_t *mctx;
1861         isc_mutex_t *lock;
1862         element *item;
1863
1864         REQUIRE(mpctxp != NULL);
1865         mpctx = (isc__mempool_t *)*mpctxp;
1866         REQUIRE(VALID_MEMPOOL(mpctx));
1867 #if ISC_MEMPOOL_NAMES
1868         if (mpctx->allocated > 0)
1869                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1870                                  "isc__mempool_destroy(): mempool %s "
1871                                  "leaked memory",
1872                                  mpctx->name);
1873 #endif
1874         REQUIRE(mpctx->allocated == 0);
1875
1876         mctx = mpctx->mctx;
1877
1878         lock = mpctx->lock;
1879
1880         if (lock != NULL)
1881                 LOCK(lock);
1882
1883         /*
1884          * Return any items on the free list
1885          */
1886         MCTXLOCK(mctx, &mctx->lock);
1887         while (mpctx->items != NULL) {
1888                 INSIST(mpctx->freecount > 0);
1889                 mpctx->freecount--;
1890                 item = mpctx->items;
1891                 mpctx->items = item->next;
1892
1893                 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1894                         mem_putunlocked(mctx, item, mpctx->size);
1895                 } else {
1896                         mem_put(mctx, item, mpctx->size);
1897                         mem_putstats(mctx, item, mpctx->size);
1898                 }
1899         }
1900         MCTXUNLOCK(mctx, &mctx->lock);
1901
1902         /*
1903          * Remove our linked list entry from the memory context.
1904          */
1905         MCTXLOCK(mctx, &mctx->lock);
1906         ISC_LIST_UNLINK(mctx->pools, mpctx, link);
1907         mctx->poolcnt--;
1908         MCTXUNLOCK(mctx, &mctx->lock);
1909
1910         mpctx->common.impmagic = 0;
1911         mpctx->common.magic = 0;
1912
1913         isc_mem_put((isc_mem_t *)mpctx->mctx, mpctx, sizeof(isc__mempool_t));
1914
1915         if (lock != NULL)
1916                 UNLOCK(lock);
1917
1918         *mpctxp = NULL;
1919 }
1920
1921 ISC_MEMFUNC_SCOPE void
1922 isc__mempool_associatelock(isc_mempool_t *mpctx0, isc_mutex_t *lock) {
1923         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1924
1925         REQUIRE(VALID_MEMPOOL(mpctx));
1926         REQUIRE(mpctx->lock == NULL);
1927         REQUIRE(lock != NULL);
1928
1929         mpctx->lock = lock;
1930 }
1931
1932 ISC_MEMFUNC_SCOPE void *
1933 isc___mempool_get(isc_mempool_t *mpctx0 FLARG) {
1934         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1935         element *item;
1936         isc__mem_t *mctx;
1937         unsigned int i;
1938
1939         REQUIRE(VALID_MEMPOOL(mpctx));
1940
1941         mctx = mpctx->mctx;
1942
1943         if (mpctx->lock != NULL)
1944                 LOCK(mpctx->lock);
1945
1946         /*
1947          * Don't let the caller go over quota
1948          */
1949         if (mpctx->allocated >= mpctx->maxalloc) {
1950                 item = NULL;
1951                 goto out;
1952         }
1953
1954         /*
1955          * if we have a free list item, return the first here
1956          */
1957         item = mpctx->items;
1958         if (item != NULL) {
1959                 mpctx->items = item->next;
1960                 INSIST(mpctx->freecount > 0);
1961                 mpctx->freecount--;
1962                 mpctx->gets++;
1963                 mpctx->allocated++;
1964                 goto out;
1965         }
1966
1967         /*
1968          * We need to dip into the well.  Lock the memory context here and
1969          * fill up our free list.
1970          */
1971         MCTXLOCK(mctx, &mctx->lock);
1972         for (i = 0; i < mpctx->fillcount; i++) {
1973                 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1974                         item = mem_getunlocked(mctx, mpctx->size);
1975                 } else {
1976                         item = mem_get(mctx, mpctx->size);
1977                         if (item != NULL)
1978                                 mem_getstats(mctx, mpctx->size);
1979                 }
1980                 if (item == NULL)
1981                         break;
1982                 item->next = mpctx->items;
1983                 mpctx->items = item;
1984                 mpctx->freecount++;
1985         }
1986         MCTXUNLOCK(mctx, &mctx->lock);
1987
1988         /*
1989          * If we didn't get any items, return NULL.
1990          */
1991         item = mpctx->items;
1992         if (item == NULL)
1993                 goto out;
1994
1995         mpctx->items = item->next;
1996         mpctx->freecount--;
1997         mpctx->gets++;
1998         mpctx->allocated++;
1999
2000  out:
2001         if (mpctx->lock != NULL)
2002                 UNLOCK(mpctx->lock);
2003
2004 #if ISC_MEM_TRACKLINES
2005         if (item != NULL) {
2006                 MCTXLOCK(mctx, &mctx->lock);
2007                 ADD_TRACE(mctx, item, mpctx->size, file, line);
2008                 MCTXUNLOCK(mctx, &mctx->lock);
2009         }
2010 #endif /* ISC_MEM_TRACKLINES */
2011
2012         return (item);
2013 }
2014
2015 ISC_MEMFUNC_SCOPE void
2016 isc___mempool_put(isc_mempool_t *mpctx0, void *mem FLARG) {
2017         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2018         isc__mem_t *mctx;
2019         element *item;
2020
2021         REQUIRE(VALID_MEMPOOL(mpctx));
2022         REQUIRE(mem != NULL);
2023
2024         mctx = mpctx->mctx;
2025
2026         if (mpctx->lock != NULL)
2027                 LOCK(mpctx->lock);
2028
2029         INSIST(mpctx->allocated > 0);
2030         mpctx->allocated--;
2031
2032 #if ISC_MEM_TRACKLINES
2033         MCTXLOCK(mctx, &mctx->lock);
2034         DELETE_TRACE(mctx, mem, mpctx->size, file, line);
2035         MCTXUNLOCK(mctx, &mctx->lock);
2036 #endif /* ISC_MEM_TRACKLINES */
2037
2038         /*
2039          * If our free list is full, return this to the mctx directly.
2040          */
2041         if (mpctx->freecount >= mpctx->freemax) {
2042                 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
2043                         MCTXLOCK(mctx, &mctx->lock);
2044                         mem_putunlocked(mctx, mem, mpctx->size);
2045                         MCTXUNLOCK(mctx, &mctx->lock);
2046                 } else {
2047                         mem_put(mctx, mem, mpctx->size);
2048                         MCTXLOCK(mctx, &mctx->lock);
2049                         mem_putstats(mctx, mem, mpctx->size);
2050                         MCTXUNLOCK(mctx, &mctx->lock);
2051                 }
2052                 if (mpctx->lock != NULL)
2053                         UNLOCK(mpctx->lock);
2054                 return;
2055         }
2056
2057         /*
2058          * Otherwise, attach it to our free list and bump the counter.
2059          */
2060         mpctx->freecount++;
2061         item = (element *)mem;
2062         item->next = mpctx->items;
2063         mpctx->items = item;
2064
2065         if (mpctx->lock != NULL)
2066                 UNLOCK(mpctx->lock);
2067 }
2068
2069 /*
2070  * Quotas
2071  */
2072
2073 ISC_MEMFUNC_SCOPE void
2074 isc__mempool_setfreemax(isc_mempool_t *mpctx0, unsigned int limit) {
2075         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2076
2077         REQUIRE(VALID_MEMPOOL(mpctx));
2078
2079         if (mpctx->lock != NULL)
2080                 LOCK(mpctx->lock);
2081
2082         mpctx->freemax = limit;
2083
2084         if (mpctx->lock != NULL)
2085                 UNLOCK(mpctx->lock);
2086 }
2087
2088 ISC_MEMFUNC_SCOPE unsigned int
2089 isc__mempool_getfreemax(isc_mempool_t *mpctx0) {
2090         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2091         unsigned int freemax;
2092
2093         REQUIRE(VALID_MEMPOOL(mpctx));
2094
2095         if (mpctx->lock != NULL)
2096                 LOCK(mpctx->lock);
2097
2098         freemax = mpctx->freemax;
2099
2100         if (mpctx->lock != NULL)
2101                 UNLOCK(mpctx->lock);
2102
2103         return (freemax);
2104 }
2105
2106 ISC_MEMFUNC_SCOPE unsigned int
2107 isc__mempool_getfreecount(isc_mempool_t *mpctx0) {
2108         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2109         unsigned int freecount;
2110
2111         REQUIRE(VALID_MEMPOOL(mpctx));
2112
2113         if (mpctx->lock != NULL)
2114                 LOCK(mpctx->lock);
2115
2116         freecount = mpctx->freecount;
2117
2118         if (mpctx->lock != NULL)
2119                 UNLOCK(mpctx->lock);
2120
2121         return (freecount);
2122 }
2123
2124 ISC_MEMFUNC_SCOPE void
2125 isc__mempool_setmaxalloc(isc_mempool_t *mpctx0, unsigned int limit) {
2126         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2127
2128         REQUIRE(limit > 0);
2129
2130         REQUIRE(VALID_MEMPOOL(mpctx));
2131
2132         if (mpctx->lock != NULL)
2133                 LOCK(mpctx->lock);
2134
2135         mpctx->maxalloc = limit;
2136
2137         if (mpctx->lock != NULL)
2138                 UNLOCK(mpctx->lock);
2139 }
2140
2141 ISC_MEMFUNC_SCOPE unsigned int
2142 isc__mempool_getmaxalloc(isc_mempool_t *mpctx0) {
2143         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2144         unsigned int maxalloc;
2145
2146         REQUIRE(VALID_MEMPOOL(mpctx));
2147
2148         if (mpctx->lock != NULL)
2149                 LOCK(mpctx->lock);
2150
2151         maxalloc = mpctx->maxalloc;
2152
2153         if (mpctx->lock != NULL)
2154                 UNLOCK(mpctx->lock);
2155
2156         return (maxalloc);
2157 }
2158
2159 ISC_MEMFUNC_SCOPE unsigned int
2160 isc__mempool_getallocated(isc_mempool_t *mpctx0) {
2161         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2162         unsigned int allocated;
2163
2164         REQUIRE(VALID_MEMPOOL(mpctx));
2165
2166         if (mpctx->lock != NULL)
2167                 LOCK(mpctx->lock);
2168
2169         allocated = mpctx->allocated;
2170
2171         if (mpctx->lock != NULL)
2172                 UNLOCK(mpctx->lock);
2173
2174         return (allocated);
2175 }
2176
2177 ISC_MEMFUNC_SCOPE void
2178 isc__mempool_setfillcount(isc_mempool_t *mpctx0, unsigned int limit) {
2179         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2180
2181         REQUIRE(limit > 0);
2182         REQUIRE(VALID_MEMPOOL(mpctx));
2183
2184         if (mpctx->lock != NULL)
2185                 LOCK(mpctx->lock);
2186
2187         mpctx->fillcount = limit;
2188
2189         if (mpctx->lock != NULL)
2190                 UNLOCK(mpctx->lock);
2191 }
2192
2193 ISC_MEMFUNC_SCOPE unsigned int
2194 isc__mempool_getfillcount(isc_mempool_t *mpctx0) {
2195         isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2196
2197         unsigned int fillcount;
2198
2199         REQUIRE(VALID_MEMPOOL(mpctx));
2200
2201         if (mpctx->lock != NULL)
2202                 LOCK(mpctx->lock);
2203
2204         fillcount = mpctx->fillcount;
2205
2206         if (mpctx->lock != NULL)
2207                 UNLOCK(mpctx->lock);
2208
2209         return (fillcount);
2210 }
2211
2212 #ifdef USE_MEMIMPREGISTER
2213 isc_result_t
2214 isc__mem_register() {
2215         return (isc_mem_register(isc__mem_create2));
2216 }
2217 #endif
2218
2219 #ifdef BIND9
2220 ISC_MEMFUNC_SCOPE void
2221 isc__mem_printactive(isc_mem_t *ctx0, FILE *file) {
2222         isc__mem_t *ctx = (isc__mem_t *)ctx0;
2223
2224         REQUIRE(VALID_CONTEXT(ctx));
2225         REQUIRE(file != NULL);
2226
2227 #if !ISC_MEM_TRACKLINES
2228         UNUSED(ctx);
2229         UNUSED(file);
2230 #else
2231         print_active(ctx, file);
2232 #endif
2233 }
2234
2235 ISC_MEMFUNC_SCOPE void
2236 isc__mem_printallactive(FILE *file) {
2237 #if !ISC_MEM_TRACKLINES
2238         UNUSED(file);
2239 #else
2240         isc__mem_t *ctx;
2241
2242         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
2243
2244         LOCK(&lock);
2245         for (ctx = ISC_LIST_HEAD(contexts);
2246              ctx != NULL;
2247              ctx = ISC_LIST_NEXT(ctx, link)) {
2248                 fprintf(file, "context: %p\n", ctx);
2249                 print_active(ctx, file);
2250         }
2251         UNLOCK(&lock);
2252 #endif
2253 }
2254
2255 ISC_MEMFUNC_SCOPE void
2256 isc__mem_checkdestroyed(FILE *file) {
2257
2258         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
2259
2260         LOCK(&lock);
2261         if (!ISC_LIST_EMPTY(contexts))  {
2262 #if ISC_MEM_TRACKLINES
2263                 isc__mem_t *ctx;
2264
2265                 for (ctx = ISC_LIST_HEAD(contexts);
2266                      ctx != NULL;
2267                      ctx = ISC_LIST_NEXT(ctx, link)) {
2268                         fprintf(file, "context: %p\n", ctx);
2269                         print_active(ctx, file);
2270                 }
2271                 fflush(file);
2272 #endif
2273                 INSIST(0);
2274         }
2275         UNLOCK(&lock);
2276 }
2277
2278 ISC_MEMFUNC_SCOPE unsigned int
2279 isc_mem_references(isc_mem_t *ctx0) {
2280         isc__mem_t *ctx = (isc__mem_t *)ctx0;
2281         unsigned int references;
2282
2283         REQUIRE(VALID_CONTEXT(ctx));
2284
2285         MCTXLOCK(ctx, &ctx->lock);
2286         references = ctx->references;
2287         MCTXUNLOCK(ctx, &ctx->lock);
2288
2289         return (references);
2290 }
2291
2292 #ifdef HAVE_LIBXML2
2293
2294 typedef struct summarystat {
2295         isc_uint64_t    total;
2296         isc_uint64_t    inuse;
2297         isc_uint64_t    blocksize;
2298         isc_uint64_t    contextsize;
2299 } summarystat_t;
2300
2301 static void
2302 renderctx(isc__mem_t *ctx, summarystat_t *summary, xmlTextWriterPtr writer) {
2303         REQUIRE(VALID_CONTEXT(ctx));
2304
2305         xmlTextWriterStartElement(writer, ISC_XMLCHAR "context");
2306
2307         xmlTextWriterStartElement(writer, ISC_XMLCHAR "id");
2308         xmlTextWriterWriteFormatString(writer, "%p", ctx);
2309         xmlTextWriterEndElement(writer); /* id */
2310
2311         if (ctx->name[0] != 0) {
2312                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "name");
2313                 xmlTextWriterWriteFormatString(writer, "%s", ctx->name);
2314                 xmlTextWriterEndElement(writer); /* name */
2315         }
2316
2317         REQUIRE(VALID_CONTEXT(ctx));
2318         MCTXLOCK(ctx, &ctx->lock);
2319
2320         summary->contextsize += sizeof(*ctx) +
2321                 (ctx->max_size + 1) * sizeof(struct stats) +
2322                 ctx->max_size * sizeof(element *) +
2323                 ctx->basic_table_count * sizeof(char *);
2324 #if ISC_MEM_TRACKLINES
2325         if (ctx->debuglist != NULL) {
2326                 summary->contextsize +=
2327                         (ctx->max_size + 1) * sizeof(debuglist_t) +
2328                         ctx->debuglistcnt * sizeof(debuglink_t);
2329         }
2330 #endif
2331         xmlTextWriterStartElement(writer, ISC_XMLCHAR "references");
2332         xmlTextWriterWriteFormatString(writer, "%d", ctx->references);
2333         xmlTextWriterEndElement(writer); /* references */
2334
2335         summary->total += ctx->total;
2336         xmlTextWriterStartElement(writer, ISC_XMLCHAR "total");
2337         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2338                                        (isc_uint64_t)ctx->total);
2339         xmlTextWriterEndElement(writer); /* total */
2340
2341         summary->inuse += ctx->inuse;
2342         xmlTextWriterStartElement(writer, ISC_XMLCHAR "inuse");
2343         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2344                                        (isc_uint64_t)ctx->inuse);
2345         xmlTextWriterEndElement(writer); /* inuse */
2346
2347         xmlTextWriterStartElement(writer, ISC_XMLCHAR "maxinuse");
2348         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2349                                        (isc_uint64_t)ctx->maxinuse);
2350         xmlTextWriterEndElement(writer); /* maxinuse */
2351
2352         xmlTextWriterStartElement(writer, ISC_XMLCHAR "blocksize");
2353         if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
2354                 summary->blocksize += ctx->basic_table_count *
2355                         NUM_BASIC_BLOCKS * ctx->mem_target;
2356                 xmlTextWriterWriteFormatString(writer,
2357                                                "%" ISC_PRINT_QUADFORMAT "u",
2358                                                (isc_uint64_t)
2359                                                ctx->basic_table_count *
2360                                                NUM_BASIC_BLOCKS *
2361                                                ctx->mem_target);
2362         } else
2363                 xmlTextWriterWriteFormatString(writer, "%s", "-");
2364         xmlTextWriterEndElement(writer); /* blocksize */
2365
2366         xmlTextWriterStartElement(writer, ISC_XMLCHAR "pools");
2367         xmlTextWriterWriteFormatString(writer, "%u", ctx->poolcnt);
2368         xmlTextWriterEndElement(writer); /* pools */
2369         summary->contextsize += ctx->poolcnt * sizeof(isc_mempool_t);
2370
2371         xmlTextWriterStartElement(writer, ISC_XMLCHAR "hiwater");
2372         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2373                                        (isc_uint64_t)ctx->hi_water);
2374         xmlTextWriterEndElement(writer); /* hiwater */
2375
2376         xmlTextWriterStartElement(writer, ISC_XMLCHAR "lowater");
2377         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2378                                        (isc_uint64_t)ctx->lo_water);
2379         xmlTextWriterEndElement(writer); /* lowater */
2380
2381         MCTXUNLOCK(ctx, &ctx->lock);
2382
2383         xmlTextWriterEndElement(writer); /* context */
2384 }
2385
2386 void
2387 isc_mem_renderxml(xmlTextWriterPtr writer) {
2388         isc__mem_t *ctx;
2389         summarystat_t summary;
2390         isc_uint64_t lost;
2391
2392         memset(&summary, 0, sizeof(summary));
2393
2394         xmlTextWriterStartElement(writer, ISC_XMLCHAR "contexts");
2395
2396         RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
2397
2398         LOCK(&lock);
2399         lost = totallost;
2400         for (ctx = ISC_LIST_HEAD(contexts);
2401              ctx != NULL;
2402              ctx = ISC_LIST_NEXT(ctx, link)) {
2403                 renderctx(ctx, &summary, writer);
2404         }
2405         UNLOCK(&lock);
2406
2407         xmlTextWriterEndElement(writer); /* contexts */
2408
2409         xmlTextWriterStartElement(writer, ISC_XMLCHAR "summary");
2410
2411         xmlTextWriterStartElement(writer, ISC_XMLCHAR "TotalUse");
2412         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2413                                        summary.total);
2414         xmlTextWriterEndElement(writer); /* TotalUse */
2415
2416         xmlTextWriterStartElement(writer, ISC_XMLCHAR "InUse");
2417         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2418                                        summary.inuse);
2419         xmlTextWriterEndElement(writer); /* InUse */
2420
2421         xmlTextWriterStartElement(writer, ISC_XMLCHAR "BlockSize");
2422         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2423                                        summary.blocksize);
2424         xmlTextWriterEndElement(writer); /* BlockSize */
2425
2426         xmlTextWriterStartElement(writer, ISC_XMLCHAR "ContextSize");
2427         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2428                                        summary.contextsize);
2429         xmlTextWriterEndElement(writer); /* ContextSize */
2430
2431         xmlTextWriterStartElement(writer, ISC_XMLCHAR "Lost");
2432         xmlTextWriterWriteFormatString(writer, "%" ISC_PRINT_QUADFORMAT "u",
2433                                        lost);
2434         xmlTextWriterEndElement(writer); /* Lost */
2435
2436         xmlTextWriterEndElement(writer); /* summary */
2437 }
2438
2439 #endif /* HAVE_LIBXML2 */
2440 #endif /* BIND9 */