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