xref: /freebsd/sys/kern/kern_malloc.c (revision cff5befbba31006db8b0c3fff0bb3b2ac38c8f88)
1 /*
2  * Copyright (c) 1987, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)kern_malloc.c	8.3 (Berkeley) 1/4/94
34  * $FreeBSD$
35  */
36 
37 #include "opt_vm.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/lock.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/mutex.h>
46 #include <sys/vmmeter.h>
47 #include <sys/proc.h>
48 #include <sys/sysctl.h>
49 #include <sys/time.h>
50 
51 #include <vm/vm.h>
52 #include <vm/pmap.h>
53 #include <vm/vm_param.h>
54 #include <vm/vm_kern.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_map.h>
57 #include <vm/vm_page.h>
58 #include <vm/uma.h>
59 #include <vm/uma_int.h>
60 #include <vm/uma_dbg.h>
61 
62 #if defined(INVARIANTS) && defined(__i386__)
63 #include <machine/cpu.h>
64 #endif
65 
66 /*
67  * When realloc() is called, if the new size is sufficiently smaller than
68  * the old size, realloc() will allocate a new, smaller block to avoid
69  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
70  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
71  */
72 #ifndef REALLOC_FRACTION
73 #define	REALLOC_FRACTION	1	/* new block if <= half the size */
74 #endif
75 
76 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
77 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
78 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
79 
80 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
81 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
82 
83 static void kmeminit(void *);
84 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
85 
86 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
87 
88 static struct malloc_type *kmemstatistics;
89 static char *kmembase;
90 static char *kmemlimit;
91 
92 #define KMEM_ZSHIFT	4
93 #define KMEM_ZBASE	16
94 #define KMEM_ZMASK	(KMEM_ZBASE - 1)
95 
96 #define KMEM_ZMAX	65536
97 #define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
98 static u_int8_t kmemsize[KMEM_ZSIZE + 1];
99 
100 /* These won't be powers of two for long */
101 struct {
102 	int kz_size;
103 	char *kz_name;
104 	uma_zone_t kz_zone;
105 } kmemzones[] = {
106 	{16, "16", NULL},
107 	{32, "32", NULL},
108 	{64, "64", NULL},
109 	{128, "128", NULL},
110 	{256, "256", NULL},
111 	{512, "512", NULL},
112 	{1024, "1024", NULL},
113 	{2048, "2048", NULL},
114 	{4096, "4096", NULL},
115 	{8192, "8192", NULL},
116 	{16384, "16384", NULL},
117 	{32768, "32768", NULL},
118 	{65536, "65536", NULL},
119 	{0, NULL},
120 };
121 
122 u_int vm_kmem_size;
123 
124 /*
125  * The malloc_mtx protects the kmemstatistics linked list.
126  */
127 
128 struct mtx malloc_mtx;
129 
130 #ifdef MALLOC_PROFILE
131 uint64_t krequests[KMEM_ZSIZE + 1];
132 
133 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
134 #endif
135 
136 static int sysctl_kern_malloc(SYSCTL_HANDLER_ARGS);
137 
138 /* time_uptime of last malloc(9) failure */
139 static time_t t_malloc_fail;
140 
141 int
142 malloc_last_fail(void)
143 {
144 
145 	return (time_uptime - t_malloc_fail);
146 }
147 
148 /*
149  *	malloc:
150  *
151  *	Allocate a block of memory.
152  *
153  *	If M_NOWAIT is set, this routine will not block and return NULL if
154  *	the allocation fails.
155  */
156 void *
157 malloc(size, type, flags)
158 	unsigned long size;
159 	struct malloc_type *type;
160 	int flags;
161 {
162 	int indx;
163 	caddr_t va;
164 	uma_zone_t zone;
165 #ifdef DIAGNOSTIC
166 	unsigned long osize = size;
167 #endif
168 	register struct malloc_type *ksp = type;
169 
170 #ifdef INVARIANTS
171 	/*
172 	 * To make sure that WAITOK or NOWAIT is set, but not more than
173 	 * one, and check against the API botches that are common.
174 	 */
175 	indx = flags & (M_WAITOK | M_NOWAIT | M_DONTWAIT | M_TRYWAIT);
176 	if (indx != M_NOWAIT && indx != M_WAITOK) {
177 		static	struct timeval lasterr;
178 		static	int curerr, once;
179 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
180 			printf("Bad malloc flags: %x\n", indx);
181 			backtrace();
182 			flags |= M_WAITOK;
183 			once++;
184 		}
185 	}
186 #endif
187 #if 0
188 	if (size == 0)
189 		Debugger("zero size malloc");
190 #endif
191 	if (flags & M_WAITOK)
192 		KASSERT(curthread->td_intr_nesting_level == 0,
193 		   ("malloc(M_WAITOK) in interrupt context"));
194 	if (size <= KMEM_ZMAX) {
195 		if (size & KMEM_ZMASK)
196 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
197 		indx = kmemsize[size >> KMEM_ZSHIFT];
198 		zone = kmemzones[indx].kz_zone;
199 #ifdef MALLOC_PROFILE
200 		krequests[size >> KMEM_ZSHIFT]++;
201 #endif
202 		va = uma_zalloc(zone, flags);
203 		mtx_lock(&ksp->ks_mtx);
204 		if (va == NULL)
205 			goto out;
206 
207 		ksp->ks_size |= 1 << indx;
208 		size = zone->uz_size;
209 	} else {
210 		size = roundup(size, PAGE_SIZE);
211 		zone = NULL;
212 		va = uma_large_malloc(size, flags);
213 		mtx_lock(&ksp->ks_mtx);
214 		if (va == NULL)
215 			goto out;
216 	}
217 	ksp->ks_memuse += size;
218 	ksp->ks_inuse++;
219 out:
220 	ksp->ks_calls++;
221 	if (ksp->ks_memuse > ksp->ks_maxused)
222 		ksp->ks_maxused = ksp->ks_memuse;
223 
224 	mtx_unlock(&ksp->ks_mtx);
225 	if (!(flags & M_NOWAIT))
226 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
227 	if (va == NULL) {
228 		t_malloc_fail = time_uptime;
229 	}
230 #ifdef DIAGNOSTIC
231 	if (!(flags & M_ZERO)) {
232 		memset(va, 0x70, osize);
233 	}
234 #endif
235 	return ((void *) va);
236 }
237 
238 /*
239  *	free:
240  *
241  *	Free a block of memory allocated by malloc.
242  *
243  *	This routine may not block.
244  */
245 void
246 free(addr, type)
247 	void *addr;
248 	struct malloc_type *type;
249 {
250 	register struct malloc_type *ksp = type;
251 	uma_slab_t slab;
252 	u_long size;
253 
254 	/* free(NULL, ...) does nothing */
255 	if (addr == NULL)
256 		return;
257 
258 	size = 0;
259 
260 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
261 
262 	if (slab == NULL)
263 		panic("free: address %p(%p) has not been allocated.\n",
264 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
265 
266 
267 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
268 #ifdef INVARIANTS
269 		struct malloc_type **mtp = addr;
270 #endif
271 		size = slab->us_zone->uz_size;
272 #ifdef INVARIANTS
273 		/*
274 		 * Cache a pointer to the malloc_type that most recently freed
275 		 * this memory here.  This way we know who is most likely to
276 		 * have stepped on it later.
277 		 *
278 		 * This code assumes that size is a multiple of 8 bytes for
279 		 * 64 bit machines
280 		 */
281 		mtp = (struct malloc_type **)
282 		    ((unsigned long)mtp & ~UMA_ALIGN_PTR);
283 		mtp += (size - sizeof(struct malloc_type *)) /
284 		    sizeof(struct malloc_type *);
285 		*mtp = type;
286 #endif
287 		uma_zfree_arg(slab->us_zone, addr, slab);
288 	} else {
289 		size = slab->us_size;
290 		uma_large_free(slab);
291 	}
292 	mtx_lock(&ksp->ks_mtx);
293 	ksp->ks_memuse -= size;
294 	ksp->ks_inuse--;
295 	mtx_unlock(&ksp->ks_mtx);
296 }
297 
298 /*
299  *	realloc: change the size of a memory block
300  */
301 void *
302 realloc(addr, size, type, flags)
303 	void *addr;
304 	unsigned long size;
305 	struct malloc_type *type;
306 	int flags;
307 {
308 	uma_slab_t slab;
309 	unsigned long alloc;
310 	void *newaddr;
311 
312 	/* realloc(NULL, ...) is equivalent to malloc(...) */
313 	if (addr == NULL)
314 		return (malloc(size, type, flags));
315 
316 	slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
317 
318 	/* Sanity check */
319 	KASSERT(slab != NULL,
320 	    ("realloc: address %p out of range", (void *)addr));
321 
322 	/* Get the size of the original block */
323 	if (slab->us_zone)
324 		alloc = slab->us_zone->uz_size;
325 	else
326 		alloc = slab->us_size;
327 
328 	/* Reuse the original block if appropriate */
329 	if (size <= alloc
330 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
331 		return (addr);
332 
333 	/* Allocate a new, bigger (or smaller) block */
334 	if ((newaddr = malloc(size, type, flags)) == NULL)
335 		return (NULL);
336 
337 	/* Copy over original contents */
338 	bcopy(addr, newaddr, min(size, alloc));
339 	free(addr, type);
340 	return (newaddr);
341 }
342 
343 /*
344  *	reallocf: same as realloc() but free memory on failure.
345  */
346 void *
347 reallocf(addr, size, type, flags)
348 	void *addr;
349 	unsigned long size;
350 	struct malloc_type *type;
351 	int flags;
352 {
353 	void *mem;
354 
355 	if ((mem = realloc(addr, size, type, flags)) == NULL)
356 		free(addr, type);
357 	return (mem);
358 }
359 
360 /*
361  * Initialize the kernel memory allocator
362  */
363 /* ARGSUSED*/
364 static void
365 kmeminit(dummy)
366 	void *dummy;
367 {
368 	u_int8_t indx;
369 	u_long npg;
370 	u_long mem_size;
371 	int i;
372 
373 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
374 
375 	/*
376 	 * Try to auto-tune the kernel memory size, so that it is
377 	 * more applicable for a wider range of machine sizes.
378 	 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
379 	 * a VM_KMEM_SIZE of 12MB is a fair compromise.  The
380 	 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
381 	 * available, and on an X86 with a total KVA space of 256MB,
382 	 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
383 	 *
384 	 * Note that the kmem_map is also used by the zone allocator,
385 	 * so make sure that there is enough space.
386 	 */
387 	vm_kmem_size = VM_KMEM_SIZE;
388 	mem_size = cnt.v_page_count * PAGE_SIZE;
389 
390 #if defined(VM_KMEM_SIZE_SCALE)
391 	if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
392 		vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
393 #endif
394 
395 #if defined(VM_KMEM_SIZE_MAX)
396 	if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
397 		vm_kmem_size = VM_KMEM_SIZE_MAX;
398 #endif
399 
400 	/* Allow final override from the kernel environment */
401 	TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
402 
403 	/*
404 	 * Limit kmem virtual size to twice the physical memory.
405 	 * This allows for kmem map sparseness, but limits the size
406 	 * to something sane. Be careful to not overflow the 32bit
407 	 * ints while doing the check.
408 	 */
409 	if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE))
410 		vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
411 
412 	/*
413 	 * In mbuf_init(), we set up submaps for mbufs and clusters, in which
414 	 * case we rounddown() (nmbufs * MSIZE) and (nmbclusters * MCLBYTES),
415 	 * respectively. Mathematically, this means that what we do here may
416 	 * amount to slightly more address space than we need for the submaps,
417 	 * but it never hurts to have an extra page in kmem_map.
418 	 */
419 	npg = (nmbufs*MSIZE + nmbclusters*MCLBYTES + vm_kmem_size) / PAGE_SIZE;
420 
421 	kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
422 		(vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
423 	kmem_map->system_map = 1;
424 
425 	uma_startup2();
426 
427 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
428 		int size = kmemzones[indx].kz_size;
429 		char *name = kmemzones[indx].kz_name;
430 
431 		kmemzones[indx].kz_zone = uma_zcreate(name, size,
432 #ifdef INVARIANTS
433 		    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
434 #else
435 		    NULL, NULL, NULL, NULL,
436 #endif
437 		    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
438 
439 		for (;i <= size; i+= KMEM_ZBASE)
440 			kmemsize[i >> KMEM_ZSHIFT] = indx;
441 
442 	}
443 }
444 
445 void
446 malloc_init(data)
447 	void *data;
448 {
449 	struct malloc_type *type = (struct malloc_type *)data;
450 
451 	mtx_lock(&malloc_mtx);
452 	if (type->ks_magic != M_MAGIC)
453 		panic("malloc type lacks magic");
454 
455 	if (cnt.v_page_count == 0)
456 		panic("malloc_init not allowed before vm init");
457 
458 	if (type->ks_next != NULL)
459 		return;
460 
461 	type->ks_next = kmemstatistics;
462 	kmemstatistics = type;
463 	mtx_init(&type->ks_mtx, type->ks_shortdesc, "Malloc Stats", MTX_DEF);
464 	mtx_unlock(&malloc_mtx);
465 }
466 
467 void
468 malloc_uninit(data)
469 	void *data;
470 {
471 	struct malloc_type *type = (struct malloc_type *)data;
472 	struct malloc_type *t;
473 
474 	mtx_lock(&malloc_mtx);
475 	mtx_lock(&type->ks_mtx);
476 	if (type->ks_magic != M_MAGIC)
477 		panic("malloc type lacks magic");
478 
479 	if (cnt.v_page_count == 0)
480 		panic("malloc_uninit not allowed before vm init");
481 
482 	if (type == kmemstatistics)
483 		kmemstatistics = type->ks_next;
484 	else {
485 		for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
486 			if (t->ks_next == type) {
487 				t->ks_next = type->ks_next;
488 				break;
489 			}
490 		}
491 	}
492 	type->ks_next = NULL;
493 	mtx_destroy(&type->ks_mtx);
494 	mtx_unlock(&malloc_mtx);
495 }
496 
497 static int
498 sysctl_kern_malloc(SYSCTL_HANDLER_ARGS)
499 {
500 	struct malloc_type *type;
501 	int linesize = 128;
502 	int curline;
503 	int bufsize;
504 	int first;
505 	int error;
506 	char *buf;
507 	char *p;
508 	int cnt;
509 	int len;
510 	int i;
511 
512 	cnt = 0;
513 
514 	mtx_lock(&malloc_mtx);
515 	for (type = kmemstatistics; type != NULL; type = type->ks_next)
516 		cnt++;
517 
518 	mtx_unlock(&malloc_mtx);
519 	bufsize = linesize * (cnt + 1);
520 	p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
521 	mtx_lock(&malloc_mtx);
522 
523 	len = snprintf(p, linesize,
524 	    "\n        Type  InUse MemUse HighUse Requests  Size(s)\n");
525 	p += len;
526 
527 	for (type = kmemstatistics; cnt != 0 && type != NULL;
528 	    type = type->ks_next, cnt--) {
529 		if (type->ks_calls == 0)
530 			continue;
531 
532 		curline = linesize - 2;	/* Leave room for the \n */
533 		len = snprintf(p, curline, "%13s%6lu%6luK%7luK%9llu",
534 			type->ks_shortdesc,
535 			type->ks_inuse,
536 			(type->ks_memuse + 1023) / 1024,
537 			(type->ks_maxused + 1023) / 1024,
538 			(long long unsigned)type->ks_calls);
539 		curline -= len;
540 		p += len;
541 
542 		first = 1;
543 		for (i = 0; i < sizeof(kmemzones) / sizeof(kmemzones[0]) - 1;
544 		    i++) {
545 			if (type->ks_size & (1 << i)) {
546 				if (first)
547 					len = snprintf(p, curline, "  ");
548 				else
549 					len = snprintf(p, curline, ",");
550 				curline -= len;
551 				p += len;
552 
553 				len = snprintf(p, curline,
554 				    "%s", kmemzones[i].kz_name);
555 				curline -= len;
556 				p += len;
557 
558 				first = 0;
559 			}
560 		}
561 
562 		len = snprintf(p, 2, "\n");
563 		p += len;
564 	}
565 
566 	mtx_unlock(&malloc_mtx);
567 	error = SYSCTL_OUT(req, buf, p - buf);
568 
569 	free(buf, M_TEMP);
570 	return (error);
571 }
572 
573 SYSCTL_OID(_kern, OID_AUTO, malloc, CTLTYPE_STRING|CTLFLAG_RD,
574     NULL, 0, sysctl_kern_malloc, "A", "Malloc Stats");
575 
576 #ifdef MALLOC_PROFILE
577 
578 static int
579 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
580 {
581 	int linesize = 64;
582 	uint64_t count;
583 	uint64_t waste;
584 	uint64_t mem;
585 	int bufsize;
586 	int error;
587 	char *buf;
588 	int rsize;
589 	int size;
590 	char *p;
591 	int len;
592 	int i;
593 
594 	bufsize = linesize * (KMEM_ZSIZE + 1);
595 	bufsize += 128; 	/* For the stats line */
596 	bufsize += 128; 	/* For the banner line */
597 	waste = 0;
598 	mem = 0;
599 
600 	p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
601 	len = snprintf(p, bufsize,
602 	    "\n  Size                    Requests  Real Size\n");
603 	bufsize -= len;
604 	p += len;
605 
606 	for (i = 0; i < KMEM_ZSIZE; i++) {
607 		size = i << KMEM_ZSHIFT;
608 		rsize = kmemzones[kmemsize[i]].kz_size;
609 		count = (long long unsigned)krequests[i];
610 
611 		len = snprintf(p, bufsize, "%6d%28llu%11d\n",
612 		    size, (unsigned long long)count, rsize);
613 		bufsize -= len;
614 		p += len;
615 
616 		if ((rsize * count) > (size * count))
617 			waste += (rsize * count) - (size * count);
618 		mem += (rsize * count);
619 	}
620 
621 	len = snprintf(p, bufsize,
622 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
623 	    (unsigned long long)mem, (unsigned long long)waste);
624 	p += len;
625 
626 	error = SYSCTL_OUT(req, buf, p - buf);
627 
628 	free(buf, M_TEMP);
629 	return (error);
630 }
631 
632 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
633     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
634 #endif /* MALLOC_PROFILE */
635