xref: /freebsd/sys/kern/kern_malloc.c (revision 32ba16b6e6dbfa5e4f536695191a8816bd6a8765)
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))
431 		return memguard_alloc(size, flags);
432 #endif
433 
434 #ifdef DEBUG_REDZONE
435 	size = redzone_size_ntor(size);
436 #endif
437 
438 	if (size <= KMEM_ZMAX) {
439 		mtip = mtp->ks_handle;
440 		if (size & KMEM_ZMASK)
441 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
442 		indx = kmemsize[size >> KMEM_ZSHIFT];
443 		KASSERT(mtip->mti_zone < numzones,
444 		    ("mti_zone %u out of range %d",
445 		    mtip->mti_zone, numzones));
446 		zone = kmemzones[indx].kz_zone[mtip->mti_zone];
447 #ifdef MALLOC_PROFILE
448 		krequests[size >> KMEM_ZSHIFT]++;
449 #endif
450 		va = uma_zalloc(zone, flags);
451 		if (va != NULL)
452 			size = zone->uz_size;
453 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
454 	} else {
455 		size = roundup(size, PAGE_SIZE);
456 		zone = NULL;
457 		va = uma_large_malloc(size, flags);
458 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
459 	}
460 	if (flags & M_WAITOK)
461 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
462 	else if (va == NULL)
463 		t_malloc_fail = time_uptime;
464 #ifdef DIAGNOSTIC
465 	if (va != NULL && !(flags & M_ZERO)) {
466 		memset(va, 0x70, osize);
467 	}
468 #endif
469 #ifdef DEBUG_REDZONE
470 	if (va != NULL)
471 		va = redzone_setup(va, osize);
472 #endif
473 	return ((void *) va);
474 }
475 
476 /*
477  *	free:
478  *
479  *	Free a block of memory allocated by malloc.
480  *
481  *	This routine may not block.
482  */
483 void
484 free(void *addr, struct malloc_type *mtp)
485 {
486 	uma_slab_t slab;
487 	u_long size;
488 
489 	KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
490 
491 	/* free(NULL, ...) does nothing */
492 	if (addr == NULL)
493 		return;
494 
495 #ifdef DEBUG_MEMGUARD
496 	if (memguard_cmp(mtp)) {
497 		memguard_free(addr);
498 		return;
499 	}
500 #endif
501 
502 #ifdef DEBUG_REDZONE
503 	redzone_check(addr);
504 	addr = redzone_addr_ntor(addr);
505 #endif
506 
507 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
508 
509 	if (slab == NULL)
510 		panic("free: address %p(%p) has not been allocated.\n",
511 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
512 
513 
514 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
515 #ifdef INVARIANTS
516 		struct malloc_type **mtpp = addr;
517 #endif
518 		size = slab->us_keg->uk_size;
519 #ifdef INVARIANTS
520 		/*
521 		 * Cache a pointer to the malloc_type that most recently freed
522 		 * this memory here.  This way we know who is most likely to
523 		 * have stepped on it later.
524 		 *
525 		 * This code assumes that size is a multiple of 8 bytes for
526 		 * 64 bit machines
527 		 */
528 		mtpp = (struct malloc_type **)
529 		    ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
530 		mtpp += (size - sizeof(struct malloc_type *)) /
531 		    sizeof(struct malloc_type *);
532 		*mtpp = mtp;
533 #endif
534 		uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
535 	} else {
536 		size = slab->us_size;
537 		uma_large_free(slab);
538 	}
539 	malloc_type_freed(mtp, size);
540 }
541 
542 /*
543  *	realloc: change the size of a memory block
544  */
545 void *
546 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
547 {
548 	uma_slab_t slab;
549 	unsigned long alloc;
550 	void *newaddr;
551 
552 	KASSERT(mtp->ks_magic == M_MAGIC,
553 	    ("realloc: bad malloc type magic"));
554 
555 	/* realloc(NULL, ...) is equivalent to malloc(...) */
556 	if (addr == NULL)
557 		return (malloc(size, mtp, flags));
558 
559 	/*
560 	 * XXX: Should report free of old memory and alloc of new memory to
561 	 * per-CPU stats.
562 	 */
563 
564 #ifdef DEBUG_MEMGUARD
565 if (memguard_cmp(mtp)) {
566 	slab = NULL;
567 	alloc = size;
568 } else {
569 #endif
570 
571 #ifdef DEBUG_REDZONE
572 	slab = NULL;
573 	alloc = redzone_get_size(addr);
574 #else
575 	slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
576 
577 	/* Sanity check */
578 	KASSERT(slab != NULL,
579 	    ("realloc: address %p out of range", (void *)addr));
580 
581 	/* Get the size of the original block */
582 	if (!(slab->us_flags & UMA_SLAB_MALLOC))
583 		alloc = slab->us_keg->uk_size;
584 	else
585 		alloc = slab->us_size;
586 
587 	/* Reuse the original block if appropriate */
588 	if (size <= alloc
589 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
590 		return (addr);
591 #endif /* !DEBUG_REDZONE */
592 
593 #ifdef DEBUG_MEMGUARD
594 }
595 #endif
596 
597 	/* Allocate a new, bigger (or smaller) block */
598 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
599 		return (NULL);
600 
601 	/* Copy over original contents */
602 	bcopy(addr, newaddr, min(size, alloc));
603 	free(addr, mtp);
604 	return (newaddr);
605 }
606 
607 /*
608  *	reallocf: same as realloc() but free memory on failure.
609  */
610 void *
611 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
612 {
613 	void *mem;
614 
615 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
616 		free(addr, mtp);
617 	return (mem);
618 }
619 
620 /*
621  * Initialize the kernel memory allocator
622  */
623 /* ARGSUSED*/
624 static void
625 kmeminit(void *dummy)
626 {
627 	uint8_t indx;
628 	u_long mem_size;
629 	int i;
630 
631 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
632 
633 	/*
634 	 * Try to auto-tune the kernel memory size, so that it is
635 	 * more applicable for a wider range of machine sizes.
636 	 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
637 	 * a VM_KMEM_SIZE of 12MB is a fair compromise.  The
638 	 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
639 	 * available, and on an X86 with a total KVA space of 256MB,
640 	 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
641 	 *
642 	 * Note that the kmem_map is also used by the zone allocator,
643 	 * so make sure that there is enough space.
644 	 */
645 	vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
646 	mem_size = cnt.v_page_count;
647 
648 #if defined(VM_KMEM_SIZE_SCALE)
649 	vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
650 #endif
651 	TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
652 	if (vm_kmem_size_scale > 0 &&
653 	    (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
654 		vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
655 
656 #if defined(VM_KMEM_SIZE_MIN)
657 	vm_kmem_size_min = VM_KMEM_SIZE_MIN;
658 #endif
659 	TUNABLE_ULONG_FETCH("vm.kmem_size_min", &vm_kmem_size_min);
660 	if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) {
661 		vm_kmem_size = vm_kmem_size_min;
662 	}
663 
664 #if defined(VM_KMEM_SIZE_MAX)
665 	vm_kmem_size_max = VM_KMEM_SIZE_MAX;
666 #endif
667 	TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
668 	if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
669 		vm_kmem_size = vm_kmem_size_max;
670 
671 	/* Allow final override from the kernel environment */
672 	TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
673 
674 	/*
675 	 * Limit kmem virtual size to twice the physical memory.
676 	 * This allows for kmem map sparseness, but limits the size
677 	 * to something sane. Be careful to not overflow the 32bit
678 	 * ints while doing the check.
679 	 */
680 	if (((vm_kmem_size / 2) / PAGE_SIZE) > cnt.v_page_count)
681 		vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
682 
683 	/*
684 	 * Tune settings based on the kmem map's size at this time.
685 	 */
686 	init_param3(vm_kmem_size / PAGE_SIZE);
687 
688 	kmem_map = kmem_suballoc(kernel_map, &kmembase, &kmemlimit,
689 	    vm_kmem_size, TRUE);
690 	kmem_map->system_map = 1;
691 
692 #ifdef DEBUG_MEMGUARD
693 	/*
694 	 * Initialize MemGuard if support compiled in.  MemGuard is a
695 	 * replacement allocator used for detecting tamper-after-free
696 	 * scenarios as they occur.  It is only used for debugging.
697 	 */
698 	vm_memguard_divisor = 10;
699 	TUNABLE_INT_FETCH("vm.memguard.divisor", &vm_memguard_divisor);
700 
701 	/* Pick a conservative value if provided value sucks. */
702 	if ((vm_memguard_divisor <= 0) ||
703 	    ((vm_kmem_size / vm_memguard_divisor) == 0))
704 		vm_memguard_divisor = 10;
705 	memguard_init(kmem_map, vm_kmem_size / vm_memguard_divisor);
706 #endif
707 
708 	uma_startup2();
709 
710 	mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
711 #ifdef INVARIANTS
712 	    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
713 #else
714 	    NULL, NULL, NULL, NULL,
715 #endif
716 	    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
717 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
718 		int size = kmemzones[indx].kz_size;
719 		char *name = kmemzones[indx].kz_name;
720 		int subzone;
721 
722 		for (subzone = 0; subzone < numzones; subzone++) {
723 			kmemzones[indx].kz_zone[subzone] =
724 			    uma_zcreate(name, size,
725 #ifdef INVARIANTS
726 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
727 #else
728 			    NULL, NULL, NULL, NULL,
729 #endif
730 			    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
731 		}
732 		for (;i <= size; i+= KMEM_ZBASE)
733 			kmemsize[i >> KMEM_ZSHIFT] = indx;
734 
735 	}
736 }
737 
738 void
739 malloc_init(void *data)
740 {
741 	struct malloc_type_internal *mtip;
742 	struct malloc_type *mtp;
743 
744 	KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
745 
746 	mtp = data;
747 	if (mtp->ks_magic != M_MAGIC)
748 		panic("malloc_init: bad malloc type magic");
749 
750 	mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
751 	mtp->ks_handle = mtip;
752 	mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
753 
754 	mtx_lock(&malloc_mtx);
755 	mtp->ks_next = kmemstatistics;
756 	kmemstatistics = mtp;
757 	kmemcount++;
758 	mtx_unlock(&malloc_mtx);
759 }
760 
761 void
762 malloc_uninit(void *data)
763 {
764 	struct malloc_type_internal *mtip;
765 	struct malloc_type_stats *mtsp;
766 	struct malloc_type *mtp, *temp;
767 	uma_slab_t slab;
768 	long temp_allocs, temp_bytes;
769 	int i;
770 
771 	mtp = data;
772 	KASSERT(mtp->ks_magic == M_MAGIC,
773 	    ("malloc_uninit: bad malloc type magic"));
774 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
775 
776 	mtx_lock(&malloc_mtx);
777 	mtip = mtp->ks_handle;
778 	mtp->ks_handle = NULL;
779 	if (mtp != kmemstatistics) {
780 		for (temp = kmemstatistics; temp != NULL;
781 		    temp = temp->ks_next) {
782 			if (temp->ks_next == mtp) {
783 				temp->ks_next = mtp->ks_next;
784 				break;
785 			}
786 		}
787 		KASSERT(temp,
788 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
789 	} else
790 		kmemstatistics = mtp->ks_next;
791 	kmemcount--;
792 	mtx_unlock(&malloc_mtx);
793 
794 	/*
795 	 * Look for memory leaks.
796 	 */
797 	temp_allocs = temp_bytes = 0;
798 	for (i = 0; i < MAXCPU; i++) {
799 		mtsp = &mtip->mti_stats[i];
800 		temp_allocs += mtsp->mts_numallocs;
801 		temp_allocs -= mtsp->mts_numfrees;
802 		temp_bytes += mtsp->mts_memalloced;
803 		temp_bytes -= mtsp->mts_memfreed;
804 	}
805 	if (temp_allocs > 0 || temp_bytes > 0) {
806 		printf("Warning: memory type %s leaked memory on destroy "
807 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
808 		    temp_allocs, temp_bytes);
809 	}
810 
811 	slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
812 	uma_zfree_arg(mt_zone, mtip, slab);
813 }
814 
815 struct malloc_type *
816 malloc_desc2type(const char *desc)
817 {
818 	struct malloc_type *mtp;
819 
820 	mtx_assert(&malloc_mtx, MA_OWNED);
821 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
822 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
823 			return (mtp);
824 	}
825 	return (NULL);
826 }
827 
828 static int
829 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
830 {
831 	struct malloc_type_stream_header mtsh;
832 	struct malloc_type_internal *mtip;
833 	struct malloc_type_header mth;
834 	struct malloc_type *mtp;
835 	int buflen, count, error, i;
836 	struct sbuf sbuf;
837 	char *buffer;
838 
839 	mtx_lock(&malloc_mtx);
840 restart:
841 	mtx_assert(&malloc_mtx, MA_OWNED);
842 	count = kmemcount;
843 	mtx_unlock(&malloc_mtx);
844 	buflen = sizeof(mtsh) + count * (sizeof(mth) +
845 	    sizeof(struct malloc_type_stats) * MAXCPU) + 1;
846 	buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
847 	mtx_lock(&malloc_mtx);
848 	if (count < kmemcount) {
849 		free(buffer, M_TEMP);
850 		goto restart;
851 	}
852 
853 	sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
854 
855 	/*
856 	 * Insert stream header.
857 	 */
858 	bzero(&mtsh, sizeof(mtsh));
859 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
860 	mtsh.mtsh_maxcpus = MAXCPU;
861 	mtsh.mtsh_count = kmemcount;
862 	if (sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)) < 0) {
863 		mtx_unlock(&malloc_mtx);
864 		error = ENOMEM;
865 		goto out;
866 	}
867 
868 	/*
869 	 * Insert alternating sequence of type headers and type statistics.
870 	 */
871 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
872 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
873 
874 		/*
875 		 * Insert type header.
876 		 */
877 		bzero(&mth, sizeof(mth));
878 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
879 		if (sbuf_bcat(&sbuf, &mth, sizeof(mth)) < 0) {
880 			mtx_unlock(&malloc_mtx);
881 			error = ENOMEM;
882 			goto out;
883 		}
884 
885 		/*
886 		 * Insert type statistics for each CPU.
887 		 */
888 		for (i = 0; i < MAXCPU; i++) {
889 			if (sbuf_bcat(&sbuf, &mtip->mti_stats[i],
890 			    sizeof(mtip->mti_stats[i])) < 0) {
891 				mtx_unlock(&malloc_mtx);
892 				error = ENOMEM;
893 				goto out;
894 			}
895 		}
896 	}
897 	mtx_unlock(&malloc_mtx);
898 	sbuf_finish(&sbuf);
899 	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
900 out:
901 	sbuf_delete(&sbuf);
902 	free(buffer, M_TEMP);
903 	return (error);
904 }
905 
906 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
907     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
908     "Return malloc types");
909 
910 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
911     "Count of kernel malloc types");
912 
913 void
914 malloc_type_list(malloc_type_list_func_t *func, void *arg)
915 {
916 	struct malloc_type *mtp, **bufmtp;
917 	int count, i;
918 	size_t buflen;
919 
920 	mtx_lock(&malloc_mtx);
921 restart:
922 	mtx_assert(&malloc_mtx, MA_OWNED);
923 	count = kmemcount;
924 	mtx_unlock(&malloc_mtx);
925 
926 	buflen = sizeof(struct malloc_type *) * count;
927 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
928 
929 	mtx_lock(&malloc_mtx);
930 
931 	if (count < kmemcount) {
932 		free(bufmtp, M_TEMP);
933 		goto restart;
934 	}
935 
936 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
937 		bufmtp[i] = mtp;
938 
939 	mtx_unlock(&malloc_mtx);
940 
941 	for (i = 0; i < count; i++)
942 		(func)(bufmtp[i], arg);
943 
944 	free(bufmtp, M_TEMP);
945 }
946 
947 #ifdef DDB
948 DB_SHOW_COMMAND(malloc, db_show_malloc)
949 {
950 	struct malloc_type_internal *mtip;
951 	struct malloc_type *mtp;
952 	uint64_t allocs, frees;
953 	uint64_t alloced, freed;
954 	int i;
955 
956 	db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
957 	    "Requests");
958 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
959 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
960 		allocs = 0;
961 		frees = 0;
962 		alloced = 0;
963 		freed = 0;
964 		for (i = 0; i < MAXCPU; i++) {
965 			allocs += mtip->mti_stats[i].mts_numallocs;
966 			frees += mtip->mti_stats[i].mts_numfrees;
967 			alloced += mtip->mti_stats[i].mts_memalloced;
968 			freed += mtip->mti_stats[i].mts_memfreed;
969 		}
970 		db_printf("%18s %12ju %12juK %12ju\n",
971 		    mtp->ks_shortdesc, allocs - frees,
972 		    (alloced - freed + 1023) / 1024, allocs);
973 	}
974 }
975 
976 #if MALLOC_DEBUG_MAXZONES > 1
977 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
978 {
979 	struct malloc_type_internal *mtip;
980 	struct malloc_type *mtp;
981 	u_int subzone;
982 
983 	if (!have_addr) {
984 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
985 		return;
986 	}
987 	mtp = (void *)addr;
988 	if (mtp->ks_magic != M_MAGIC) {
989 		db_printf("Magic %lx does not match expected %x\n",
990 		    mtp->ks_magic, M_MAGIC);
991 		return;
992 	}
993 
994 	mtip = mtp->ks_handle;
995 	subzone = mtip->mti_zone;
996 
997 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
998 		mtip = mtp->ks_handle;
999 		if (mtip->mti_zone != subzone)
1000 			continue;
1001 		db_printf("%s\n", mtp->ks_shortdesc);
1002 	}
1003 }
1004 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1005 #endif /* DDB */
1006 
1007 #ifdef MALLOC_PROFILE
1008 
1009 static int
1010 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1011 {
1012 	int linesize = 64;
1013 	struct sbuf sbuf;
1014 	uint64_t count;
1015 	uint64_t waste;
1016 	uint64_t mem;
1017 	int bufsize;
1018 	int error;
1019 	char *buf;
1020 	int rsize;
1021 	int size;
1022 	int i;
1023 
1024 	bufsize = linesize * (KMEM_ZSIZE + 1);
1025 	bufsize += 128; 	/* For the stats line */
1026 	bufsize += 128; 	/* For the banner line */
1027 	waste = 0;
1028 	mem = 0;
1029 
1030 	buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
1031 	sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
1032 	sbuf_printf(&sbuf,
1033 	    "\n  Size                    Requests  Real Size\n");
1034 	for (i = 0; i < KMEM_ZSIZE; i++) {
1035 		size = i << KMEM_ZSHIFT;
1036 		rsize = kmemzones[kmemsize[i]].kz_size;
1037 		count = (long long unsigned)krequests[i];
1038 
1039 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1040 		    (unsigned long long)count, rsize);
1041 
1042 		if ((rsize * count) > (size * count))
1043 			waste += (rsize * count) - (size * count);
1044 		mem += (rsize * count);
1045 	}
1046 	sbuf_printf(&sbuf,
1047 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1048 	    (unsigned long long)mem, (unsigned long long)waste);
1049 	sbuf_finish(&sbuf);
1050 
1051 	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
1052 
1053 	sbuf_delete(&sbuf);
1054 	free(buf, M_TEMP);
1055 	return (error);
1056 }
1057 
1058 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1059     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1060 #endif /* MALLOC_PROFILE */
1061