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