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