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