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