xref: /freebsd/sys/kern/kern_malloc.c (revision 90e2fc863a95ebc1fc12ae656dbbc42c16e17a83)
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_keg)
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 *mtp, *temp;
612 
613 	mtp = data;
614 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
615 	mtx_lock(&malloc_mtx);
616 	mtip = mtp->ks_handle;
617 	mtp->ks_handle = NULL;
618 	if (mtp != kmemstatistics) {
619 		for (temp = kmemstatistics; temp != NULL;
620 		    temp = temp->ks_next) {
621 			if (temp->ks_next == mtp)
622 				temp->ks_next = mtp->ks_next;
623 		}
624 	} else
625 		kmemstatistics = mtp->ks_next;
626 	kmemcount--;
627 	mtx_unlock(&malloc_mtx);
628 	uma_zfree(mt_zone, mtip);
629 }
630 
631 static int
632 sysctl_kern_malloc(SYSCTL_HANDLER_ARGS)
633 {
634 	struct malloc_type_stats mts_local, *mtsp;
635 	struct malloc_type_internal *mtip;
636 	struct malloc_type *mtp;
637 	struct sbuf sbuf;
638 	long temp_allocs, temp_bytes;
639 	int linesize = 128;
640 	int bufsize;
641 	int first;
642 	int error;
643 	char *buf;
644 	int cnt;
645 	int i;
646 
647 	cnt = 0;
648 
649 	/* Guess at how much room is needed. */
650 	mtx_lock(&malloc_mtx);
651 	cnt = kmemcount;
652 	mtx_unlock(&malloc_mtx);
653 
654 	bufsize = linesize * (cnt + 1);
655 	buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
656 	sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
657 
658 	mtx_lock(&malloc_mtx);
659 	sbuf_printf(&sbuf,
660 	    "\n        Type  InUse MemUse HighUse Requests  Size(s)\n");
661 	for (mtp = kmemstatistics; cnt != 0 && mtp != NULL;
662 	    mtp = mtp->ks_next, cnt--) {
663 		mtip = mtp->ks_handle;
664 		bzero(&mts_local, sizeof(mts_local));
665 		for (i = 0; i < MAXCPU; i++) {
666 			mtsp = &mtip->mti_stats[i];
667 			mts_local.mts_memalloced += mtsp->mts_memalloced;
668 			mts_local.mts_memfreed += mtsp->mts_memfreed;
669 			mts_local.mts_numallocs += mtsp->mts_numallocs;
670 			mts_local.mts_numfrees += mtsp->mts_numfrees;
671 			mts_local.mts_size |= mtsp->mts_size;
672 		}
673 		if (mts_local.mts_numallocs == 0)
674 			continue;
675 
676 		/*
677 		 * Due to races in per-CPU statistics gather, it's possible to
678 		 * get a slightly negative number here.  If we do, approximate
679 		 * with 0.
680 		 */
681 		if (mts_local.mts_numallocs > mts_local.mts_numfrees)
682 			temp_allocs = mts_local.mts_numallocs -
683 			    mts_local.mts_numfrees;
684 		else
685 			temp_allocs = 0;
686 
687 		/*
688 		 * Ditto for bytes allocated.
689 		 */
690 		if (mts_local.mts_memalloced > mts_local.mts_memfreed)
691 			temp_bytes = mts_local.mts_memalloced -
692 			    mts_local.mts_memfreed;
693 		else
694 			temp_bytes = 0;
695 
696 		/*
697 		 * High-waterwark is no longer easily available, so we just
698 		 * print '-' for that column.
699 		 */
700 		sbuf_printf(&sbuf, "%13s%6lu%6luK       -%9llu",
701 		    mtp->ks_shortdesc,
702 		    temp_allocs,
703 		    (temp_bytes + 1023) / 1024,
704 		    (unsigned long long)mts_local.mts_numallocs);
705 
706 		first = 1;
707 		for (i = 0; i < sizeof(kmemzones) / sizeof(kmemzones[0]) - 1;
708 		    i++) {
709 			if (mts_local.mts_size & (1 << i)) {
710 				if (first)
711 					sbuf_printf(&sbuf, "  ");
712 				else
713 					sbuf_printf(&sbuf, ",");
714 				sbuf_printf(&sbuf, "%s",
715 				    kmemzones[i].kz_name);
716 				first = 0;
717 			}
718 		}
719 		sbuf_printf(&sbuf, "\n");
720 	}
721 	sbuf_finish(&sbuf);
722 	mtx_unlock(&malloc_mtx);
723 
724 	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
725 
726 	sbuf_delete(&sbuf);
727 	free(buf, M_TEMP);
728 	return (error);
729 }
730 
731 SYSCTL_OID(_kern, OID_AUTO, malloc, CTLTYPE_STRING|CTLFLAG_RD,
732     NULL, 0, sysctl_kern_malloc, "A", "Malloc Stats");
733 
734 static int
735 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
736 {
737 	struct malloc_type_stream_header mtsh;
738 	struct malloc_type_internal *mtip;
739 	struct malloc_type_header mth;
740 	struct malloc_type *mtp;
741 	int buflen, count, error, i;
742 	struct sbuf sbuf;
743 	char *buffer;
744 
745 	mtx_lock(&malloc_mtx);
746 restart:
747 	mtx_assert(&malloc_mtx, MA_OWNED);
748 	count = kmemcount;
749 	mtx_unlock(&malloc_mtx);
750 	buflen = sizeof(mtsh) + count * (sizeof(mth) +
751 	    sizeof(struct malloc_type_stats) * MAXCPU) + 1;
752 	buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
753 	mtx_lock(&malloc_mtx);
754 	if (count < kmemcount) {
755 		free(buffer, M_TEMP);
756 		goto restart;
757 	}
758 
759 	sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
760 
761 	/*
762 	 * Insert stream header.
763 	 */
764 	bzero(&mtsh, sizeof(mtsh));
765 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
766 	mtsh.mtsh_maxcpus = MAXCPU;
767 	mtsh.mtsh_count = kmemcount;
768 	if (sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)) < 0) {
769 		mtx_unlock(&malloc_mtx);
770 		error = ENOMEM;
771 		goto out;
772 	}
773 
774 	/*
775 	 * Insert alternating sequence of type headers and type statistics.
776 	 */
777 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
778 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
779 
780 		/*
781 		 * Insert type header.
782 		 */
783 		bzero(&mth, sizeof(mth));
784 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
785 		if (sbuf_bcat(&sbuf, &mth, sizeof(mth)) < 0) {
786 			mtx_unlock(&malloc_mtx);
787 			error = ENOMEM;
788 			goto out;
789 		}
790 
791 		/*
792 		 * Insert type statistics for each CPU.
793 		 */
794 		for (i = 0; i < MAXCPU; i++) {
795 			if (sbuf_bcat(&sbuf, &mtip->mti_stats[i],
796 			    sizeof(mtip->mti_stats[i])) < 0) {
797 				mtx_unlock(&malloc_mtx);
798 				error = ENOMEM;
799 				goto out;
800 			}
801 		}
802 	}
803 	mtx_unlock(&malloc_mtx);
804 	sbuf_finish(&sbuf);
805 	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
806 out:
807 	sbuf_delete(&sbuf);
808 	free(buffer, M_TEMP);
809 	return (error);
810 }
811 
812 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
813     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
814     "Return malloc types");
815 
816 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
817     "Count of kernel malloc types");
818 
819 #ifdef DDB
820 DB_SHOW_COMMAND(malloc, db_show_malloc)
821 {
822 	struct malloc_type_internal *mtip;
823 	struct malloc_type *mtp;
824 	u_int64_t allocs, frees;
825 	int i;
826 
827 	db_printf("%18s %12s %12s %12s\n", "Type", "Allocs", "Frees",
828 	    "Used");
829 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
830 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
831 		allocs = 0;
832 		frees = 0;
833 		for (i = 0; i < MAXCPU; i++) {
834 			allocs += mtip->mti_stats[i].mts_numallocs;
835 			frees += mtip->mti_stats[i].mts_numfrees;
836 		}
837 		db_printf("%18s %12ju %12ju %12ju\n", mtp->ks_shortdesc,
838 		    allocs, frees, allocs - frees);
839 	}
840 }
841 #endif
842 
843 #ifdef MALLOC_PROFILE
844 
845 static int
846 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
847 {
848 	int linesize = 64;
849 	struct sbuf sbuf;
850 	uint64_t count;
851 	uint64_t waste;
852 	uint64_t mem;
853 	int bufsize;
854 	int error;
855 	char *buf;
856 	int rsize;
857 	int size;
858 	int i;
859 
860 	bufsize = linesize * (KMEM_ZSIZE + 1);
861 	bufsize += 128; 	/* For the stats line */
862 	bufsize += 128; 	/* For the banner line */
863 	waste = 0;
864 	mem = 0;
865 
866 	buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
867 	sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
868 	sbuf_printf(&sbuf,
869 	    "\n  Size                    Requests  Real Size\n");
870 	for (i = 0; i < KMEM_ZSIZE; i++) {
871 		size = i << KMEM_ZSHIFT;
872 		rsize = kmemzones[kmemsize[i]].kz_size;
873 		count = (long long unsigned)krequests[i];
874 
875 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
876 		    (unsigned long long)count, rsize);
877 
878 		if ((rsize * count) > (size * count))
879 			waste += (rsize * count) - (size * count);
880 		mem += (rsize * count);
881 	}
882 	sbuf_printf(&sbuf,
883 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
884 	    (unsigned long long)mem, (unsigned long long)waste);
885 	sbuf_finish(&sbuf);
886 
887 	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
888 
889 	sbuf_delete(&sbuf);
890 	free(buf, M_TEMP);
891 	return (error);
892 }
893 
894 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
895     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
896 #endif /* MALLOC_PROFILE */
897