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