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