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