]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_malloc.c
Clear stack allocated data structure to prevent kernel memory leak.
[FreeBSD/FreeBSD.git] / sys / kern / kern_malloc.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1987, 1991, 1993
5  *      The Regents of the University of California.
6  * Copyright (c) 2005-2009 Robert N. M. Watson
7  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> (mallocarray)
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)kern_malloc.c       8.3 (Berkeley) 1/4/94
35  */
36
37 /*
38  * Kernel malloc(9) implementation -- general purpose kernel memory allocator
39  * based on memory types.  Back end is implemented using the UMA(9) zone
40  * allocator.  A set of fixed-size buckets are used for smaller allocations,
41  * and a special UMA allocation interface is used for larger allocations.
42  * Callers declare memory types, and statistics are maintained independently
43  * for each memory type.  Statistics are maintained per-CPU for performance
44  * reasons.  See malloc(9) and comments in malloc.h for a detailed
45  * description.
46  */
47
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
50
51 #include "opt_ddb.h"
52 #include "opt_vm.h"
53
54 #include <sys/param.h>
55 #include <sys/systm.h>
56 #include <sys/kdb.h>
57 #include <sys/kernel.h>
58 #include <sys/lock.h>
59 #include <sys/malloc.h>
60 #include <sys/mutex.h>
61 #include <sys/vmmeter.h>
62 #include <sys/proc.h>
63 #include <sys/sbuf.h>
64 #include <sys/smp.h>
65 #include <sys/sysctl.h>
66 #include <sys/time.h>
67 #include <sys/vmem.h>
68
69 #include <vm/vm.h>
70 #include <vm/pmap.h>
71 #include <vm/vm_pageout.h>
72 #include <vm/vm_param.h>
73 #include <vm/vm_kern.h>
74 #include <vm/vm_extern.h>
75 #include <vm/vm_map.h>
76 #include <vm/vm_page.h>
77 #include <vm/uma.h>
78 #include <vm/uma_int.h>
79 #include <vm/uma_dbg.h>
80
81 #ifdef DEBUG_MEMGUARD
82 #include <vm/memguard.h>
83 #endif
84 #ifdef DEBUG_REDZONE
85 #include <vm/redzone.h>
86 #endif
87
88 #if defined(INVARIANTS) && defined(__i386__)
89 #include <machine/cpu.h>
90 #endif
91
92 #include <ddb/ddb.h>
93
94 #ifdef KDTRACE_HOOKS
95 #include <sys/dtrace_bsd.h>
96
97 bool    __read_frequently                       dtrace_malloc_enabled;
98 dtrace_malloc_probe_func_t __read_mostly        dtrace_malloc_probe;
99 #endif
100
101 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) ||             \
102     defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
103 #define MALLOC_DEBUG    1
104 #endif
105
106 /*
107  * When realloc() is called, if the new size is sufficiently smaller than
108  * the old size, realloc() will allocate a new, smaller block to avoid
109  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
110  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
111  */
112 #ifndef REALLOC_FRACTION
113 #define REALLOC_FRACTION        1       /* new block if <= half the size */
114 #endif
115
116 /*
117  * Centrally define some common malloc types.
118  */
119 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
120 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
121 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
122
123 static struct malloc_type *kmemstatistics;
124 static int kmemcount;
125
126 #define KMEM_ZSHIFT     4
127 #define KMEM_ZBASE      16
128 #define KMEM_ZMASK      (KMEM_ZBASE - 1)
129
130 #define KMEM_ZMAX       65536
131 #define KMEM_ZSIZE      (KMEM_ZMAX >> KMEM_ZSHIFT)
132 static uint8_t kmemsize[KMEM_ZSIZE + 1];
133
134 #ifndef MALLOC_DEBUG_MAXZONES
135 #define MALLOC_DEBUG_MAXZONES   1
136 #endif
137 static int numzones = MALLOC_DEBUG_MAXZONES;
138
139 /*
140  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
141  * of various sizes.
142  *
143  * XXX: The comment here used to read "These won't be powers of two for
144  * long."  It's possible that a significant amount of wasted memory could be
145  * recovered by tuning the sizes of these buckets.
146  */
147 struct {
148         int kz_size;
149         char *kz_name;
150         uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
151 } kmemzones[] = {
152         {16, "16", },
153         {32, "32", },
154         {64, "64", },
155         {128, "128", },
156         {256, "256", },
157         {512, "512", },
158         {1024, "1024", },
159         {2048, "2048", },
160         {4096, "4096", },
161         {8192, "8192", },
162         {16384, "16384", },
163         {32768, "32768", },
164         {65536, "65536", },
165         {0, NULL},
166 };
167
168 /*
169  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
170  * types are described by a data structure passed by the declaring code, but
171  * the malloc(9) implementation has its own data structure describing the
172  * type and statistics.  This permits the malloc(9)-internal data structures
173  * to be modified without breaking binary-compiled kernel modules that
174  * declare malloc types.
175  */
176 static uma_zone_t mt_zone;
177 static uma_zone_t mt_stats_zone;
178
179 u_long vm_kmem_size;
180 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
181     "Size of kernel memory");
182
183 static u_long kmem_zmax = KMEM_ZMAX;
184 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
185     "Maximum allocation size that malloc(9) would use UMA as backend");
186
187 static u_long vm_kmem_size_min;
188 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
189     "Minimum size of kernel memory");
190
191 static u_long vm_kmem_size_max;
192 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
193     "Maximum size of kernel memory");
194
195 static u_int vm_kmem_size_scale;
196 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
197     "Scale factor for kernel memory size");
198
199 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
200 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
201     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
202     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
203
204 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
205 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
206     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
207     sysctl_kmem_map_free, "LU", "Free space in kmem");
208
209 /*
210  * The malloc_mtx protects the kmemstatistics linked list.
211  */
212 struct mtx malloc_mtx;
213
214 #ifdef MALLOC_PROFILE
215 uint64_t krequests[KMEM_ZSIZE + 1];
216
217 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
218 #endif
219
220 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
221
222 /*
223  * time_uptime of the last malloc(9) failure (induced or real).
224  */
225 static time_t t_malloc_fail;
226
227 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
228 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
229     "Kernel malloc debugging options");
230 #endif
231
232 /*
233  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
234  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
235  */
236 #ifdef MALLOC_MAKE_FAILURES
237 static int malloc_failure_rate;
238 static int malloc_nowait_count;
239 static int malloc_failure_count;
240 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
241     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
242 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
243     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
244 #endif
245
246 static int
247 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
248 {
249         u_long size;
250
251         size = uma_size();
252         return (sysctl_handle_long(oidp, &size, 0, req));
253 }
254
255 static int
256 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
257 {
258         u_long size, limit;
259
260         /* The sysctl is unsigned, implement as a saturation value. */
261         size = uma_size();
262         limit = uma_limit();
263         if (size > limit)
264                 size = 0;
265         else
266                 size = limit - size;
267         return (sysctl_handle_long(oidp, &size, 0, req));
268 }
269
270 /*
271  * malloc(9) uma zone separation -- sub-page buffer overruns in one
272  * malloc type will affect only a subset of other malloc types.
273  */
274 #if MALLOC_DEBUG_MAXZONES > 1
275 static void
276 tunable_set_numzones(void)
277 {
278
279         TUNABLE_INT_FETCH("debug.malloc.numzones",
280             &numzones);
281
282         /* Sanity check the number of malloc uma zones. */
283         if (numzones <= 0)
284                 numzones = 1;
285         if (numzones > MALLOC_DEBUG_MAXZONES)
286                 numzones = MALLOC_DEBUG_MAXZONES;
287 }
288 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
289 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
290     &numzones, 0, "Number of malloc uma subzones");
291
292 /*
293  * Any number that changes regularly is an okay choice for the
294  * offset.  Build numbers are pretty good of you have them.
295  */
296 static u_int zone_offset = __FreeBSD_version;
297 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
298 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
299     &zone_offset, 0, "Separate malloc types by examining the "
300     "Nth character in the malloc type short description.");
301
302 static void
303 mtp_set_subzone(struct malloc_type *mtp)
304 {
305         struct malloc_type_internal *mtip;
306         const char *desc;
307         size_t len;
308         u_int val;
309
310         mtip = mtp->ks_handle;
311         desc = mtp->ks_shortdesc;
312         if (desc == NULL || (len = strlen(desc)) == 0)
313                 val = 0;
314         else
315                 val = desc[zone_offset % len];
316         mtip->mti_zone = (val % numzones);
317 }
318
319 static inline u_int
320 mtp_get_subzone(struct malloc_type *mtp)
321 {
322         struct malloc_type_internal *mtip;
323
324         mtip = mtp->ks_handle;
325
326         KASSERT(mtip->mti_zone < numzones,
327             ("mti_zone %u out of range %d",
328             mtip->mti_zone, numzones));
329         return (mtip->mti_zone);
330 }
331 #elif MALLOC_DEBUG_MAXZONES == 0
332 #error "MALLOC_DEBUG_MAXZONES must be positive."
333 #else
334 static void
335 mtp_set_subzone(struct malloc_type *mtp)
336 {
337         struct malloc_type_internal *mtip;
338
339         mtip = mtp->ks_handle;
340         mtip->mti_zone = 0;
341 }
342
343 static inline u_int
344 mtp_get_subzone(struct malloc_type *mtp)
345 {
346
347         return (0);
348 }
349 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
350
351 int
352 malloc_last_fail(void)
353 {
354
355         return (time_uptime - t_malloc_fail);
356 }
357
358 /*
359  * An allocation has succeeded -- update malloc type statistics for the
360  * amount of bucket size.  Occurs within a critical section so that the
361  * thread isn't preempted and doesn't migrate while updating per-PCU
362  * statistics.
363  */
364 static void
365 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
366     int zindx)
367 {
368         struct malloc_type_internal *mtip;
369         struct malloc_type_stats *mtsp;
370
371         critical_enter();
372         mtip = mtp->ks_handle;
373         mtsp = zpcpu_get(mtip->mti_stats);
374         if (size > 0) {
375                 mtsp->mts_memalloced += size;
376                 mtsp->mts_numallocs++;
377         }
378         if (zindx != -1)
379                 mtsp->mts_size |= 1 << zindx;
380
381 #ifdef KDTRACE_HOOKS
382         if (__predict_false(dtrace_malloc_enabled)) {
383                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
384                 if (probe_id != 0)
385                         (dtrace_malloc_probe)(probe_id,
386                             (uintptr_t) mtp, (uintptr_t) mtip,
387                             (uintptr_t) mtsp, size, zindx);
388         }
389 #endif
390
391         critical_exit();
392 }
393
394 void
395 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
396 {
397
398         if (size > 0)
399                 malloc_type_zone_allocated(mtp, size, -1);
400 }
401
402 /*
403  * A free operation has occurred -- update malloc type statistics for the
404  * amount of the bucket size.  Occurs within a critical section so that the
405  * thread isn't preempted and doesn't migrate while updating per-CPU
406  * statistics.
407  */
408 void
409 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
410 {
411         struct malloc_type_internal *mtip;
412         struct malloc_type_stats *mtsp;
413
414         critical_enter();
415         mtip = mtp->ks_handle;
416         mtsp = zpcpu_get(mtip->mti_stats);
417         mtsp->mts_memfreed += size;
418         mtsp->mts_numfrees++;
419
420 #ifdef KDTRACE_HOOKS
421         if (__predict_false(dtrace_malloc_enabled)) {
422                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
423                 if (probe_id != 0)
424                         (dtrace_malloc_probe)(probe_id,
425                             (uintptr_t) mtp, (uintptr_t) mtip,
426                             (uintptr_t) mtsp, size, 0);
427         }
428 #endif
429
430         critical_exit();
431 }
432
433 /*
434  *      contigmalloc:
435  *
436  *      Allocate a block of physically contiguous memory.
437  *
438  *      If M_NOWAIT is set, this routine will not block and return NULL if
439  *      the allocation fails.
440  */
441 void *
442 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
443     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
444     vm_paddr_t boundary)
445 {
446         void *ret;
447
448         ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
449             boundary, VM_MEMATTR_DEFAULT);
450         if (ret != NULL)
451                 malloc_type_allocated(type, round_page(size));
452         return (ret);
453 }
454
455 void *
456 contigmalloc_domain(unsigned long size, struct malloc_type *type,
457     int domain, int flags, vm_paddr_t low, vm_paddr_t high,
458     unsigned long alignment, vm_paddr_t boundary)
459 {
460         void *ret;
461
462         ret = (void *)kmem_alloc_contig_domain(domain, size, flags, low, high,
463             alignment, boundary, VM_MEMATTR_DEFAULT);
464         if (ret != NULL)
465                 malloc_type_allocated(type, round_page(size));
466         return (ret);
467 }
468
469 /*
470  *      contigfree:
471  *
472  *      Free a block of memory allocated by contigmalloc.
473  *
474  *      This routine may not block.
475  */
476 void
477 contigfree(void *addr, unsigned long size, struct malloc_type *type)
478 {
479
480         kmem_free((vm_offset_t)addr, size);
481         malloc_type_freed(type, round_page(size));
482 }
483
484 #ifdef MALLOC_DEBUG
485 static int
486 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
487     int flags)
488 {
489 #ifdef INVARIANTS
490         int indx;
491
492         KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
493         /*
494          * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
495          */
496         indx = flags & (M_WAITOK | M_NOWAIT);
497         if (indx != M_NOWAIT && indx != M_WAITOK) {
498                 static  struct timeval lasterr;
499                 static  int curerr, once;
500                 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
501                         printf("Bad malloc flags: %x\n", indx);
502                         kdb_backtrace();
503                         flags |= M_WAITOK;
504                         once++;
505                 }
506         }
507 #endif
508 #ifdef MALLOC_MAKE_FAILURES
509         if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
510                 atomic_add_int(&malloc_nowait_count, 1);
511                 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
512                         atomic_add_int(&malloc_failure_count, 1);
513                         t_malloc_fail = time_uptime;
514                         *vap = NULL;
515                         return (EJUSTRETURN);
516                 }
517         }
518 #endif
519         if (flags & M_WAITOK) {
520                 KASSERT(curthread->td_intr_nesting_level == 0,
521                    ("malloc(M_WAITOK) in interrupt context"));
522                 KASSERT(curthread->td_epochnest == 0,
523                         ("malloc(M_WAITOK) in epoch context"));         
524         }
525         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
526             ("malloc: called with spinlock or critical section held"));
527
528 #ifdef DEBUG_MEMGUARD
529         if (memguard_cmp_mtp(mtp, *sizep)) {
530                 *vap = memguard_alloc(*sizep, flags);
531                 if (*vap != NULL)
532                         return (EJUSTRETURN);
533                 /* This is unfortunate but should not be fatal. */
534         }
535 #endif
536
537 #ifdef DEBUG_REDZONE
538         *sizep = redzone_size_ntor(*sizep);
539 #endif
540
541         return (0);
542 }
543 #endif
544
545 /*
546  *      malloc:
547  *
548  *      Allocate a block of memory.
549  *
550  *      If M_NOWAIT is set, this routine will not block and return NULL if
551  *      the allocation fails.
552  */
553 void *
554 (malloc)(size_t size, struct malloc_type *mtp, int flags)
555 {
556         int indx;
557         caddr_t va;
558         uma_zone_t zone;
559 #if defined(DEBUG_REDZONE)
560         unsigned long osize = size;
561 #endif
562
563 #ifdef MALLOC_DEBUG
564         va = NULL;
565         if (malloc_dbg(&va, &size, mtp, flags) != 0)
566                 return (va);
567 #endif
568
569         if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
570                 if (size & KMEM_ZMASK)
571                         size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
572                 indx = kmemsize[size >> KMEM_ZSHIFT];
573                 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
574 #ifdef MALLOC_PROFILE
575                 krequests[size >> KMEM_ZSHIFT]++;
576 #endif
577                 va = uma_zalloc(zone, flags);
578                 if (va != NULL)
579                         size = zone->uz_size;
580                 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
581         } else {
582                 size = roundup(size, PAGE_SIZE);
583                 zone = NULL;
584                 va = uma_large_malloc(size, flags);
585                 malloc_type_allocated(mtp, va == NULL ? 0 : size);
586         }
587         if (flags & M_WAITOK)
588                 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
589         else if (va == NULL)
590                 t_malloc_fail = time_uptime;
591 #ifdef DEBUG_REDZONE
592         if (va != NULL)
593                 va = redzone_setup(va, osize);
594 #endif
595         return ((void *) va);
596 }
597
598 void *
599 malloc_domain(size_t size, struct malloc_type *mtp, int domain,
600     int flags)
601 {
602         int indx;
603         caddr_t va;
604         uma_zone_t zone;
605 #if defined(DEBUG_REDZONE)
606         unsigned long osize = size;
607 #endif
608
609 #ifdef MALLOC_DEBUG
610         va = NULL;
611         if (malloc_dbg(&va, &size, mtp, flags) != 0)
612                 return (va);
613 #endif
614         if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
615                 if (size & KMEM_ZMASK)
616                         size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
617                 indx = kmemsize[size >> KMEM_ZSHIFT];
618                 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
619 #ifdef MALLOC_PROFILE
620                 krequests[size >> KMEM_ZSHIFT]++;
621 #endif
622                 va = uma_zalloc_domain(zone, NULL, domain, flags);
623                 if (va != NULL)
624                         size = zone->uz_size;
625                 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
626         } else {
627                 size = roundup(size, PAGE_SIZE);
628                 zone = NULL;
629                 va = uma_large_malloc_domain(size, domain, flags);
630                 malloc_type_allocated(mtp, va == NULL ? 0 : size);
631         }
632         if (flags & M_WAITOK)
633                 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
634         else if (va == NULL)
635                 t_malloc_fail = time_uptime;
636 #ifdef DEBUG_REDZONE
637         if (va != NULL)
638                 va = redzone_setup(va, osize);
639 #endif
640         return ((void *) va);
641 }
642
643 void *
644 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
645 {
646
647         if (WOULD_OVERFLOW(nmemb, size))
648                 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
649
650         return (malloc(size * nmemb, type, flags));
651 }
652
653 #ifdef INVARIANTS
654 static void
655 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
656 {
657         struct malloc_type **mtpp = addr;
658
659         /*
660          * Cache a pointer to the malloc_type that most recently freed
661          * this memory here.  This way we know who is most likely to
662          * have stepped on it later.
663          *
664          * This code assumes that size is a multiple of 8 bytes for
665          * 64 bit machines
666          */
667         mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
668         mtpp += (size - sizeof(struct malloc_type *)) /
669             sizeof(struct malloc_type *);
670         *mtpp = mtp;
671 }
672 #endif
673
674 #ifdef MALLOC_DEBUG
675 static int
676 free_dbg(void **addrp, struct malloc_type *mtp)
677 {
678         void *addr;
679
680         addr = *addrp;
681         KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
682         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
683             ("free: called with spinlock or critical section held"));
684
685         /* free(NULL, ...) does nothing */
686         if (addr == NULL)
687                 return (EJUSTRETURN);
688
689 #ifdef DEBUG_MEMGUARD
690         if (is_memguard_addr(addr)) {
691                 memguard_free(addr);
692                 return (EJUSTRETURN);
693         }
694 #endif
695
696 #ifdef DEBUG_REDZONE
697         redzone_check(addr);
698         *addrp = redzone_addr_ntor(addr);
699 #endif
700
701         return (0);
702 }
703 #endif
704
705 /*
706  *      free:
707  *
708  *      Free a block of memory allocated by malloc.
709  *
710  *      This routine may not block.
711  */
712 void
713 free(void *addr, struct malloc_type *mtp)
714 {
715         uma_slab_t slab;
716         u_long size;
717
718 #ifdef MALLOC_DEBUG
719         if (free_dbg(&addr, mtp) != 0)
720                 return;
721 #endif
722         /* free(NULL, ...) does nothing */
723         if (addr == NULL)
724                 return;
725
726         slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
727         if (slab == NULL)
728                 panic("free: address %p(%p) has not been allocated.\n",
729                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
730
731         if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
732                 size = slab->us_keg->uk_size;
733 #ifdef INVARIANTS
734                 free_save_type(addr, mtp, size);
735 #endif
736                 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
737         } else {
738                 size = slab->us_size;
739                 uma_large_free(slab);
740         }
741         malloc_type_freed(mtp, size);
742 }
743
744 void
745 free_domain(void *addr, struct malloc_type *mtp)
746 {
747         uma_slab_t slab;
748         u_long size;
749
750 #ifdef MALLOC_DEBUG
751         if (free_dbg(&addr, mtp) != 0)
752                 return;
753 #endif
754
755         /* free(NULL, ...) does nothing */
756         if (addr == NULL)
757                 return;
758
759         slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
760         if (slab == NULL)
761                 panic("free_domain: address %p(%p) has not been allocated.\n",
762                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
763
764         if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
765                 size = slab->us_keg->uk_size;
766 #ifdef INVARIANTS
767                 free_save_type(addr, mtp, size);
768 #endif
769                 uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones),
770                     addr, slab);
771         } else {
772                 size = slab->us_size;
773                 uma_large_free(slab);
774         }
775         malloc_type_freed(mtp, size);
776 }
777
778 /*
779  *      realloc: change the size of a memory block
780  */
781 void *
782 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
783 {
784         uma_slab_t slab;
785         unsigned long alloc;
786         void *newaddr;
787
788         KASSERT(mtp->ks_magic == M_MAGIC,
789             ("realloc: bad malloc type magic"));
790         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
791             ("realloc: called with spinlock or critical section held"));
792
793         /* realloc(NULL, ...) is equivalent to malloc(...) */
794         if (addr == NULL)
795                 return (malloc(size, mtp, flags));
796
797         /*
798          * XXX: Should report free of old memory and alloc of new memory to
799          * per-CPU stats.
800          */
801
802 #ifdef DEBUG_MEMGUARD
803         if (is_memguard_addr(addr))
804                 return (memguard_realloc(addr, size, mtp, flags));
805 #endif
806
807 #ifdef DEBUG_REDZONE
808         slab = NULL;
809         alloc = redzone_get_size(addr);
810 #else
811         slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
812
813         /* Sanity check */
814         KASSERT(slab != NULL,
815             ("realloc: address %p out of range", (void *)addr));
816
817         /* Get the size of the original block */
818         if (!(slab->us_flags & UMA_SLAB_MALLOC))
819                 alloc = slab->us_keg->uk_size;
820         else
821                 alloc = slab->us_size;
822
823         /* Reuse the original block if appropriate */
824         if (size <= alloc
825             && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
826                 return (addr);
827 #endif /* !DEBUG_REDZONE */
828
829         /* Allocate a new, bigger (or smaller) block */
830         if ((newaddr = malloc(size, mtp, flags)) == NULL)
831                 return (NULL);
832
833         /* Copy over original contents */
834         bcopy(addr, newaddr, min(size, alloc));
835         free(addr, mtp);
836         return (newaddr);
837 }
838
839 /*
840  *      reallocf: same as realloc() but free memory on failure.
841  */
842 void *
843 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
844 {
845         void *mem;
846
847         if ((mem = realloc(addr, size, mtp, flags)) == NULL)
848                 free(addr, mtp);
849         return (mem);
850 }
851
852 #ifndef __sparc64__
853 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
854 #endif
855
856 /*
857  * Initialize the kernel memory (kmem) arena.
858  */
859 void
860 kmeminit(void)
861 {
862         u_long mem_size;
863         u_long tmp;
864
865 #ifdef VM_KMEM_SIZE
866         if (vm_kmem_size == 0)
867                 vm_kmem_size = VM_KMEM_SIZE;
868 #endif
869 #ifdef VM_KMEM_SIZE_MIN
870         if (vm_kmem_size_min == 0)
871                 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
872 #endif
873 #ifdef VM_KMEM_SIZE_MAX
874         if (vm_kmem_size_max == 0)
875                 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
876 #endif
877         /*
878          * Calculate the amount of kernel virtual address (KVA) space that is
879          * preallocated to the kmem arena.  In order to support a wide range
880          * of machines, it is a function of the physical memory size,
881          * specifically,
882          *
883          *      min(max(physical memory size / VM_KMEM_SIZE_SCALE,
884          *          VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
885          *
886          * Every architecture must define an integral value for
887          * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
888          * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
889          * ceiling on this preallocation, are optional.  Typically,
890          * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
891          * a given architecture.
892          */
893         mem_size = vm_cnt.v_page_count;
894         if (mem_size <= 32768) /* delphij XXX 128MB */
895                 kmem_zmax = PAGE_SIZE;
896
897         if (vm_kmem_size_scale < 1)
898                 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
899
900         /*
901          * Check if we should use defaults for the "vm_kmem_size"
902          * variable:
903          */
904         if (vm_kmem_size == 0) {
905                 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
906
907                 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
908                         vm_kmem_size = vm_kmem_size_min;
909                 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
910                         vm_kmem_size = vm_kmem_size_max;
911         }
912
913         /*
914          * The amount of KVA space that is preallocated to the
915          * kmem arena can be set statically at compile-time or manually
916          * through the kernel environment.  However, it is still limited to
917          * twice the physical memory size, which has been sufficient to handle
918          * the most severe cases of external fragmentation in the kmem arena. 
919          */
920         if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
921                 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
922
923         vm_kmem_size = round_page(vm_kmem_size);
924 #ifdef DEBUG_MEMGUARD
925         tmp = memguard_fudge(vm_kmem_size, kernel_map);
926 #else
927         tmp = vm_kmem_size;
928 #endif
929         uma_set_limit(tmp);
930
931 #ifdef DEBUG_MEMGUARD
932         /*
933          * Initialize MemGuard if support compiled in.  MemGuard is a
934          * replacement allocator used for detecting tamper-after-free
935          * scenarios as they occur.  It is only used for debugging.
936          */
937         memguard_init(kernel_arena);
938 #endif
939 }
940
941 /*
942  * Initialize the kernel memory allocator
943  */
944 /* ARGSUSED*/
945 static void
946 mallocinit(void *dummy)
947 {
948         int i;
949         uint8_t indx;
950
951         mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
952
953         kmeminit();
954
955         if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
956                 kmem_zmax = KMEM_ZMAX;
957
958         mt_stats_zone = uma_zcreate("mt_stats_zone",
959             sizeof(struct malloc_type_stats), NULL, NULL, NULL, NULL,
960             UMA_ALIGN_PTR, UMA_ZONE_PCPU);
961         mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
962 #ifdef INVARIANTS
963             mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
964 #else
965             NULL, NULL, NULL, NULL,
966 #endif
967             UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
968         for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
969                 int size = kmemzones[indx].kz_size;
970                 char *name = kmemzones[indx].kz_name;
971                 int subzone;
972
973                 for (subzone = 0; subzone < numzones; subzone++) {
974                         kmemzones[indx].kz_zone[subzone] =
975                             uma_zcreate(name, size,
976 #ifdef INVARIANTS
977                             mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
978 #else
979                             NULL, NULL, NULL, NULL,
980 #endif
981                             UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
982                 }                   
983                 for (;i <= size; i+= KMEM_ZBASE)
984                         kmemsize[i >> KMEM_ZSHIFT] = indx;
985
986         }
987 }
988 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
989
990 void
991 malloc_init(void *data)
992 {
993         struct malloc_type_internal *mtip;
994         struct malloc_type *mtp;
995
996         KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
997
998         mtp = data;
999         if (mtp->ks_magic != M_MAGIC)
1000                 panic("malloc_init: bad malloc type magic");
1001
1002         mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
1003         mtip->mti_stats = uma_zalloc_pcpu(mt_stats_zone, M_WAITOK | M_ZERO);
1004         mtp->ks_handle = mtip;
1005         mtp_set_subzone(mtp);
1006
1007         mtx_lock(&malloc_mtx);
1008         mtp->ks_next = kmemstatistics;
1009         kmemstatistics = mtp;
1010         kmemcount++;
1011         mtx_unlock(&malloc_mtx);
1012 }
1013
1014 void
1015 malloc_uninit(void *data)
1016 {
1017         struct malloc_type_internal *mtip;
1018         struct malloc_type_stats *mtsp;
1019         struct malloc_type *mtp, *temp;
1020         uma_slab_t slab;
1021         long temp_allocs, temp_bytes;
1022         int i;
1023
1024         mtp = data;
1025         KASSERT(mtp->ks_magic == M_MAGIC,
1026             ("malloc_uninit: bad malloc type magic"));
1027         KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1028
1029         mtx_lock(&malloc_mtx);
1030         mtip = mtp->ks_handle;
1031         mtp->ks_handle = NULL;
1032         if (mtp != kmemstatistics) {
1033                 for (temp = kmemstatistics; temp != NULL;
1034                     temp = temp->ks_next) {
1035                         if (temp->ks_next == mtp) {
1036                                 temp->ks_next = mtp->ks_next;
1037                                 break;
1038                         }
1039                 }
1040                 KASSERT(temp,
1041                     ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1042         } else
1043                 kmemstatistics = mtp->ks_next;
1044         kmemcount--;
1045         mtx_unlock(&malloc_mtx);
1046
1047         /*
1048          * Look for memory leaks.
1049          */
1050         temp_allocs = temp_bytes = 0;
1051         for (i = 0; i <= mp_maxid; i++) {
1052                 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1053                 temp_allocs += mtsp->mts_numallocs;
1054                 temp_allocs -= mtsp->mts_numfrees;
1055                 temp_bytes += mtsp->mts_memalloced;
1056                 temp_bytes -= mtsp->mts_memfreed;
1057         }
1058         if (temp_allocs > 0 || temp_bytes > 0) {
1059                 printf("Warning: memory type %s leaked memory on destroy "
1060                     "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1061                     temp_allocs, temp_bytes);
1062         }
1063
1064         slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
1065         uma_zfree_pcpu(mt_stats_zone, mtip->mti_stats);
1066         uma_zfree_arg(mt_zone, mtip, slab);
1067 }
1068
1069 struct malloc_type *
1070 malloc_desc2type(const char *desc)
1071 {
1072         struct malloc_type *mtp;
1073
1074         mtx_assert(&malloc_mtx, MA_OWNED);
1075         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1076                 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1077                         return (mtp);
1078         }
1079         return (NULL);
1080 }
1081
1082 static int
1083 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1084 {
1085         struct malloc_type_stream_header mtsh;
1086         struct malloc_type_internal *mtip;
1087         struct malloc_type_stats *mtsp, zeromts;
1088         struct malloc_type_header mth;
1089         struct malloc_type *mtp;
1090         int error, i;
1091         struct sbuf sbuf;
1092
1093         error = sysctl_wire_old_buffer(req, 0);
1094         if (error != 0)
1095                 return (error);
1096         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1097         sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1098         mtx_lock(&malloc_mtx);
1099
1100         bzero(&zeromts, sizeof(zeromts));
1101
1102         /*
1103          * Insert stream header.
1104          */
1105         bzero(&mtsh, sizeof(mtsh));
1106         mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1107         mtsh.mtsh_maxcpus = MAXCPU;
1108         mtsh.mtsh_count = kmemcount;
1109         (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1110
1111         /*
1112          * Insert alternating sequence of type headers and type statistics.
1113          */
1114         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1115                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1116
1117                 /*
1118                  * Insert type header.
1119                  */
1120                 bzero(&mth, sizeof(mth));
1121                 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1122                 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1123
1124                 /*
1125                  * Insert type statistics for each CPU.
1126                  */
1127                 for (i = 0; i <= mp_maxid; i++) {
1128                         mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1129                         (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1130                 }
1131                 /*
1132                  * Fill in the missing CPUs.
1133                  */
1134                 for (; i < MAXCPU; i++) {
1135                         (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1136                 }
1137
1138         }
1139         mtx_unlock(&malloc_mtx);
1140         error = sbuf_finish(&sbuf);
1141         sbuf_delete(&sbuf);
1142         return (error);
1143 }
1144
1145 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1146     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1147     "Return malloc types");
1148
1149 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1150     "Count of kernel malloc types");
1151
1152 void
1153 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1154 {
1155         struct malloc_type *mtp, **bufmtp;
1156         int count, i;
1157         size_t buflen;
1158
1159         mtx_lock(&malloc_mtx);
1160 restart:
1161         mtx_assert(&malloc_mtx, MA_OWNED);
1162         count = kmemcount;
1163         mtx_unlock(&malloc_mtx);
1164
1165         buflen = sizeof(struct malloc_type *) * count;
1166         bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1167
1168         mtx_lock(&malloc_mtx);
1169
1170         if (count < kmemcount) {
1171                 free(bufmtp, M_TEMP);
1172                 goto restart;
1173         }
1174
1175         for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1176                 bufmtp[i] = mtp;
1177
1178         mtx_unlock(&malloc_mtx);
1179
1180         for (i = 0; i < count; i++)
1181                 (func)(bufmtp[i], arg);
1182
1183         free(bufmtp, M_TEMP);
1184 }
1185
1186 #ifdef DDB
1187 DB_SHOW_COMMAND(malloc, db_show_malloc)
1188 {
1189         struct malloc_type_internal *mtip;
1190         struct malloc_type_internal *mtsp;
1191         struct malloc_type *mtp;
1192         uint64_t allocs, frees;
1193         uint64_t alloced, freed;
1194         int i;
1195
1196         db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
1197             "Requests");
1198         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1199                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1200                 allocs = 0;
1201                 frees = 0;
1202                 alloced = 0;
1203                 freed = 0;
1204                 for (i = 0; i <= mp_maxid; i++) {
1205                         mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1206                         allocs += mtip->mti_stats[i].mts_numallocs;
1207                         frees += mtip->mti_stats[i].mts_numfrees;
1208                         alloced += mtip->mti_stats[i].mts_memalloced;
1209                         freed += mtip->mti_stats[i].mts_memfreed;
1210                 }
1211                 db_printf("%18s %12ju %12juK %12ju\n",
1212                     mtp->ks_shortdesc, allocs - frees,
1213                     (alloced - freed + 1023) / 1024, allocs);
1214                 if (db_pager_quit)
1215                         break;
1216         }
1217 }
1218
1219 #if MALLOC_DEBUG_MAXZONES > 1
1220 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1221 {
1222         struct malloc_type_internal *mtip;
1223         struct malloc_type *mtp;
1224         u_int subzone;
1225
1226         if (!have_addr) {
1227                 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1228                 return;
1229         }
1230         mtp = (void *)addr;
1231         if (mtp->ks_magic != M_MAGIC) {
1232                 db_printf("Magic %lx does not match expected %x\n",
1233                     mtp->ks_magic, M_MAGIC);
1234                 return;
1235         }
1236
1237         mtip = mtp->ks_handle;
1238         subzone = mtip->mti_zone;
1239
1240         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1241                 mtip = mtp->ks_handle;
1242                 if (mtip->mti_zone != subzone)
1243                         continue;
1244                 db_printf("%s\n", mtp->ks_shortdesc);
1245                 if (db_pager_quit)
1246                         break;
1247         }
1248 }
1249 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1250 #endif /* DDB */
1251
1252 #ifdef MALLOC_PROFILE
1253
1254 static int
1255 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1256 {
1257         struct sbuf sbuf;
1258         uint64_t count;
1259         uint64_t waste;
1260         uint64_t mem;
1261         int error;
1262         int rsize;
1263         int size;
1264         int i;
1265
1266         waste = 0;
1267         mem = 0;
1268
1269         error = sysctl_wire_old_buffer(req, 0);
1270         if (error != 0)
1271                 return (error);
1272         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1273         sbuf_printf(&sbuf, 
1274             "\n  Size                    Requests  Real Size\n");
1275         for (i = 0; i < KMEM_ZSIZE; i++) {
1276                 size = i << KMEM_ZSHIFT;
1277                 rsize = kmemzones[kmemsize[i]].kz_size;
1278                 count = (long long unsigned)krequests[i];
1279
1280                 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1281                     (unsigned long long)count, rsize);
1282
1283                 if ((rsize * count) > (size * count))
1284                         waste += (rsize * count) - (size * count);
1285                 mem += (rsize * count);
1286         }
1287         sbuf_printf(&sbuf,
1288             "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1289             (unsigned long long)mem, (unsigned long long)waste);
1290         error = sbuf_finish(&sbuf);
1291         sbuf_delete(&sbuf);
1292         return (error);
1293 }
1294
1295 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1296     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1297 #endif /* MALLOC_PROFILE */