xref: /freebsd/sys/kern/kern_malloc.c (revision f9218d3d4fd34f082473b3a021c6d4d109fb47cf)
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 #if 0
171 	if (size == 0)
172 		Debugger("zero size malloc");
173 #endif
174 	if (!(flags & M_NOWAIT))
175 		KASSERT(curthread->td_intr_nesting_level == 0,
176 		   ("malloc(M_WAITOK) in interrupt context"));
177 	if (size <= KMEM_ZMAX) {
178 		if (size & KMEM_ZMASK)
179 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
180 		indx = kmemsize[size >> KMEM_ZSHIFT];
181 		zone = kmemzones[indx].kz_zone;
182 #ifdef MALLOC_PROFILE
183 		krequests[size >> KMEM_ZSHIFT]++;
184 #endif
185 		va = uma_zalloc(zone, flags);
186 		mtx_lock(&ksp->ks_mtx);
187 		if (va == NULL)
188 			goto out;
189 
190 		ksp->ks_size |= 1 << indx;
191 		size = zone->uz_size;
192 	} else {
193 		size = roundup(size, PAGE_SIZE);
194 		zone = NULL;
195 		va = uma_large_malloc(size, flags);
196 		mtx_lock(&ksp->ks_mtx);
197 		if (va == NULL)
198 			goto out;
199 	}
200 	ksp->ks_memuse += size;
201 	ksp->ks_inuse++;
202 out:
203 	ksp->ks_calls++;
204 	if (ksp->ks_memuse > ksp->ks_maxused)
205 		ksp->ks_maxused = ksp->ks_memuse;
206 
207 	mtx_unlock(&ksp->ks_mtx);
208 	if (!(flags & M_NOWAIT))
209 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
210 	if (va == NULL) {
211 		t_malloc_fail = time_uptime;
212 	}
213 #ifdef DIAGNOSTIC
214 	if (!(flags & M_ZERO)) {
215 		memset(va, 0x70, osize);
216 	}
217 #endif
218 	return ((void *) va);
219 }
220 
221 /*
222  *	free:
223  *
224  *	Free a block of memory allocated by malloc.
225  *
226  *	This routine may not block.
227  */
228 void
229 free(addr, type)
230 	void *addr;
231 	struct malloc_type *type;
232 {
233 	register struct malloc_type *ksp = type;
234 	uma_slab_t slab;
235 	u_long size;
236 
237 	/* free(NULL, ...) does nothing */
238 	if (addr == NULL)
239 		return;
240 
241 	size = 0;
242 
243 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
244 
245 	if (slab == NULL)
246 		panic("free: address %p(%p) has not been allocated.\n",
247 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
248 
249 
250 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
251 #ifdef INVARIANTS
252 		struct malloc_type **mtp = addr;
253 #endif
254 		size = slab->us_zone->uz_size;
255 #ifdef INVARIANTS
256 		/*
257 		 * Cache a pointer to the malloc_type that most recently freed
258 		 * this memory here.  This way we know who is most likely to
259 		 * have stepped on it later.
260 		 *
261 		 * This code assumes that size is a multiple of 8 bytes for
262 		 * 64 bit machines
263 		 */
264 		mtp = (struct malloc_type **)
265 		    ((unsigned long)mtp & ~UMA_ALIGN_PTR);
266 		mtp += (size - sizeof(struct malloc_type *)) /
267 		    sizeof(struct malloc_type *);
268 		*mtp = type;
269 #endif
270 		uma_zfree_arg(slab->us_zone, addr, slab);
271 	} else {
272 		size = slab->us_size;
273 		uma_large_free(slab);
274 	}
275 	mtx_lock(&ksp->ks_mtx);
276 	ksp->ks_memuse -= size;
277 	ksp->ks_inuse--;
278 	mtx_unlock(&ksp->ks_mtx);
279 }
280 
281 /*
282  *	realloc: change the size of a memory block
283  */
284 void *
285 realloc(addr, size, type, flags)
286 	void *addr;
287 	unsigned long size;
288 	struct malloc_type *type;
289 	int flags;
290 {
291 	uma_slab_t slab;
292 	unsigned long alloc;
293 	void *newaddr;
294 
295 	/* realloc(NULL, ...) is equivalent to malloc(...) */
296 	if (addr == NULL)
297 		return (malloc(size, type, flags));
298 
299 	slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
300 
301 	/* Sanity check */
302 	KASSERT(slab != NULL,
303 	    ("realloc: address %p out of range", (void *)addr));
304 
305 	/* Get the size of the original block */
306 	if (slab->us_zone)
307 		alloc = slab->us_zone->uz_size;
308 	else
309 		alloc = slab->us_size;
310 
311 	/* Reuse the original block if appropriate */
312 	if (size <= alloc
313 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
314 		return (addr);
315 
316 	/* Allocate a new, bigger (or smaller) block */
317 	if ((newaddr = malloc(size, type, flags)) == NULL)
318 		return (NULL);
319 
320 	/* Copy over original contents */
321 	bcopy(addr, newaddr, min(size, alloc));
322 	free(addr, type);
323 	return (newaddr);
324 }
325 
326 /*
327  *	reallocf: same as realloc() but free memory on failure.
328  */
329 void *
330 reallocf(addr, size, type, flags)
331 	void *addr;
332 	unsigned long size;
333 	struct malloc_type *type;
334 	int flags;
335 {
336 	void *mem;
337 
338 	if ((mem = realloc(addr, size, type, flags)) == NULL)
339 		free(addr, type);
340 	return (mem);
341 }
342 
343 /*
344  * Initialize the kernel memory allocator
345  */
346 /* ARGSUSED*/
347 static void
348 kmeminit(dummy)
349 	void *dummy;
350 {
351 	u_int8_t indx;
352 	u_long npg;
353 	u_long mem_size;
354 	int i;
355 
356 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
357 
358 	/*
359 	 * Try to auto-tune the kernel memory size, so that it is
360 	 * more applicable for a wider range of machine sizes.
361 	 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
362 	 * a VM_KMEM_SIZE of 12MB is a fair compromise.  The
363 	 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
364 	 * available, and on an X86 with a total KVA space of 256MB,
365 	 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
366 	 *
367 	 * Note that the kmem_map is also used by the zone allocator,
368 	 * so make sure that there is enough space.
369 	 */
370 	vm_kmem_size = VM_KMEM_SIZE;
371 	mem_size = cnt.v_page_count * PAGE_SIZE;
372 
373 #if defined(VM_KMEM_SIZE_SCALE)
374 	if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
375 		vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
376 #endif
377 
378 #if defined(VM_KMEM_SIZE_MAX)
379 	if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
380 		vm_kmem_size = VM_KMEM_SIZE_MAX;
381 #endif
382 
383 	/* Allow final override from the kernel environment */
384 	TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
385 
386 	/*
387 	 * Limit kmem virtual size to twice the physical memory.
388 	 * This allows for kmem map sparseness, but limits the size
389 	 * to something sane. Be careful to not overflow the 32bit
390 	 * ints while doing the check.
391 	 */
392 	if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE))
393 		vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
394 
395 	/*
396 	 * In mbuf_init(), we set up submaps for mbufs and clusters, in which
397 	 * case we rounddown() (nmbufs * MSIZE) and (nmbclusters * MCLBYTES),
398 	 * respectively. Mathematically, this means that what we do here may
399 	 * amount to slightly more address space than we need for the submaps,
400 	 * but it never hurts to have an extra page in kmem_map.
401 	 */
402 	npg = (nmbufs*MSIZE + nmbclusters*MCLBYTES + vm_kmem_size) / PAGE_SIZE;
403 
404 	kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
405 		(vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
406 	kmem_map->system_map = 1;
407 
408 	uma_startup2();
409 
410 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
411 		int size = kmemzones[indx].kz_size;
412 		char *name = kmemzones[indx].kz_name;
413 
414 		kmemzones[indx].kz_zone = uma_zcreate(name, size,
415 #ifdef INVARIANTS
416 		    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
417 #else
418 		    NULL, NULL, NULL, NULL,
419 #endif
420 		    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
421 
422 		for (;i <= size; i+= KMEM_ZBASE)
423 			kmemsize[i >> KMEM_ZSHIFT] = indx;
424 
425 	}
426 }
427 
428 void
429 malloc_init(data)
430 	void *data;
431 {
432 	struct malloc_type *type = (struct malloc_type *)data;
433 
434 	mtx_lock(&malloc_mtx);
435 	if (type->ks_magic != M_MAGIC)
436 		panic("malloc type lacks magic");
437 
438 	if (cnt.v_page_count == 0)
439 		panic("malloc_init not allowed before vm init");
440 
441 	if (type->ks_next != NULL)
442 		return;
443 
444 	type->ks_next = kmemstatistics;
445 	kmemstatistics = type;
446 	mtx_init(&type->ks_mtx, type->ks_shortdesc, "Malloc Stats", MTX_DEF);
447 	mtx_unlock(&malloc_mtx);
448 }
449 
450 void
451 malloc_uninit(data)
452 	void *data;
453 {
454 	struct malloc_type *type = (struct malloc_type *)data;
455 	struct malloc_type *t;
456 
457 	mtx_lock(&malloc_mtx);
458 	mtx_lock(&type->ks_mtx);
459 	if (type->ks_magic != M_MAGIC)
460 		panic("malloc type lacks magic");
461 
462 	if (cnt.v_page_count == 0)
463 		panic("malloc_uninit not allowed before vm init");
464 
465 	if (type == kmemstatistics)
466 		kmemstatistics = type->ks_next;
467 	else {
468 		for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
469 			if (t->ks_next == type) {
470 				t->ks_next = type->ks_next;
471 				break;
472 			}
473 		}
474 	}
475 	type->ks_next = NULL;
476 	mtx_destroy(&type->ks_mtx);
477 	mtx_unlock(&malloc_mtx);
478 }
479 
480 static int
481 sysctl_kern_malloc(SYSCTL_HANDLER_ARGS)
482 {
483 	struct malloc_type *type;
484 	int linesize = 128;
485 	int curline;
486 	int bufsize;
487 	int first;
488 	int error;
489 	char *buf;
490 	char *p;
491 	int cnt;
492 	int len;
493 	int i;
494 
495 	cnt = 0;
496 
497 	mtx_lock(&malloc_mtx);
498 	for (type = kmemstatistics; type != NULL; type = type->ks_next)
499 		cnt++;
500 
501 	mtx_unlock(&malloc_mtx);
502 	bufsize = linesize * (cnt + 1);
503 	p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
504 	mtx_lock(&malloc_mtx);
505 
506 	len = snprintf(p, linesize,
507 	    "\n        Type  InUse MemUse HighUse Requests  Size(s)\n");
508 	p += len;
509 
510 	for (type = kmemstatistics; cnt != 0 && type != NULL;
511 	    type = type->ks_next, cnt--) {
512 		if (type->ks_calls == 0)
513 			continue;
514 
515 		curline = linesize - 2;	/* Leave room for the \n */
516 		len = snprintf(p, curline, "%13s%6lu%6luK%7luK%9llu",
517 			type->ks_shortdesc,
518 			type->ks_inuse,
519 			(type->ks_memuse + 1023) / 1024,
520 			(type->ks_maxused + 1023) / 1024,
521 			(long long unsigned)type->ks_calls);
522 		curline -= len;
523 		p += len;
524 
525 		first = 1;
526 		for (i = 0; i < sizeof(kmemzones) / sizeof(kmemzones[0]) - 1;
527 		    i++) {
528 			if (type->ks_size & (1 << i)) {
529 				if (first)
530 					len = snprintf(p, curline, "  ");
531 				else
532 					len = snprintf(p, curline, ",");
533 				curline -= len;
534 				p += len;
535 
536 				len = snprintf(p, curline,
537 				    "%s", kmemzones[i].kz_name);
538 				curline -= len;
539 				p += len;
540 
541 				first = 0;
542 			}
543 		}
544 
545 		len = snprintf(p, 2, "\n");
546 		p += len;
547 	}
548 
549 	mtx_unlock(&malloc_mtx);
550 	error = SYSCTL_OUT(req, buf, p - buf);
551 
552 	free(buf, M_TEMP);
553 	return (error);
554 }
555 
556 SYSCTL_OID(_kern, OID_AUTO, malloc, CTLTYPE_STRING|CTLFLAG_RD,
557     NULL, 0, sysctl_kern_malloc, "A", "Malloc Stats");
558 
559 #ifdef MALLOC_PROFILE
560 
561 static int
562 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
563 {
564 	int linesize = 64;
565 	uint64_t count;
566 	uint64_t waste;
567 	uint64_t mem;
568 	int bufsize;
569 	int error;
570 	char *buf;
571 	int rsize;
572 	int size;
573 	char *p;
574 	int len;
575 	int i;
576 
577 	bufsize = linesize * (KMEM_ZSIZE + 1);
578 	bufsize += 128; 	/* For the stats line */
579 	bufsize += 128; 	/* For the banner line */
580 	waste = 0;
581 	mem = 0;
582 
583 	p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
584 	len = snprintf(p, bufsize,
585 	    "\n  Size                    Requests  Real Size\n");
586 	bufsize -= len;
587 	p += len;
588 
589 	for (i = 0; i < KMEM_ZSIZE; i++) {
590 		size = i << KMEM_ZSHIFT;
591 		rsize = kmemzones[kmemsize[i]].kz_size;
592 		count = (long long unsigned)krequests[i];
593 
594 		len = snprintf(p, bufsize, "%6d%28llu%11d\n",
595 		    size, (unsigned long long)count, rsize);
596 		bufsize -= len;
597 		p += len;
598 
599 		if ((rsize * count) > (size * count))
600 			waste += (rsize * count) - (size * count);
601 		mem += (rsize * count);
602 	}
603 
604 	len = snprintf(p, bufsize,
605 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
606 	    (unsigned long long)mem, (unsigned long long)waste);
607 	p += len;
608 
609 	error = SYSCTL_OUT(req, buf, p - buf);
610 
611 	free(buf, M_TEMP);
612 	return (error);
613 }
614 
615 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
616     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
617 #endif /* MALLOC_PROFILE */
618