xref: /freebsd/sys/kern/kern_malloc.c (revision bfe691b2f75de2224c7ceb304ebcdef2b42d4179)
1 /*-
2  * Copyright (c) 1987, 1991, 1993
3  *	The Regents of the University of California.
4  * Copyright (c) 2005-2006 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)kern_malloc.c	8.3 (Berkeley) 1/4/94
32  */
33 
34 /*
35  * Kernel malloc(9) implementation -- general purpose kernel memory allocator
36  * based on memory types.  Back end is implemented using the UMA(9) zone
37  * allocator.  A set of fixed-size buckets are used for smaller allocations,
38  * and a special UMA allocation interface is used for larger allocations.
39  * Callers declare memory types, and statistics are maintained independently
40  * for each memory type.  Statistics are maintained per-CPU for performance
41  * reasons.  See malloc(9) and comments in malloc.h for a detailed
42  * description.
43  */
44 
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47 
48 #include "opt_ddb.h"
49 #include "opt_vm.h"
50 
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/kdb.h>
54 #include <sys/kernel.h>
55 #include <sys/lock.h>
56 #include <sys/malloc.h>
57 #include <sys/mbuf.h>
58 #include <sys/mutex.h>
59 #include <sys/vmmeter.h>
60 #include <sys/proc.h>
61 #include <sys/sbuf.h>
62 #include <sys/sysctl.h>
63 #include <sys/time.h>
64 
65 #include <vm/vm.h>
66 #include <vm/pmap.h>
67 #include <vm/vm_param.h>
68 #include <vm/vm_kern.h>
69 #include <vm/vm_extern.h>
70 #include <vm/vm_map.h>
71 #include <vm/vm_page.h>
72 #include <vm/uma.h>
73 #include <vm/uma_int.h>
74 #include <vm/uma_dbg.h>
75 
76 #ifdef DEBUG_MEMGUARD
77 #include <vm/memguard.h>
78 #endif
79 #ifdef DEBUG_REDZONE
80 #include <vm/redzone.h>
81 #endif
82 
83 #if defined(INVARIANTS) && defined(__i386__)
84 #include <machine/cpu.h>
85 #endif
86 
87 #include <ddb/ddb.h>
88 
89 /*
90  * When realloc() is called, if the new size is sufficiently smaller than
91  * the old size, realloc() will allocate a new, smaller block to avoid
92  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
93  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
94  */
95 #ifndef REALLOC_FRACTION
96 #define	REALLOC_FRACTION	1	/* new block if <= half the size */
97 #endif
98 
99 /*
100  * Centrally define some common malloc types.
101  */
102 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
103 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
104 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
105 
106 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
107 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
108 
109 static void kmeminit(void *);
110 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
111 
112 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
113 
114 static struct malloc_type *kmemstatistics;
115 static char *kmembase;
116 static char *kmemlimit;
117 static int kmemcount;
118 
119 #define KMEM_ZSHIFT	4
120 #define KMEM_ZBASE	16
121 #define KMEM_ZMASK	(KMEM_ZBASE - 1)
122 
123 #define KMEM_ZMAX	PAGE_SIZE
124 #define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
125 static u_int8_t kmemsize[KMEM_ZSIZE + 1];
126 
127 /*
128  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
129  * of various sizes.
130  *
131  * XXX: The comment here used to read "These won't be powers of two for
132  * long."  It's possible that a significant amount of wasted memory could be
133  * recovered by tuning the sizes of these buckets.
134  */
135 struct {
136 	int kz_size;
137 	char *kz_name;
138 	uma_zone_t kz_zone;
139 } kmemzones[] = {
140 	{16, "16", NULL},
141 	{32, "32", NULL},
142 	{64, "64", NULL},
143 	{128, "128", NULL},
144 	{256, "256", NULL},
145 	{512, "512", NULL},
146 	{1024, "1024", NULL},
147 	{2048, "2048", NULL},
148 	{4096, "4096", NULL},
149 #if PAGE_SIZE > 4096
150 	{8192, "8192", NULL},
151 #if PAGE_SIZE > 8192
152 	{16384, "16384", NULL},
153 #if PAGE_SIZE > 16384
154 	{32768, "32768", NULL},
155 #if PAGE_SIZE > 32768
156 	{65536, "65536", NULL},
157 #if PAGE_SIZE > 65536
158 #error	"Unsupported PAGE_SIZE"
159 #endif	/* 65536 */
160 #endif	/* 32768 */
161 #endif	/* 16384 */
162 #endif	/* 8192 */
163 #endif	/* 4096 */
164 	{0, NULL},
165 };
166 
167 /*
168  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
169  * types are described by a data structure passed by the declaring code, but
170  * the malloc(9) implementation has its own data structure describing the
171  * type and statistics.  This permits the malloc(9)-internal data structures
172  * to be modified without breaking binary-compiled kernel modules that
173  * declare malloc types.
174  */
175 static uma_zone_t mt_zone;
176 
177 u_int vm_kmem_size;
178 SYSCTL_UINT(_vm, OID_AUTO, kmem_size, CTLFLAG_RD, &vm_kmem_size, 0,
179     "Size of kernel memory");
180 
181 u_int vm_kmem_size_max;
182 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RD, &vm_kmem_size_max, 0,
183     "Maximum size of kernel memory");
184 
185 u_int vm_kmem_size_scale;
186 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RD, &vm_kmem_size_scale, 0,
187     "Scale factor for kernel memory size");
188 
189 /*
190  * The malloc_mtx protects the kmemstatistics linked list.
191  */
192 struct mtx malloc_mtx;
193 
194 #ifdef MALLOC_PROFILE
195 uint64_t krequests[KMEM_ZSIZE + 1];
196 
197 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
198 #endif
199 
200 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
201 
202 /*
203  * time_uptime of the last malloc(9) failure (induced or real).
204  */
205 static time_t t_malloc_fail;
206 
207 /*
208  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
209  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
210  */
211 #ifdef MALLOC_MAKE_FAILURES
212 SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
213     "Kernel malloc debugging options");
214 
215 static int malloc_failure_rate;
216 static int malloc_nowait_count;
217 static int malloc_failure_count;
218 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW,
219     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
220 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
221 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
222     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
223 #endif
224 
225 int
226 malloc_last_fail(void)
227 {
228 
229 	return (time_uptime - t_malloc_fail);
230 }
231 
232 /*
233  * An allocation has succeeded -- update malloc type statistics for the
234  * amount of bucket size.  Occurs within a critical section so that the
235  * thread isn't preempted and doesn't migrate while updating per-PCU
236  * statistics.
237  */
238 static void
239 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
240     int zindx)
241 {
242 	struct malloc_type_internal *mtip;
243 	struct malloc_type_stats *mtsp;
244 
245 	critical_enter();
246 	mtip = mtp->ks_handle;
247 	mtsp = &mtip->mti_stats[curcpu];
248 	if (size > 0) {
249 		mtsp->mts_memalloced += size;
250 		mtsp->mts_numallocs++;
251 	}
252 	if (zindx != -1)
253 		mtsp->mts_size |= 1 << zindx;
254 	critical_exit();
255 }
256 
257 void
258 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
259 {
260 
261 	if (size > 0)
262 		malloc_type_zone_allocated(mtp, size, -1);
263 }
264 
265 /*
266  * A free operation has occurred -- update malloc type statistis for the
267  * amount of the bucket size.  Occurs within a critical section so that the
268  * thread isn't preempted and doesn't migrate while updating per-CPU
269  * statistics.
270  */
271 void
272 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
273 {
274 	struct malloc_type_internal *mtip;
275 	struct malloc_type_stats *mtsp;
276 
277 	critical_enter();
278 	mtip = mtp->ks_handle;
279 	mtsp = &mtip->mti_stats[curcpu];
280 	mtsp->mts_memfreed += size;
281 	mtsp->mts_numfrees++;
282 	critical_exit();
283 }
284 
285 /*
286  *	malloc:
287  *
288  *	Allocate a block of memory.
289  *
290  *	If M_NOWAIT is set, this routine will not block and return NULL if
291  *	the allocation fails.
292  */
293 void *
294 malloc(unsigned long size, struct malloc_type *mtp, int flags)
295 {
296 	int indx;
297 	caddr_t va;
298 	uma_zone_t zone;
299 	uma_keg_t keg;
300 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
301 	unsigned long osize = size;
302 #endif
303 
304 #ifdef INVARIANTS
305 	/*
306 	 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
307 	 */
308 	indx = flags & (M_WAITOK | M_NOWAIT);
309 	if (indx != M_NOWAIT && indx != M_WAITOK) {
310 		static	struct timeval lasterr;
311 		static	int curerr, once;
312 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
313 			printf("Bad malloc flags: %x\n", indx);
314 			kdb_backtrace();
315 			flags |= M_WAITOK;
316 			once++;
317 		}
318 	}
319 #endif
320 #if 0
321 	if (size == 0)
322 		kdb_enter("zero size malloc");
323 #endif
324 #ifdef MALLOC_MAKE_FAILURES
325 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
326 		atomic_add_int(&malloc_nowait_count, 1);
327 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
328 			atomic_add_int(&malloc_failure_count, 1);
329 			t_malloc_fail = time_uptime;
330 			return (NULL);
331 		}
332 	}
333 #endif
334 	if (flags & M_WAITOK)
335 		KASSERT(curthread->td_intr_nesting_level == 0,
336 		   ("malloc(M_WAITOK) in interrupt context"));
337 
338 #ifdef DEBUG_MEMGUARD
339 	if (memguard_cmp(mtp))
340 		return memguard_alloc(size, flags);
341 #endif
342 
343 #ifdef DEBUG_REDZONE
344 	size = redzone_size_ntor(size);
345 #endif
346 
347 	if (size <= KMEM_ZMAX) {
348 		if (size & KMEM_ZMASK)
349 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
350 		indx = kmemsize[size >> KMEM_ZSHIFT];
351 		zone = kmemzones[indx].kz_zone;
352 		keg = zone->uz_keg;
353 #ifdef MALLOC_PROFILE
354 		krequests[size >> KMEM_ZSHIFT]++;
355 #endif
356 		va = uma_zalloc(zone, flags);
357 		if (va != NULL)
358 			size = keg->uk_size;
359 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
360 	} else {
361 		size = roundup(size, PAGE_SIZE);
362 		zone = NULL;
363 		keg = NULL;
364 		va = uma_large_malloc(size, flags);
365 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
366 	}
367 	if (flags & M_WAITOK)
368 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
369 	else if (va == NULL)
370 		t_malloc_fail = time_uptime;
371 #ifdef DIAGNOSTIC
372 	if (va != NULL && !(flags & M_ZERO)) {
373 		memset(va, 0x70, osize);
374 	}
375 #endif
376 #ifdef DEBUG_REDZONE
377 	if (va != NULL)
378 		va = redzone_setup(va, osize);
379 #endif
380 	return ((void *) va);
381 }
382 
383 /*
384  *	free:
385  *
386  *	Free a block of memory allocated by malloc.
387  *
388  *	This routine may not block.
389  */
390 void
391 free(void *addr, struct malloc_type *mtp)
392 {
393 	uma_slab_t slab;
394 	u_long size;
395 
396 	/* free(NULL, ...) does nothing */
397 	if (addr == NULL)
398 		return;
399 
400 #ifdef DEBUG_MEMGUARD
401 	if (memguard_cmp(mtp)) {
402 		memguard_free(addr);
403 		return;
404 	}
405 #endif
406 
407 #ifdef DEBUG_REDZONE
408 	redzone_check(addr);
409 	addr = redzone_addr_ntor(addr);
410 #endif
411 
412 	size = 0;
413 
414 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
415 
416 	if (slab == NULL)
417 		panic("free: address %p(%p) has not been allocated.\n",
418 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
419 
420 
421 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
422 #ifdef INVARIANTS
423 		struct malloc_type **mtpp = addr;
424 #endif
425 		size = slab->us_keg->uk_size;
426 #ifdef INVARIANTS
427 		/*
428 		 * Cache a pointer to the malloc_type that most recently freed
429 		 * this memory here.  This way we know who is most likely to
430 		 * have stepped on it later.
431 		 *
432 		 * This code assumes that size is a multiple of 8 bytes for
433 		 * 64 bit machines
434 		 */
435 		mtpp = (struct malloc_type **)
436 		    ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
437 		mtpp += (size - sizeof(struct malloc_type *)) /
438 		    sizeof(struct malloc_type *);
439 		*mtpp = mtp;
440 #endif
441 		uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
442 	} else {
443 		size = slab->us_size;
444 		uma_large_free(slab);
445 	}
446 	malloc_type_freed(mtp, size);
447 }
448 
449 /*
450  *	realloc: change the size of a memory block
451  */
452 void *
453 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
454 {
455 	uma_slab_t slab;
456 	unsigned long alloc;
457 	void *newaddr;
458 
459 	/* realloc(NULL, ...) is equivalent to malloc(...) */
460 	if (addr == NULL)
461 		return (malloc(size, mtp, flags));
462 
463 	/*
464 	 * XXX: Should report free of old memory and alloc of new memory to
465 	 * per-CPU stats.
466 	 */
467 
468 #ifdef DEBUG_MEMGUARD
469 if (memguard_cmp(mtp)) {
470 	slab = NULL;
471 	alloc = size;
472 } else {
473 #endif
474 
475 #ifdef DEBUG_REDZONE
476 	slab = NULL;
477 	alloc = redzone_get_size(addr);
478 #else
479 	slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
480 
481 	/* Sanity check */
482 	KASSERT(slab != NULL,
483 	    ("realloc: address %p out of range", (void *)addr));
484 
485 	/* Get the size of the original block */
486 	if (!(slab->us_flags & UMA_SLAB_MALLOC))
487 		alloc = slab->us_keg->uk_size;
488 	else
489 		alloc = slab->us_size;
490 
491 	/* Reuse the original block if appropriate */
492 	if (size <= alloc
493 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
494 		return (addr);
495 #endif /* !DEBUG_REDZONE */
496 
497 #ifdef DEBUG_MEMGUARD
498 }
499 #endif
500 
501 	/* Allocate a new, bigger (or smaller) block */
502 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
503 		return (NULL);
504 
505 	/* Copy over original contents */
506 	bcopy(addr, newaddr, min(size, alloc));
507 	free(addr, mtp);
508 	return (newaddr);
509 }
510 
511 /*
512  *	reallocf: same as realloc() but free memory on failure.
513  */
514 void *
515 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
516 {
517 	void *mem;
518 
519 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
520 		free(addr, mtp);
521 	return (mem);
522 }
523 
524 /*
525  * Initialize the kernel memory allocator
526  */
527 /* ARGSUSED*/
528 static void
529 kmeminit(void *dummy)
530 {
531 	u_int8_t indx;
532 	u_long mem_size;
533 	int i;
534 
535 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
536 
537 	/*
538 	 * Try to auto-tune the kernel memory size, so that it is
539 	 * more applicable for a wider range of machine sizes.
540 	 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
541 	 * a VM_KMEM_SIZE of 12MB is a fair compromise.  The
542 	 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
543 	 * available, and on an X86 with a total KVA space of 256MB,
544 	 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
545 	 *
546 	 * Note that the kmem_map is also used by the zone allocator,
547 	 * so make sure that there is enough space.
548 	 */
549 	vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
550 	mem_size = cnt.v_page_count;
551 
552 #if defined(VM_KMEM_SIZE_SCALE)
553 	vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
554 #endif
555 	TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
556 	if (vm_kmem_size_scale > 0 &&
557 	    (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
558 		vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
559 
560 #if defined(VM_KMEM_SIZE_MAX)
561 	vm_kmem_size_max = VM_KMEM_SIZE_MAX;
562 #endif
563 	TUNABLE_INT_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
564 	if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
565 		vm_kmem_size = vm_kmem_size_max;
566 
567 	/* Allow final override from the kernel environment */
568 #ifndef BURN_BRIDGES
569 	if (TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size) != 0)
570 		printf("kern.vm.kmem.size is now called vm.kmem_size!\n");
571 #endif
572 	TUNABLE_INT_FETCH("vm.kmem_size", &vm_kmem_size);
573 
574 	/*
575 	 * Limit kmem virtual size to twice the physical memory.
576 	 * This allows for kmem map sparseness, but limits the size
577 	 * to something sane. Be careful to not overflow the 32bit
578 	 * ints while doing the check.
579 	 */
580 	if (((vm_kmem_size / 2) / PAGE_SIZE) > cnt.v_page_count)
581 		vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
582 
583 	/*
584 	 * Tune settings based on the kernel map's size at this time.
585 	 */
586 	init_param3(vm_kmem_size / PAGE_SIZE);
587 
588 	kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
589 		(vm_offset_t *)&kmemlimit, vm_kmem_size);
590 	kmem_map->system_map = 1;
591 
592 #ifdef DEBUG_MEMGUARD
593 	/*
594 	 * Initialize MemGuard if support compiled in.  MemGuard is a
595 	 * replacement allocator used for detecting tamper-after-free
596 	 * scenarios as they occur.  It is only used for debugging.
597 	 */
598 	vm_memguard_divisor = 10;
599 	TUNABLE_INT_FETCH("vm.memguard.divisor", &vm_memguard_divisor);
600 
601 	/* Pick a conservative value if provided value sucks. */
602 	if ((vm_memguard_divisor <= 0) ||
603 	    ((vm_kmem_size / vm_memguard_divisor) == 0))
604 		vm_memguard_divisor = 10;
605 	memguard_init(kmem_map, vm_kmem_size / vm_memguard_divisor);
606 #endif
607 
608 	uma_startup2();
609 
610 	mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
611 #ifdef INVARIANTS
612 	    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
613 #else
614 	    NULL, NULL, NULL, NULL,
615 #endif
616 	    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
617 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
618 		int size = kmemzones[indx].kz_size;
619 		char *name = kmemzones[indx].kz_name;
620 
621 		kmemzones[indx].kz_zone = uma_zcreate(name, size,
622 #ifdef INVARIANTS
623 		    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
624 #else
625 		    NULL, NULL, NULL, NULL,
626 #endif
627 		    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
628 
629 		for (;i <= size; i+= KMEM_ZBASE)
630 			kmemsize[i >> KMEM_ZSHIFT] = indx;
631 
632 	}
633 }
634 
635 void
636 malloc_init(void *data)
637 {
638 	struct malloc_type_internal *mtip;
639 	struct malloc_type *mtp;
640 
641 	KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
642 
643 	mtp = data;
644 	mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
645 	mtp->ks_handle = mtip;
646 
647 	mtx_lock(&malloc_mtx);
648 	mtp->ks_next = kmemstatistics;
649 	kmemstatistics = mtp;
650 	kmemcount++;
651 	mtx_unlock(&malloc_mtx);
652 }
653 
654 void
655 malloc_uninit(void *data)
656 {
657 	struct malloc_type_internal *mtip;
658 	struct malloc_type_stats *mtsp;
659 	struct malloc_type *mtp, *temp;
660 	uma_slab_t slab;
661 	long temp_allocs, temp_bytes;
662 	int i;
663 
664 	mtp = data;
665 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
666 	mtx_lock(&malloc_mtx);
667 	mtip = mtp->ks_handle;
668 	mtp->ks_handle = NULL;
669 	if (mtp != kmemstatistics) {
670 		for (temp = kmemstatistics; temp != NULL;
671 		    temp = temp->ks_next) {
672 			if (temp->ks_next == mtp)
673 				temp->ks_next = mtp->ks_next;
674 		}
675 	} else
676 		kmemstatistics = mtp->ks_next;
677 	kmemcount--;
678 	mtx_unlock(&malloc_mtx);
679 
680 	/*
681 	 * Look for memory leaks.
682 	 */
683 	temp_allocs = temp_bytes = 0;
684 	for (i = 0; i < MAXCPU; i++) {
685 		mtsp = &mtip->mti_stats[i];
686 		temp_allocs += mtsp->mts_numallocs;
687 		temp_allocs -= mtsp->mts_numfrees;
688 		temp_bytes += mtsp->mts_memalloced;
689 		temp_bytes -= mtsp->mts_memfreed;
690 	}
691 	if (temp_allocs > 0 || temp_bytes > 0) {
692 		printf("Warning: memory type %s leaked memory on destroy "
693 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
694 		    temp_allocs, temp_bytes);
695 	}
696 
697 	slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
698 	uma_zfree_arg(mt_zone, mtip, slab);
699 }
700 
701 struct malloc_type *
702 malloc_desc2type(const char *desc)
703 {
704 	struct malloc_type *mtp;
705 
706 	mtx_assert(&malloc_mtx, MA_OWNED);
707 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
708 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
709 			return (mtp);
710 	}
711 	return (NULL);
712 }
713 
714 static int
715 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
716 {
717 	struct malloc_type_stream_header mtsh;
718 	struct malloc_type_internal *mtip;
719 	struct malloc_type_header mth;
720 	struct malloc_type *mtp;
721 	int buflen, count, error, i;
722 	struct sbuf sbuf;
723 	char *buffer;
724 
725 	mtx_lock(&malloc_mtx);
726 restart:
727 	mtx_assert(&malloc_mtx, MA_OWNED);
728 	count = kmemcount;
729 	mtx_unlock(&malloc_mtx);
730 	buflen = sizeof(mtsh) + count * (sizeof(mth) +
731 	    sizeof(struct malloc_type_stats) * MAXCPU) + 1;
732 	buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
733 	mtx_lock(&malloc_mtx);
734 	if (count < kmemcount) {
735 		free(buffer, M_TEMP);
736 		goto restart;
737 	}
738 
739 	sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
740 
741 	/*
742 	 * Insert stream header.
743 	 */
744 	bzero(&mtsh, sizeof(mtsh));
745 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
746 	mtsh.mtsh_maxcpus = MAXCPU;
747 	mtsh.mtsh_count = kmemcount;
748 	if (sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)) < 0) {
749 		mtx_unlock(&malloc_mtx);
750 		error = ENOMEM;
751 		goto out;
752 	}
753 
754 	/*
755 	 * Insert alternating sequence of type headers and type statistics.
756 	 */
757 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
758 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
759 
760 		/*
761 		 * Insert type header.
762 		 */
763 		bzero(&mth, sizeof(mth));
764 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
765 		if (sbuf_bcat(&sbuf, &mth, sizeof(mth)) < 0) {
766 			mtx_unlock(&malloc_mtx);
767 			error = ENOMEM;
768 			goto out;
769 		}
770 
771 		/*
772 		 * Insert type statistics for each CPU.
773 		 */
774 		for (i = 0; i < MAXCPU; i++) {
775 			if (sbuf_bcat(&sbuf, &mtip->mti_stats[i],
776 			    sizeof(mtip->mti_stats[i])) < 0) {
777 				mtx_unlock(&malloc_mtx);
778 				error = ENOMEM;
779 				goto out;
780 			}
781 		}
782 	}
783 	mtx_unlock(&malloc_mtx);
784 	sbuf_finish(&sbuf);
785 	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
786 out:
787 	sbuf_delete(&sbuf);
788 	free(buffer, M_TEMP);
789 	return (error);
790 }
791 
792 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
793     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
794     "Return malloc types");
795 
796 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
797     "Count of kernel malloc types");
798 
799 #ifdef DDB
800 DB_SHOW_COMMAND(malloc, db_show_malloc)
801 {
802 	struct malloc_type_internal *mtip;
803 	struct malloc_type *mtp;
804 	u_int64_t allocs, frees;
805 	u_int64_t alloced, freed;
806 	int i;
807 
808 	db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
809 	    "Requests");
810 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
811 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
812 		allocs = 0;
813 		frees = 0;
814 		alloced = 0;
815 		freed = 0;
816 		for (i = 0; i < MAXCPU; i++) {
817 			allocs += mtip->mti_stats[i].mts_numallocs;
818 			frees += mtip->mti_stats[i].mts_numfrees;
819 			alloced += mtip->mti_stats[i].mts_memalloced;
820 			freed += mtip->mti_stats[i].mts_memfreed;
821 		}
822 		db_printf("%18s %12ju %12juK %12ju\n",
823 		    mtp->ks_shortdesc, allocs - frees,
824 		    (alloced - freed + 1023) / 1024, allocs);
825 	}
826 }
827 #endif
828 
829 #ifdef MALLOC_PROFILE
830 
831 static int
832 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
833 {
834 	int linesize = 64;
835 	struct sbuf sbuf;
836 	uint64_t count;
837 	uint64_t waste;
838 	uint64_t mem;
839 	int bufsize;
840 	int error;
841 	char *buf;
842 	int rsize;
843 	int size;
844 	int i;
845 
846 	bufsize = linesize * (KMEM_ZSIZE + 1);
847 	bufsize += 128; 	/* For the stats line */
848 	bufsize += 128; 	/* For the banner line */
849 	waste = 0;
850 	mem = 0;
851 
852 	buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
853 	sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
854 	sbuf_printf(&sbuf,
855 	    "\n  Size                    Requests  Real Size\n");
856 	for (i = 0; i < KMEM_ZSIZE; i++) {
857 		size = i << KMEM_ZSHIFT;
858 		rsize = kmemzones[kmemsize[i]].kz_size;
859 		count = (long long unsigned)krequests[i];
860 
861 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
862 		    (unsigned long long)count, rsize);
863 
864 		if ((rsize * count) > (size * count))
865 			waste += (rsize * count) - (size * count);
866 		mem += (rsize * count);
867 	}
868 	sbuf_printf(&sbuf,
869 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
870 	    (unsigned long long)mem, (unsigned long long)waste);
871 	sbuf_finish(&sbuf);
872 
873 	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
874 
875 	sbuf_delete(&sbuf);
876 	free(buf, M_TEMP);
877 	return (error);
878 }
879 
880 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
881     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
882 #endif /* MALLOC_PROFILE */
883