]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_malloc.c
malloc: retire malloc_last_fail
[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/queue.h>
64 #include <sys/sbuf.h>
65 #include <sys/smp.h>
66 #include <sys/sysctl.h>
67 #include <sys/time.h>
68 #include <sys/vmem.h>
69 #ifdef EPOCH_TRACE
70 #include <sys/epoch.h>
71 #endif
72
73 #include <vm/vm.h>
74 #include <vm/pmap.h>
75 #include <vm/vm_domainset.h>
76 #include <vm/vm_pageout.h>
77 #include <vm/vm_param.h>
78 #include <vm/vm_kern.h>
79 #include <vm/vm_extern.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_phys.h>
83 #include <vm/vm_pagequeue.h>
84 #include <vm/uma.h>
85 #include <vm/uma_int.h>
86 #include <vm/uma_dbg.h>
87
88 #ifdef DEBUG_MEMGUARD
89 #include <vm/memguard.h>
90 #endif
91 #ifdef DEBUG_REDZONE
92 #include <vm/redzone.h>
93 #endif
94
95 #if defined(INVARIANTS) && defined(__i386__)
96 #include <machine/cpu.h>
97 #endif
98
99 #include <ddb/ddb.h>
100
101 #ifdef KDTRACE_HOOKS
102 #include <sys/dtrace_bsd.h>
103
104 bool    __read_frequently                       dtrace_malloc_enabled;
105 dtrace_malloc_probe_func_t __read_mostly        dtrace_malloc_probe;
106 #endif
107
108 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) ||             \
109     defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
110 #define MALLOC_DEBUG    1
111 #endif
112
113 /*
114  * When realloc() is called, if the new size is sufficiently smaller than
115  * the old size, realloc() will allocate a new, smaller block to avoid
116  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
117  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
118  */
119 #ifndef REALLOC_FRACTION
120 #define REALLOC_FRACTION        1       /* new block if <= half the size */
121 #endif
122
123 /*
124  * Centrally define some common malloc types.
125  */
126 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
127 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
128 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
129
130 static struct malloc_type *kmemstatistics;
131 static int kmemcount;
132
133 #define KMEM_ZSHIFT     4
134 #define KMEM_ZBASE      16
135 #define KMEM_ZMASK      (KMEM_ZBASE - 1)
136
137 #define KMEM_ZMAX       65536
138 #define KMEM_ZSIZE      (KMEM_ZMAX >> KMEM_ZSHIFT)
139 static uint8_t kmemsize[KMEM_ZSIZE + 1];
140
141 #ifndef MALLOC_DEBUG_MAXZONES
142 #define MALLOC_DEBUG_MAXZONES   1
143 #endif
144 static int numzones = MALLOC_DEBUG_MAXZONES;
145
146 /*
147  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
148  * of various sizes.
149  *
150  * Warning: the layout of the struct is duplicated in libmemstat for KVM support.
151  *
152  * XXX: The comment here used to read "These won't be powers of two for
153  * long."  It's possible that a significant amount of wasted memory could be
154  * recovered by tuning the sizes of these buckets.
155  */
156 struct {
157         int kz_size;
158         const char *kz_name;
159         uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
160 } kmemzones[] = {
161         {16, "malloc-16", },
162         {32, "malloc-32", },
163         {64, "malloc-64", },
164         {128, "malloc-128", },
165         {256, "malloc-256", },
166         {384, "malloc-384", },
167         {512, "malloc-512", },
168         {1024, "malloc-1024", },
169         {2048, "malloc-2048", },
170         {4096, "malloc-4096", },
171         {8192, "malloc-8192", },
172         {16384, "malloc-16384", },
173         {32768, "malloc-32768", },
174         {65536, "malloc-65536", },
175         {0, NULL},
176 };
177
178 u_long vm_kmem_size;
179 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
180     "Size of kernel memory");
181
182 static u_long kmem_zmax = KMEM_ZMAX;
183 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
184     "Maximum allocation size that malloc(9) would use UMA as backend");
185
186 static u_long vm_kmem_size_min;
187 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
188     "Minimum size of kernel memory");
189
190 static u_long vm_kmem_size_max;
191 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
192     "Maximum size of kernel memory");
193
194 static u_int vm_kmem_size_scale;
195 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
196     "Scale factor for kernel memory size");
197
198 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
199 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
200     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
201     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
202
203 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
204 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
205     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
206     sysctl_kmem_map_free, "LU", "Free space in kmem");
207
208 static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
209     "Malloc information");
210
211 static u_int vm_malloc_zone_count = nitems(kmemzones);
212 SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
213     CTLFLAG_RD, &vm_malloc_zone_count, 0,
214     "Number of malloc zones");
215
216 static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
217 SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
218     CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
219     sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
220
221 /*
222  * The malloc_mtx protects the kmemstatistics linked list.
223  */
224 struct mtx malloc_mtx;
225
226 #ifdef MALLOC_PROFILE
227 uint64_t krequests[KMEM_ZSIZE + 1];
228
229 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
230 #endif
231
232 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
233
234 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
235 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
236     "Kernel malloc debugging options");
237 #endif
238
239 /*
240  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
241  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
242  */
243 #ifdef MALLOC_MAKE_FAILURES
244 static int malloc_failure_rate;
245 static int malloc_nowait_count;
246 static int malloc_failure_count;
247 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
248     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
249 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
250     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
251 #endif
252
253 static int
254 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
255 {
256         u_long size;
257
258         size = uma_size();
259         return (sysctl_handle_long(oidp, &size, 0, req));
260 }
261
262 static int
263 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
264 {
265         u_long size, limit;
266
267         /* The sysctl is unsigned, implement as a saturation value. */
268         size = uma_size();
269         limit = uma_limit();
270         if (size > limit)
271                 size = 0;
272         else
273                 size = limit - size;
274         return (sysctl_handle_long(oidp, &size, 0, req));
275 }
276
277 static int
278 sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
279 {
280         int sizes[nitems(kmemzones)];
281         int i;
282
283         for (i = 0; i < nitems(kmemzones); i++) {
284                 sizes[i] = kmemzones[i].kz_size;
285         }
286
287         return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
288 }
289
290 /*
291  * malloc(9) uma zone separation -- sub-page buffer overruns in one
292  * malloc type will affect only a subset of other malloc types.
293  */
294 #if MALLOC_DEBUG_MAXZONES > 1
295 static void
296 tunable_set_numzones(void)
297 {
298
299         TUNABLE_INT_FETCH("debug.malloc.numzones",
300             &numzones);
301
302         /* Sanity check the number of malloc uma zones. */
303         if (numzones <= 0)
304                 numzones = 1;
305         if (numzones > MALLOC_DEBUG_MAXZONES)
306                 numzones = MALLOC_DEBUG_MAXZONES;
307 }
308 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
309 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
310     &numzones, 0, "Number of malloc uma subzones");
311
312 /*
313  * Any number that changes regularly is an okay choice for the
314  * offset.  Build numbers are pretty good of you have them.
315  */
316 static u_int zone_offset = __FreeBSD_version;
317 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
318 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
319     &zone_offset, 0, "Separate malloc types by examining the "
320     "Nth character in the malloc type short description.");
321
322 static void
323 mtp_set_subzone(struct malloc_type *mtp)
324 {
325         struct malloc_type_internal *mtip;
326         const char *desc;
327         size_t len;
328         u_int val;
329
330         mtip = &mtp->ks_mti;
331         desc = mtp->ks_shortdesc;
332         if (desc == NULL || (len = strlen(desc)) == 0)
333                 val = 0;
334         else
335                 val = desc[zone_offset % len];
336         mtip->mti_zone = (val % numzones);
337 }
338
339 static inline u_int
340 mtp_get_subzone(struct malloc_type *mtp)
341 {
342         struct malloc_type_internal *mtip;
343
344         mtip = &mtp->ks_mti;
345
346         KASSERT(mtip->mti_zone < numzones,
347             ("mti_zone %u out of range %d",
348             mtip->mti_zone, numzones));
349         return (mtip->mti_zone);
350 }
351 #elif MALLOC_DEBUG_MAXZONES == 0
352 #error "MALLOC_DEBUG_MAXZONES must be positive."
353 #else
354 static void
355 mtp_set_subzone(struct malloc_type *mtp)
356 {
357         struct malloc_type_internal *mtip;
358
359         mtip = &mtp->ks_mti;
360         mtip->mti_zone = 0;
361 }
362
363 static inline u_int
364 mtp_get_subzone(struct malloc_type *mtp)
365 {
366
367         return (0);
368 }
369 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
370
371 /*
372  * An allocation has succeeded -- update malloc type statistics for the
373  * amount of bucket size.  Occurs within a critical section so that the
374  * thread isn't preempted and doesn't migrate while updating per-PCU
375  * statistics.
376  */
377 static void
378 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
379     int zindx)
380 {
381         struct malloc_type_internal *mtip;
382         struct malloc_type_stats *mtsp;
383
384         critical_enter();
385         mtip = &mtp->ks_mti;
386         mtsp = zpcpu_get(mtip->mti_stats);
387         if (size > 0) {
388                 mtsp->mts_memalloced += size;
389                 mtsp->mts_numallocs++;
390         }
391         if (zindx != -1)
392                 mtsp->mts_size |= 1 << zindx;
393
394 #ifdef KDTRACE_HOOKS
395         if (__predict_false(dtrace_malloc_enabled)) {
396                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
397                 if (probe_id != 0)
398                         (dtrace_malloc_probe)(probe_id,
399                             (uintptr_t) mtp, (uintptr_t) mtip,
400                             (uintptr_t) mtsp, size, zindx);
401         }
402 #endif
403
404         critical_exit();
405 }
406
407 void
408 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
409 {
410
411         if (size > 0)
412                 malloc_type_zone_allocated(mtp, size, -1);
413 }
414
415 /*
416  * A free operation has occurred -- update malloc type statistics for the
417  * amount of the bucket size.  Occurs within a critical section so that the
418  * thread isn't preempted and doesn't migrate while updating per-CPU
419  * statistics.
420  */
421 void
422 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
423 {
424         struct malloc_type_internal *mtip;
425         struct malloc_type_stats *mtsp;
426
427         critical_enter();
428         mtip = &mtp->ks_mti;
429         mtsp = zpcpu_get(mtip->mti_stats);
430         mtsp->mts_memfreed += size;
431         mtsp->mts_numfrees++;
432
433 #ifdef KDTRACE_HOOKS
434         if (__predict_false(dtrace_malloc_enabled)) {
435                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
436                 if (probe_id != 0)
437                         (dtrace_malloc_probe)(probe_id,
438                             (uintptr_t) mtp, (uintptr_t) mtip,
439                             (uintptr_t) mtsp, size, 0);
440         }
441 #endif
442
443         critical_exit();
444 }
445
446 /*
447  *      contigmalloc:
448  *
449  *      Allocate a block of physically contiguous memory.
450  *
451  *      If M_NOWAIT is set, this routine will not block and return NULL if
452  *      the allocation fails.
453  */
454 void *
455 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
456     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
457     vm_paddr_t boundary)
458 {
459         void *ret;
460
461         ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
462             boundary, VM_MEMATTR_DEFAULT);
463         if (ret != NULL)
464                 malloc_type_allocated(type, round_page(size));
465         return (ret);
466 }
467
468 void *
469 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
470     struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
471     unsigned long alignment, vm_paddr_t boundary)
472 {
473         void *ret;
474
475         ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
476             alignment, boundary, VM_MEMATTR_DEFAULT);
477         if (ret != NULL)
478                 malloc_type_allocated(type, round_page(size));
479         return (ret);
480 }
481
482 /*
483  *      contigfree:
484  *
485  *      Free a block of memory allocated by contigmalloc.
486  *
487  *      This routine may not block.
488  */
489 void
490 contigfree(void *addr, unsigned long size, struct malloc_type *type)
491 {
492
493         kmem_free((vm_offset_t)addr, size);
494         malloc_type_freed(type, round_page(size));
495 }
496
497 #ifdef MALLOC_DEBUG
498 static int
499 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
500     int flags)
501 {
502 #ifdef INVARIANTS
503         int indx;
504
505         KASSERT(mtp->ks_version == M_VERSION, ("malloc: bad malloc type version"));
506         /*
507          * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
508          */
509         indx = flags & (M_WAITOK | M_NOWAIT);
510         if (indx != M_NOWAIT && indx != M_WAITOK) {
511                 static  struct timeval lasterr;
512                 static  int curerr, once;
513                 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
514                         printf("Bad malloc flags: %x\n", indx);
515                         kdb_backtrace();
516                         flags |= M_WAITOK;
517                         once++;
518                 }
519         }
520 #endif
521 #ifdef MALLOC_MAKE_FAILURES
522         if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
523                 atomic_add_int(&malloc_nowait_count, 1);
524                 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
525                         atomic_add_int(&malloc_failure_count, 1);
526                         *vap = NULL;
527                         return (EJUSTRETURN);
528                 }
529         }
530 #endif
531         if (flags & M_WAITOK) {
532                 KASSERT(curthread->td_intr_nesting_level == 0,
533                    ("malloc(M_WAITOK) in interrupt context"));
534                 if (__predict_false(!THREAD_CAN_SLEEP())) {
535 #ifdef EPOCH_TRACE
536                         epoch_trace_list(curthread);
537 #endif
538                         KASSERT(1, 
539                             ("malloc(M_WAITOK) with sleeping prohibited"));
540                 }
541         }
542         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
543             ("malloc: called with spinlock or critical section held"));
544
545 #ifdef DEBUG_MEMGUARD
546         if (memguard_cmp_mtp(mtp, *sizep)) {
547                 *vap = memguard_alloc(*sizep, flags);
548                 if (*vap != NULL)
549                         return (EJUSTRETURN);
550                 /* This is unfortunate but should not be fatal. */
551         }
552 #endif
553
554 #ifdef DEBUG_REDZONE
555         *sizep = redzone_size_ntor(*sizep);
556 #endif
557
558         return (0);
559 }
560 #endif
561
562 /*
563  * Handle large allocations and frees by using kmem_malloc directly.
564  */
565 static inline bool
566 malloc_large_slab(uma_slab_t slab)
567 {
568         uintptr_t va;
569
570         va = (uintptr_t)slab;
571         return ((va & 1) != 0);
572 }
573
574 static inline size_t
575 malloc_large_size(uma_slab_t slab)
576 {
577         uintptr_t va;
578
579         va = (uintptr_t)slab;
580         return (va >> 1);
581 }
582
583 static caddr_t
584 malloc_large(size_t *size, struct domainset *policy, int flags)
585 {
586         vm_offset_t va;
587         size_t sz;
588
589         sz = roundup(*size, PAGE_SIZE);
590         va = kmem_malloc_domainset(policy, sz, flags);
591         if (va != 0) {
592                 /* The low bit is unused for slab pointers. */
593                 vsetzoneslab(va, NULL, (void *)((sz << 1) | 1));
594                 uma_total_inc(sz);
595                 *size = sz;
596         }
597         return ((caddr_t)va);
598 }
599
600 static void
601 free_large(void *addr, size_t size)
602 {
603
604         kmem_free((vm_offset_t)addr, size);
605         uma_total_dec(size);
606 }
607
608 /*
609  *      malloc:
610  *
611  *      Allocate a block of memory.
612  *
613  *      If M_NOWAIT is set, this routine will not block and return NULL if
614  *      the allocation fails.
615  */
616 void *
617 (malloc)(size_t size, struct malloc_type *mtp, int flags)
618 {
619         int indx;
620         caddr_t va;
621         uma_zone_t zone;
622 #if defined(DEBUG_REDZONE)
623         unsigned long osize = size;
624 #endif
625
626         MPASS((flags & M_EXEC) == 0);
627 #ifdef MALLOC_DEBUG
628         va = NULL;
629         if (malloc_dbg(&va, &size, mtp, flags) != 0)
630                 return (va);
631 #endif
632
633         if (size <= kmem_zmax) {
634                 if (size & KMEM_ZMASK)
635                         size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
636                 indx = kmemsize[size >> KMEM_ZSHIFT];
637                 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
638 #ifdef MALLOC_PROFILE
639                 krequests[size >> KMEM_ZSHIFT]++;
640 #endif
641                 va = uma_zalloc(zone, flags);
642                 if (va != NULL)
643                         size = zone->uz_size;
644                 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
645         } else {
646                 va = malloc_large(&size, DOMAINSET_RR(), flags);
647                 malloc_type_allocated(mtp, va == NULL ? 0 : size);
648         }
649         if (__predict_false(va == NULL)) {
650                 KASSERT((flags & M_WAITOK) == 0,
651                     ("malloc(M_WAITOK) returned NULL"));
652         }
653 #ifdef DEBUG_REDZONE
654         if (va != NULL)
655                 va = redzone_setup(va, osize);
656 #endif
657         return ((void *) va);
658 }
659
660 static void *
661 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
662     int flags)
663 {
664         uma_zone_t zone;
665         caddr_t va;
666         size_t size;
667         int indx;
668
669         size = *sizep;
670         KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
671             ("malloc_domain: Called with bad flag / size combination."));
672         if (size & KMEM_ZMASK)
673                 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
674         indx = kmemsize[size >> KMEM_ZSHIFT];
675         zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
676 #ifdef MALLOC_PROFILE
677         krequests[size >> KMEM_ZSHIFT]++;
678 #endif
679         va = uma_zalloc_domain(zone, NULL, domain, flags);
680         if (va != NULL)
681                 *sizep = zone->uz_size;
682         *indxp = indx;
683         return ((void *)va);
684 }
685
686 void *
687 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
688     int flags)
689 {
690         struct vm_domainset_iter di;
691         caddr_t va;
692         int domain;
693         int indx;
694
695 #if defined(DEBUG_REDZONE)
696         unsigned long osize = size;
697 #endif
698         MPASS((flags & M_EXEC) == 0);
699 #ifdef MALLOC_DEBUG
700         va = NULL;
701         if (malloc_dbg(&va, &size, mtp, flags) != 0)
702                 return (va);
703 #endif
704         if (size <= kmem_zmax) {
705                 vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
706                 do {
707                         va = malloc_domain(&size, &indx, mtp, domain, flags);
708                 } while (va == NULL &&
709                     vm_domainset_iter_policy(&di, &domain) == 0);
710                 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
711         } else {
712                 /* Policy is handled by kmem. */
713                 va = malloc_large(&size, ds, flags);
714                 malloc_type_allocated(mtp, va == NULL ? 0 : size);
715         }
716         if (__predict_false(va == NULL)) {
717                 KASSERT((flags & M_WAITOK) == 0,
718                     ("malloc(M_WAITOK) returned NULL"));
719         }
720 #ifdef DEBUG_REDZONE
721         if (va != NULL)
722                 va = redzone_setup(va, osize);
723 #endif
724         return (va);
725 }
726
727 /*
728  * Allocate an executable area.
729  */
730 void *
731 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
732 {
733         caddr_t va;
734 #if defined(DEBUG_REDZONE)
735         unsigned long osize = size;
736 #endif
737
738         flags |= M_EXEC;
739 #ifdef MALLOC_DEBUG
740         va = NULL;
741         if (malloc_dbg(&va, &size, mtp, flags) != 0)
742                 return (va);
743 #endif
744         va = malloc_large(&size, DOMAINSET_RR(), flags);
745         malloc_type_allocated(mtp, va == NULL ? 0 : size);
746         if (__predict_false(va == NULL)) {
747                 KASSERT((flags & M_WAITOK) == 0,
748                     ("malloc(M_WAITOK) returned NULL"));
749         }
750 #ifdef DEBUG_REDZONE
751         if (va != NULL)
752                 va = redzone_setup(va, osize);
753 #endif
754         return ((void *) va);
755 }
756
757 void *
758 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
759     int flags)
760 {
761         caddr_t va;
762 #if defined(DEBUG_REDZONE)
763         unsigned long osize = size;
764 #endif
765
766         flags |= M_EXEC;
767 #ifdef MALLOC_DEBUG
768         va = NULL;
769         if (malloc_dbg(&va, &size, mtp, flags) != 0)
770                 return (va);
771 #endif
772         /* Policy is handled by kmem. */
773         va = malloc_large(&size, ds, flags);
774         malloc_type_allocated(mtp, va == NULL ? 0 : size);
775         if (__predict_false(va == NULL)) {
776                 KASSERT((flags & M_WAITOK) == 0,
777                     ("malloc(M_WAITOK) returned NULL"));
778         }
779 #ifdef DEBUG_REDZONE
780         if (va != NULL)
781                 va = redzone_setup(va, osize);
782 #endif
783         return (va);
784 }
785
786 void *
787 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
788 {
789
790         if (WOULD_OVERFLOW(nmemb, size))
791                 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
792
793         return (malloc(size * nmemb, type, flags));
794 }
795
796 #ifdef INVARIANTS
797 static void
798 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
799 {
800         struct malloc_type **mtpp = addr;
801
802         /*
803          * Cache a pointer to the malloc_type that most recently freed
804          * this memory here.  This way we know who is most likely to
805          * have stepped on it later.
806          *
807          * This code assumes that size is a multiple of 8 bytes for
808          * 64 bit machines
809          */
810         mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
811         mtpp += (size - sizeof(struct malloc_type *)) /
812             sizeof(struct malloc_type *);
813         *mtpp = mtp;
814 }
815 #endif
816
817 #ifdef MALLOC_DEBUG
818 static int
819 free_dbg(void **addrp, struct malloc_type *mtp)
820 {
821         void *addr;
822
823         addr = *addrp;
824         KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
825         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
826             ("free: called with spinlock or critical section held"));
827
828         /* free(NULL, ...) does nothing */
829         if (addr == NULL)
830                 return (EJUSTRETURN);
831
832 #ifdef DEBUG_MEMGUARD
833         if (is_memguard_addr(addr)) {
834                 memguard_free(addr);
835                 return (EJUSTRETURN);
836         }
837 #endif
838
839 #ifdef DEBUG_REDZONE
840         redzone_check(addr);
841         *addrp = redzone_addr_ntor(addr);
842 #endif
843
844         return (0);
845 }
846 #endif
847
848 /*
849  *      free:
850  *
851  *      Free a block of memory allocated by malloc.
852  *
853  *      This routine may not block.
854  */
855 void
856 free(void *addr, struct malloc_type *mtp)
857 {
858         uma_zone_t zone;
859         uma_slab_t slab;
860         u_long size;
861
862 #ifdef MALLOC_DEBUG
863         if (free_dbg(&addr, mtp) != 0)
864                 return;
865 #endif
866         /* free(NULL, ...) does nothing */
867         if (addr == NULL)
868                 return;
869
870         vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
871         if (slab == NULL)
872                 panic("free: address %p(%p) has not been allocated.\n",
873                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
874
875         if (__predict_true(!malloc_large_slab(slab))) {
876                 size = zone->uz_size;
877 #ifdef INVARIANTS
878                 free_save_type(addr, mtp, size);
879 #endif
880                 uma_zfree_arg(zone, addr, slab);
881         } else {
882                 size = malloc_large_size(slab);
883                 free_large(addr, size);
884         }
885         malloc_type_freed(mtp, size);
886 }
887
888 /*
889  *      zfree:
890  *
891  *      Zero then free a block of memory allocated by malloc.
892  *
893  *      This routine may not block.
894  */
895 void
896 zfree(void *addr, struct malloc_type *mtp)
897 {
898         uma_zone_t zone;
899         uma_slab_t slab;
900         u_long size;
901
902 #ifdef MALLOC_DEBUG
903         if (free_dbg(&addr, mtp) != 0)
904                 return;
905 #endif
906         /* free(NULL, ...) does nothing */
907         if (addr == NULL)
908                 return;
909
910         vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
911         if (slab == NULL)
912                 panic("free: address %p(%p) has not been allocated.\n",
913                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
914
915         if (__predict_true(!malloc_large_slab(slab))) {
916                 size = zone->uz_size;
917 #ifdef INVARIANTS
918                 free_save_type(addr, mtp, size);
919 #endif
920                 explicit_bzero(addr, size);
921                 uma_zfree_arg(zone, addr, slab);
922         } else {
923                 size = malloc_large_size(slab);
924                 explicit_bzero(addr, size);
925                 free_large(addr, size);
926         }
927         malloc_type_freed(mtp, size);
928 }
929
930 /*
931  *      realloc: change the size of a memory block
932  */
933 void *
934 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
935 {
936         uma_zone_t zone;
937         uma_slab_t slab;
938         unsigned long alloc;
939         void *newaddr;
940
941         KASSERT(mtp->ks_version == M_VERSION,
942             ("realloc: bad malloc type version"));
943         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
944             ("realloc: called with spinlock or critical section held"));
945
946         /* realloc(NULL, ...) is equivalent to malloc(...) */
947         if (addr == NULL)
948                 return (malloc(size, mtp, flags));
949
950         /*
951          * XXX: Should report free of old memory and alloc of new memory to
952          * per-CPU stats.
953          */
954
955 #ifdef DEBUG_MEMGUARD
956         if (is_memguard_addr(addr))
957                 return (memguard_realloc(addr, size, mtp, flags));
958 #endif
959
960 #ifdef DEBUG_REDZONE
961         slab = NULL;
962         zone = NULL;
963         alloc = redzone_get_size(addr);
964 #else
965         vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
966
967         /* Sanity check */
968         KASSERT(slab != NULL,
969             ("realloc: address %p out of range", (void *)addr));
970
971         /* Get the size of the original block */
972         if (!malloc_large_slab(slab))
973                 alloc = zone->uz_size;
974         else
975                 alloc = malloc_large_size(slab);
976
977         /* Reuse the original block if appropriate */
978         if (size <= alloc
979             && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
980                 return (addr);
981 #endif /* !DEBUG_REDZONE */
982
983         /* Allocate a new, bigger (or smaller) block */
984         if ((newaddr = malloc(size, mtp, flags)) == NULL)
985                 return (NULL);
986
987         /* Copy over original contents */
988         bcopy(addr, newaddr, min(size, alloc));
989         free(addr, mtp);
990         return (newaddr);
991 }
992
993 /*
994  *      reallocf: same as realloc() but free memory on failure.
995  */
996 void *
997 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
998 {
999         void *mem;
1000
1001         if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1002                 free(addr, mtp);
1003         return (mem);
1004 }
1005
1006 /*
1007  *      malloc_size: returns the number of bytes allocated for a request of the
1008  *                   specified size
1009  */
1010 size_t
1011 malloc_size(size_t size)
1012 {
1013         int indx;
1014
1015         if (size > kmem_zmax)
1016                 return (0);
1017         if (size & KMEM_ZMASK)
1018                 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
1019         indx = kmemsize[size >> KMEM_ZSHIFT];
1020         return (kmemzones[indx].kz_size);
1021 }
1022
1023 /*
1024  *      malloc_usable_size: returns the usable size of the allocation.
1025  */
1026 size_t
1027 malloc_usable_size(const void *addr)
1028 {
1029 #ifndef DEBUG_REDZONE
1030         uma_zone_t zone;
1031         uma_slab_t slab;
1032 #endif
1033         u_long size;
1034
1035         if (addr == NULL)
1036                 return (0);
1037
1038 #ifdef DEBUG_MEMGUARD
1039         if (is_memguard_addr(__DECONST(void *, addr)))
1040                 return (memguard_get_req_size(addr));
1041 #endif
1042
1043 #ifdef DEBUG_REDZONE
1044         size = redzone_get_size(__DECONST(void *, addr));
1045 #else
1046         vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1047         if (slab == NULL)
1048                 panic("malloc_usable_size: address %p(%p) is not allocated.\n",
1049                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1050
1051         if (!malloc_large_slab(slab))
1052                 size = zone->uz_size;
1053         else
1054                 size = malloc_large_size(slab);
1055 #endif
1056         return (size);
1057 }
1058
1059 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1060
1061 /*
1062  * Initialize the kernel memory (kmem) arena.
1063  */
1064 void
1065 kmeminit(void)
1066 {
1067         u_long mem_size;
1068         u_long tmp;
1069
1070 #ifdef VM_KMEM_SIZE
1071         if (vm_kmem_size == 0)
1072                 vm_kmem_size = VM_KMEM_SIZE;
1073 #endif
1074 #ifdef VM_KMEM_SIZE_MIN
1075         if (vm_kmem_size_min == 0)
1076                 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1077 #endif
1078 #ifdef VM_KMEM_SIZE_MAX
1079         if (vm_kmem_size_max == 0)
1080                 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1081 #endif
1082         /*
1083          * Calculate the amount of kernel virtual address (KVA) space that is
1084          * preallocated to the kmem arena.  In order to support a wide range
1085          * of machines, it is a function of the physical memory size,
1086          * specifically,
1087          *
1088          *      min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1089          *          VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1090          *
1091          * Every architecture must define an integral value for
1092          * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
1093          * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1094          * ceiling on this preallocation, are optional.  Typically,
1095          * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1096          * a given architecture.
1097          */
1098         mem_size = vm_cnt.v_page_count;
1099         if (mem_size <= 32768) /* delphij XXX 128MB */
1100                 kmem_zmax = PAGE_SIZE;
1101
1102         if (vm_kmem_size_scale < 1)
1103                 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1104
1105         /*
1106          * Check if we should use defaults for the "vm_kmem_size"
1107          * variable:
1108          */
1109         if (vm_kmem_size == 0) {
1110                 vm_kmem_size = mem_size / vm_kmem_size_scale;
1111                 vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1112                     vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1113                 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1114                         vm_kmem_size = vm_kmem_size_min;
1115                 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1116                         vm_kmem_size = vm_kmem_size_max;
1117         }
1118         if (vm_kmem_size == 0)
1119                 panic("Tune VM_KMEM_SIZE_* for the platform");
1120
1121         /*
1122          * The amount of KVA space that is preallocated to the
1123          * kmem arena can be set statically at compile-time or manually
1124          * through the kernel environment.  However, it is still limited to
1125          * twice the physical memory size, which has been sufficient to handle
1126          * the most severe cases of external fragmentation in the kmem arena. 
1127          */
1128         if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1129                 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1130
1131         vm_kmem_size = round_page(vm_kmem_size);
1132 #ifdef DEBUG_MEMGUARD
1133         tmp = memguard_fudge(vm_kmem_size, kernel_map);
1134 #else
1135         tmp = vm_kmem_size;
1136 #endif
1137         uma_set_limit(tmp);
1138
1139 #ifdef DEBUG_MEMGUARD
1140         /*
1141          * Initialize MemGuard if support compiled in.  MemGuard is a
1142          * replacement allocator used for detecting tamper-after-free
1143          * scenarios as they occur.  It is only used for debugging.
1144          */
1145         memguard_init(kernel_arena);
1146 #endif
1147 }
1148
1149 /*
1150  * Initialize the kernel memory allocator
1151  */
1152 /* ARGSUSED*/
1153 static void
1154 mallocinit(void *dummy)
1155 {
1156         int i;
1157         uint8_t indx;
1158
1159         mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1160
1161         kmeminit();
1162
1163         if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1164                 kmem_zmax = KMEM_ZMAX;
1165
1166         for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1167                 int size = kmemzones[indx].kz_size;
1168                 const char *name = kmemzones[indx].kz_name;
1169                 int subzone;
1170
1171                 for (subzone = 0; subzone < numzones; subzone++) {
1172                         kmemzones[indx].kz_zone[subzone] =
1173                             uma_zcreate(name, size,
1174 #ifdef INVARIANTS
1175                             mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1176 #else
1177                             NULL, NULL, NULL, NULL,
1178 #endif
1179                             UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1180                 }
1181                 for (;i <= size; i+= KMEM_ZBASE)
1182                         kmemsize[i >> KMEM_ZSHIFT] = indx;
1183         }
1184 }
1185 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1186
1187 void
1188 malloc_init(void *data)
1189 {
1190         struct malloc_type_internal *mtip;
1191         struct malloc_type *mtp;
1192
1193         KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1194
1195         mtp = data;
1196         if (mtp->ks_version != M_VERSION)
1197                 panic("malloc_init: type %s with unsupported version %lu",
1198                     mtp->ks_shortdesc, mtp->ks_version);
1199
1200         mtip = &mtp->ks_mti;
1201         mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1202         mtp_set_subzone(mtp);
1203
1204         mtx_lock(&malloc_mtx);
1205         mtp->ks_next = kmemstatistics;
1206         kmemstatistics = mtp;
1207         kmemcount++;
1208         mtx_unlock(&malloc_mtx);
1209 }
1210
1211 void
1212 malloc_uninit(void *data)
1213 {
1214         struct malloc_type_internal *mtip;
1215         struct malloc_type_stats *mtsp;
1216         struct malloc_type *mtp, *temp;
1217         long temp_allocs, temp_bytes;
1218         int i;
1219
1220         mtp = data;
1221         KASSERT(mtp->ks_version == M_VERSION,
1222             ("malloc_uninit: bad malloc type version"));
1223
1224         mtx_lock(&malloc_mtx);
1225         mtip = &mtp->ks_mti;
1226         if (mtp != kmemstatistics) {
1227                 for (temp = kmemstatistics; temp != NULL;
1228                     temp = temp->ks_next) {
1229                         if (temp->ks_next == mtp) {
1230                                 temp->ks_next = mtp->ks_next;
1231                                 break;
1232                         }
1233                 }
1234                 KASSERT(temp,
1235                     ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1236         } else
1237                 kmemstatistics = mtp->ks_next;
1238         kmemcount--;
1239         mtx_unlock(&malloc_mtx);
1240
1241         /*
1242          * Look for memory leaks.
1243          */
1244         temp_allocs = temp_bytes = 0;
1245         for (i = 0; i <= mp_maxid; i++) {
1246                 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1247                 temp_allocs += mtsp->mts_numallocs;
1248                 temp_allocs -= mtsp->mts_numfrees;
1249                 temp_bytes += mtsp->mts_memalloced;
1250                 temp_bytes -= mtsp->mts_memfreed;
1251         }
1252         if (temp_allocs > 0 || temp_bytes > 0) {
1253                 printf("Warning: memory type %s leaked memory on destroy "
1254                     "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1255                     temp_allocs, temp_bytes);
1256         }
1257
1258         uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1259 }
1260
1261 struct malloc_type *
1262 malloc_desc2type(const char *desc)
1263 {
1264         struct malloc_type *mtp;
1265
1266         mtx_assert(&malloc_mtx, MA_OWNED);
1267         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1268                 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1269                         return (mtp);
1270         }
1271         return (NULL);
1272 }
1273
1274 static int
1275 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1276 {
1277         struct malloc_type_stream_header mtsh;
1278         struct malloc_type_internal *mtip;
1279         struct malloc_type_stats *mtsp, zeromts;
1280         struct malloc_type_header mth;
1281         struct malloc_type *mtp;
1282         int error, i;
1283         struct sbuf sbuf;
1284
1285         error = sysctl_wire_old_buffer(req, 0);
1286         if (error != 0)
1287                 return (error);
1288         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1289         sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1290         mtx_lock(&malloc_mtx);
1291
1292         bzero(&zeromts, sizeof(zeromts));
1293
1294         /*
1295          * Insert stream header.
1296          */
1297         bzero(&mtsh, sizeof(mtsh));
1298         mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1299         mtsh.mtsh_maxcpus = MAXCPU;
1300         mtsh.mtsh_count = kmemcount;
1301         (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1302
1303         /*
1304          * Insert alternating sequence of type headers and type statistics.
1305          */
1306         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1307                 mtip = &mtp->ks_mti;
1308
1309                 /*
1310                  * Insert type header.
1311                  */
1312                 bzero(&mth, sizeof(mth));
1313                 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1314                 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1315
1316                 /*
1317                  * Insert type statistics for each CPU.
1318                  */
1319                 for (i = 0; i <= mp_maxid; i++) {
1320                         mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1321                         (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1322                 }
1323                 /*
1324                  * Fill in the missing CPUs.
1325                  */
1326                 for (; i < MAXCPU; i++) {
1327                         (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1328                 }
1329         }
1330         mtx_unlock(&malloc_mtx);
1331         error = sbuf_finish(&sbuf);
1332         sbuf_delete(&sbuf);
1333         return (error);
1334 }
1335
1336 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1337     CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1338     sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1339     "Return malloc types");
1340
1341 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1342     "Count of kernel malloc types");
1343
1344 void
1345 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1346 {
1347         struct malloc_type *mtp, **bufmtp;
1348         int count, i;
1349         size_t buflen;
1350
1351         mtx_lock(&malloc_mtx);
1352 restart:
1353         mtx_assert(&malloc_mtx, MA_OWNED);
1354         count = kmemcount;
1355         mtx_unlock(&malloc_mtx);
1356
1357         buflen = sizeof(struct malloc_type *) * count;
1358         bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1359
1360         mtx_lock(&malloc_mtx);
1361
1362         if (count < kmemcount) {
1363                 free(bufmtp, M_TEMP);
1364                 goto restart;
1365         }
1366
1367         for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1368                 bufmtp[i] = mtp;
1369
1370         mtx_unlock(&malloc_mtx);
1371
1372         for (i = 0; i < count; i++)
1373                 (func)(bufmtp[i], arg);
1374
1375         free(bufmtp, M_TEMP);
1376 }
1377
1378 #ifdef DDB
1379 static int64_t
1380 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1381     uint64_t *inuse)
1382 {
1383         const struct malloc_type_stats *mtsp;
1384         uint64_t frees, alloced, freed;
1385         int i;
1386
1387         *allocs = 0;
1388         frees = 0;
1389         alloced = 0;
1390         freed = 0;
1391         for (i = 0; i <= mp_maxid; i++) {
1392                 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1393
1394                 *allocs += mtsp->mts_numallocs;
1395                 frees += mtsp->mts_numfrees;
1396                 alloced += mtsp->mts_memalloced;
1397                 freed += mtsp->mts_memfreed;
1398         }
1399         *inuse = *allocs - frees;
1400         return (alloced - freed);
1401 }
1402
1403 DB_SHOW_COMMAND(malloc, db_show_malloc)
1404 {
1405         const char *fmt_hdr, *fmt_entry;
1406         struct malloc_type *mtp;
1407         uint64_t allocs, inuse;
1408         int64_t size;
1409         /* variables for sorting */
1410         struct malloc_type *last_mtype, *cur_mtype;
1411         int64_t cur_size, last_size;
1412         int ties;
1413
1414         if (modif[0] == 'i') {
1415                 fmt_hdr = "%s,%s,%s,%s\n";
1416                 fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1417         } else {
1418                 fmt_hdr = "%18s %12s  %12s %12s\n";
1419                 fmt_entry = "%18s %12ju %12jdK %12ju\n";
1420         }
1421
1422         db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1423
1424         /* Select sort, largest size first. */
1425         last_mtype = NULL;
1426         last_size = INT64_MAX;
1427         for (;;) {
1428                 cur_mtype = NULL;
1429                 cur_size = -1;
1430                 ties = 0;
1431
1432                 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1433                         /*
1434                          * In the case of size ties, print out mtypes
1435                          * in the order they are encountered.  That is,
1436                          * when we encounter the most recently output
1437                          * mtype, we have already printed all preceding
1438                          * ties, and we must print all following ties.
1439                          */
1440                         if (mtp == last_mtype) {
1441                                 ties = 1;
1442                                 continue;
1443                         }
1444                         size = get_malloc_stats(&mtp->ks_mti, &allocs,
1445                             &inuse);
1446                         if (size > cur_size && size < last_size + ties) {
1447                                 cur_size = size;
1448                                 cur_mtype = mtp;
1449                         }
1450                 }
1451                 if (cur_mtype == NULL)
1452                         break;
1453
1454                 size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
1455                 db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1456                     howmany(size, 1024), allocs);
1457
1458                 if (db_pager_quit)
1459                         break;
1460
1461                 last_mtype = cur_mtype;
1462                 last_size = cur_size;
1463         }
1464 }
1465
1466 #if MALLOC_DEBUG_MAXZONES > 1
1467 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1468 {
1469         struct malloc_type_internal *mtip;
1470         struct malloc_type *mtp;
1471         u_int subzone;
1472
1473         if (!have_addr) {
1474                 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1475                 return;
1476         }
1477         mtp = (void *)addr;
1478         if (mtp->ks_version != M_VERSION) {
1479                 db_printf("Version %lx does not match expected %x\n",
1480                     mtp->ks_version, M_VERSION);
1481                 return;
1482         }
1483
1484         mtip = &mtp->ks_mti;
1485         subzone = mtip->mti_zone;
1486
1487         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1488                 mtip = &mtp->ks_mti;
1489                 if (mtip->mti_zone != subzone)
1490                         continue;
1491                 db_printf("%s\n", mtp->ks_shortdesc);
1492                 if (db_pager_quit)
1493                         break;
1494         }
1495 }
1496 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1497 #endif /* DDB */
1498
1499 #ifdef MALLOC_PROFILE
1500
1501 static int
1502 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1503 {
1504         struct sbuf sbuf;
1505         uint64_t count;
1506         uint64_t waste;
1507         uint64_t mem;
1508         int error;
1509         int rsize;
1510         int size;
1511         int i;
1512
1513         waste = 0;
1514         mem = 0;
1515
1516         error = sysctl_wire_old_buffer(req, 0);
1517         if (error != 0)
1518                 return (error);
1519         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1520         sbuf_printf(&sbuf, 
1521             "\n  Size                    Requests  Real Size\n");
1522         for (i = 0; i < KMEM_ZSIZE; i++) {
1523                 size = i << KMEM_ZSHIFT;
1524                 rsize = kmemzones[kmemsize[i]].kz_size;
1525                 count = (long long unsigned)krequests[i];
1526
1527                 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1528                     (unsigned long long)count, rsize);
1529
1530                 if ((rsize * count) > (size * count))
1531                         waste += (rsize * count) - (size * count);
1532                 mem += (rsize * count);
1533         }
1534         sbuf_printf(&sbuf,
1535             "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1536             (unsigned long long)mem, (unsigned long long)waste);
1537         error = sbuf_finish(&sbuf);
1538         sbuf_delete(&sbuf);
1539         return (error);
1540 }
1541
1542 SYSCTL_OID(_kern, OID_AUTO, mprof,
1543     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
1544     sysctl_kern_mprof, "A",
1545     "Malloc Profiling");
1546 #endif /* MALLOC_PROFILE */