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