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