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