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