xref: /freebsd/sys/kern/kern_malloc.c (revision b40ce4165d5eb3a5de1515245055350ae3dbab8e)
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 
49 #include <vm/vm.h>
50 #include <vm/vm_param.h>
51 #include <vm/vm_kern.h>
52 #include <vm/vm_extern.h>
53 #include <vm/pmap.h>
54 #include <vm/vm_map.h>
55 
56 #if defined(INVARIANTS) && defined(__i386__)
57 #include <machine/cpu.h>
58 #endif
59 
60 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
61 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
62 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
63 
64 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
65 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
66 
67 static void kmeminit __P((void *));
68 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
69 
70 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
71 
72 static struct malloc_type *kmemstatistics;
73 static struct kmembuckets bucket[MINBUCKET + 16];
74 static struct kmemusage *kmemusage;
75 static char *kmembase;
76 static char *kmemlimit;
77 
78 static struct mtx malloc_mtx;
79 
80 u_int vm_kmem_size;
81 
82 #ifdef INVARIANTS
83 /*
84  * This structure provides a set of masks to catch unaligned frees.
85  */
86 static long addrmask[] = { 0,
87 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
88 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
89 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
90 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
91 };
92 
93 /*
94  * The WEIRD_ADDR is used as known text to copy into free objects so
95  * that modifications after frees can be detected.
96  */
97 #define WEIRD_ADDR	0xdeadc0de
98 #define MAX_COPY	64
99 
100 /*
101  * Normally the first word of the structure is used to hold the list
102  * pointer for free objects. However, when running with diagnostics,
103  * we use the third and fourth fields, so as to catch modifications
104  * in the most commonly trashed first two words.
105  */
106 struct freelist {
107 	long	spare0;
108 	struct malloc_type *type;
109 	long	spare1;
110 	caddr_t	next;
111 };
112 #else /* !INVARIANTS */
113 struct freelist {
114 	caddr_t	next;
115 };
116 #endif /* INVARIANTS */
117 
118 /*
119  *	malloc:
120  *
121  *	Allocate a block of memory.
122  *
123  *	If M_NOWAIT is set, this routine will not block and return NULL if
124  *	the allocation fails.
125  */
126 void *
127 malloc(size, type, flags)
128 	unsigned long size;
129 	struct malloc_type *type;
130 	int flags;
131 {
132 	register struct kmembuckets *kbp;
133 	register struct kmemusage *kup;
134 	register struct freelist *freep;
135 	long indx, npg, allocsize;
136 	int s;
137 	caddr_t va, cp, savedlist;
138 #ifdef INVARIANTS
139 	long *end, *lp;
140 	int copysize;
141 	const char *savedtype;
142 #endif
143 	register struct malloc_type *ksp = type;
144 
145 #if defined(INVARIANTS)
146 	if (flags == M_WAITOK)
147 		KASSERT(curthread->td_intr_nesting_level == 0,
148 		   ("malloc(M_WAITOK) in interrupt context"));
149 #endif
150 	indx = BUCKETINDX(size);
151 	kbp = &bucket[indx];
152 	s = splmem();
153 	mtx_lock(&malloc_mtx);
154 	while (ksp->ks_memuse >= ksp->ks_limit) {
155 		if (flags & M_NOWAIT) {
156 			splx(s);
157 			mtx_unlock(&malloc_mtx);
158 			return ((void *) NULL);
159 		}
160 		if (ksp->ks_limblocks < 65535)
161 			ksp->ks_limblocks++;
162 		msleep((caddr_t)ksp, &malloc_mtx, PSWP+2, type->ks_shortdesc,
163 		    0);
164 	}
165 	ksp->ks_size |= 1 << indx;
166 #ifdef INVARIANTS
167 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
168 #endif
169 	if (kbp->kb_next == NULL) {
170 		kbp->kb_last = NULL;
171 		if (size > MAXALLOCSAVE)
172 			allocsize = roundup(size, PAGE_SIZE);
173 		else
174 			allocsize = 1 << indx;
175 		npg = btoc(allocsize);
176 
177 		mtx_unlock(&malloc_mtx);
178 		va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg), flags);
179 
180 		if (va == NULL) {
181 			splx(s);
182 			return ((void *) NULL);
183 		}
184 		/*
185 		 * Enter malloc_mtx after the error check to avoid having to
186 		 * immediately exit it again if there is an error.
187 		 */
188 		mtx_lock(&malloc_mtx);
189 
190 		kbp->kb_total += kbp->kb_elmpercl;
191 		kup = btokup(va);
192 		kup->ku_indx = indx;
193 		if (allocsize > MAXALLOCSAVE) {
194 			if (npg > 65535)
195 				panic("malloc: allocation too large");
196 			kup->ku_pagecnt = npg;
197 			ksp->ks_memuse += allocsize;
198 			goto out;
199 		}
200 		kup->ku_freecnt = kbp->kb_elmpercl;
201 		kbp->kb_totalfree += kbp->kb_elmpercl;
202 		/*
203 		 * Just in case we blocked while allocating memory,
204 		 * and someone else also allocated memory for this
205 		 * bucket, don't assume the list is still empty.
206 		 */
207 		savedlist = kbp->kb_next;
208 		kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
209 		for (;;) {
210 			freep = (struct freelist *)cp;
211 #ifdef INVARIANTS
212 			/*
213 			 * Copy in known text to detect modification
214 			 * after freeing.
215 			 */
216 			end = (long *)&cp[copysize];
217 			for (lp = (long *)cp; lp < end; lp++)
218 				*lp = WEIRD_ADDR;
219 			freep->type = M_FREE;
220 #endif /* INVARIANTS */
221 			if (cp <= va)
222 				break;
223 			cp -= allocsize;
224 			freep->next = cp;
225 		}
226 		freep->next = savedlist;
227 		if (kbp->kb_last == NULL)
228 			kbp->kb_last = (caddr_t)freep;
229 	}
230 	va = kbp->kb_next;
231 	kbp->kb_next = ((struct freelist *)va)->next;
232 #ifdef INVARIANTS
233 	freep = (struct freelist *)va;
234 	savedtype = (const char *) freep->type->ks_shortdesc;
235 	freep->type = (struct malloc_type *)WEIRD_ADDR;
236 	if ((intptr_t)(void *)&freep->next & 0x2)
237 		freep->next = (caddr_t)((WEIRD_ADDR >> 16)|(WEIRD_ADDR << 16));
238 	else
239 		freep->next = (caddr_t)WEIRD_ADDR;
240 	end = (long *)&va[copysize];
241 	for (lp = (long *)va; lp < end; lp++) {
242 		if (*lp == WEIRD_ADDR)
243 			continue;
244 		printf("%s %ld of object %p size %lu %s %s (0x%lx != 0x%lx)\n",
245 			"Data modified on freelist: word",
246 			(long)(lp - (long *)va), (void *)va, size,
247 			"previous type", savedtype, *lp, (u_long)WEIRD_ADDR);
248 		break;
249 	}
250 	freep->spare0 = 0;
251 #endif /* INVARIANTS */
252 	kup = btokup(va);
253 	if (kup->ku_indx != indx)
254 		panic("malloc: wrong bucket");
255 	if (kup->ku_freecnt == 0)
256 		panic("malloc: lost data");
257 	kup->ku_freecnt--;
258 	kbp->kb_totalfree--;
259 	ksp->ks_memuse += 1 << indx;
260 out:
261 	kbp->kb_calls++;
262 	ksp->ks_inuse++;
263 	ksp->ks_calls++;
264 	if (ksp->ks_memuse > ksp->ks_maxused)
265 		ksp->ks_maxused = ksp->ks_memuse;
266 	splx(s);
267 	mtx_unlock(&malloc_mtx);
268 	/* XXX: Do idle pre-zeroing.  */
269 	if (va != NULL && (flags & M_ZERO))
270 		bzero(va, size);
271 	return ((void *) va);
272 }
273 
274 /*
275  *	free:
276  *
277  *	Free a block of memory allocated by malloc.
278  *
279  *	This routine may not block.
280  */
281 void
282 free(addr, type)
283 	void *addr;
284 	struct malloc_type *type;
285 {
286 	register struct kmembuckets *kbp;
287 	register struct kmemusage *kup;
288 	register struct freelist *freep;
289 	long size;
290 	int s;
291 #ifdef INVARIANTS
292 	struct freelist *fp;
293 	long *end, *lp, alloc, copysize;
294 #endif
295 	register struct malloc_type *ksp = type;
296 
297 	KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
298 	    ("free: address %p out of range", (void *)addr));
299 	kup = btokup(addr);
300 	size = 1 << kup->ku_indx;
301 	kbp = &bucket[kup->ku_indx];
302 	s = splmem();
303 	mtx_lock(&malloc_mtx);
304 #ifdef INVARIANTS
305 	/*
306 	 * Check for returns of data that do not point to the
307 	 * beginning of the allocation.
308 	 */
309 	if (size > PAGE_SIZE)
310 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
311 	else
312 		alloc = addrmask[kup->ku_indx];
313 	if (((uintptr_t)(void *)addr & alloc) != 0)
314 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
315 		    (void *)addr, size, type->ks_shortdesc, alloc);
316 #endif /* INVARIANTS */
317 	if (size > MAXALLOCSAVE) {
318 		mtx_unlock(&malloc_mtx);
319 		kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
320 		mtx_lock(&malloc_mtx);
321 
322 		size = kup->ku_pagecnt << PAGE_SHIFT;
323 		ksp->ks_memuse -= size;
324 		kup->ku_indx = 0;
325 		kup->ku_pagecnt = 0;
326 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
327 		    ksp->ks_memuse < ksp->ks_limit)
328 			wakeup((caddr_t)ksp);
329 		ksp->ks_inuse--;
330 		kbp->kb_total -= 1;
331 		splx(s);
332 		mtx_unlock(&malloc_mtx);
333 		return;
334 	}
335 	freep = (struct freelist *)addr;
336 #ifdef INVARIANTS
337 	/*
338 	 * Check for multiple frees. Use a quick check to see if
339 	 * it looks free before laboriously searching the freelist.
340 	 */
341 	if (freep->spare0 == WEIRD_ADDR) {
342 		fp = (struct freelist *)kbp->kb_next;
343 		while (fp) {
344 			if (fp->spare0 != WEIRD_ADDR)
345 				panic("free: free item %p modified", fp);
346 			else if (addr == (caddr_t)fp)
347 				panic("free: multiple freed item %p", addr);
348 			fp = (struct freelist *)fp->next;
349 		}
350 	}
351 	/*
352 	 * Copy in known text to detect modification after freeing
353 	 * and to make it look free. Also, save the type being freed
354 	 * so we can list likely culprit if modification is detected
355 	 * when the object is reallocated.
356 	 */
357 	copysize = size < MAX_COPY ? size : MAX_COPY;
358 	end = (long *)&((caddr_t)addr)[copysize];
359 	for (lp = (long *)addr; lp < end; lp++)
360 		*lp = WEIRD_ADDR;
361 	freep->type = type;
362 #endif /* INVARIANTS */
363 	kup->ku_freecnt++;
364 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
365 		if (kup->ku_freecnt > kbp->kb_elmpercl)
366 			panic("free: multiple frees");
367 		else if (kbp->kb_totalfree > kbp->kb_highwat)
368 			kbp->kb_couldfree++;
369 	}
370 	kbp->kb_totalfree++;
371 	ksp->ks_memuse -= size;
372 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
373 	    ksp->ks_memuse < ksp->ks_limit)
374 		wakeup((caddr_t)ksp);
375 	ksp->ks_inuse--;
376 #ifdef OLD_MALLOC_MEMORY_POLICY
377 	if (kbp->kb_next == NULL)
378 		kbp->kb_next = addr;
379 	else
380 		((struct freelist *)kbp->kb_last)->next = addr;
381 	freep->next = NULL;
382 	kbp->kb_last = addr;
383 #else
384 	/*
385 	 * Return memory to the head of the queue for quick reuse.  This
386 	 * can improve performance by improving the probability of the
387 	 * item being in the cache when it is reused.
388 	 */
389 	if (kbp->kb_next == NULL) {
390 		kbp->kb_next = addr;
391 		kbp->kb_last = addr;
392 		freep->next = NULL;
393 	} else {
394 		freep->next = kbp->kb_next;
395 		kbp->kb_next = addr;
396 	}
397 #endif
398 	splx(s);
399 	mtx_unlock(&malloc_mtx);
400 }
401 
402 /*
403  * Initialize the kernel memory allocator
404  */
405 /* ARGSUSED*/
406 static void
407 kmeminit(dummy)
408 	void *dummy;
409 {
410 	register long indx;
411 	u_long npg;
412 	u_long mem_size;
413 
414 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
415 #error "kmeminit: MAXALLOCSAVE not power of 2"
416 #endif
417 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
418 #error "kmeminit: MAXALLOCSAVE too big"
419 #endif
420 #if	(MAXALLOCSAVE < PAGE_SIZE)
421 #error "kmeminit: MAXALLOCSAVE too small"
422 #endif
423 
424 	mtx_init(&malloc_mtx, "malloc", MTX_DEF);
425 
426 	/*
427 	 * Try to auto-tune the kernel memory size, so that it is
428 	 * more applicable for a wider range of machine sizes.
429 	 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
430 	 * a VM_KMEM_SIZE of 12MB is a fair compromise.  The
431 	 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
432 	 * available, and on an X86 with a total KVA space of 256MB,
433 	 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
434 	 *
435 	 * Note that the kmem_map is also used by the zone allocator,
436 	 * so make sure that there is enough space.
437 	 */
438 	vm_kmem_size = VM_KMEM_SIZE;
439 	mem_size = cnt.v_page_count * PAGE_SIZE;
440 
441 #if defined(VM_KMEM_SIZE_SCALE)
442 	if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
443 		vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
444 #endif
445 
446 #if defined(VM_KMEM_SIZE_MAX)
447 	if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
448 		vm_kmem_size = VM_KMEM_SIZE_MAX;
449 #endif
450 
451 	/* Allow final override from the kernel environment */
452 	TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
453 
454 	/*
455 	 * Limit kmem virtual size to twice the physical memory.
456 	 * This allows for kmem map sparseness, but limits the size
457 	 * to something sane. Be careful to not overflow the 32bit
458 	 * ints while doing the check.
459 	 */
460 	if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE))
461 		vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
462 
463 	/*
464 	 * In mbuf_init(), we set up submaps for mbufs and clusters, in which
465 	 * case we rounddown() (nmbufs * MSIZE) and (nmbclusters * MCLBYTES),
466 	 * respectively. Mathematically, this means that what we do here may
467 	 * amount to slightly more address space than we need for the submaps,
468 	 * but it never hurts to have an extra page in kmem_map.
469 	 */
470 	npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + nmbcnt *
471 	    sizeof(u_int) + vm_kmem_size) / PAGE_SIZE;
472 
473 	kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
474 		(vm_size_t)(npg * sizeof(struct kmemusage)));
475 	kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
476 		(vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
477 	kmem_map->system_map = 1;
478 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
479 		if (1 << indx >= PAGE_SIZE)
480 			bucket[indx].kb_elmpercl = 1;
481 		else
482 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
483 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
484 	}
485 }
486 
487 void
488 malloc_init(data)
489 	void *data;
490 {
491 	struct malloc_type *type = (struct malloc_type *)data;
492 
493 	if (type->ks_magic != M_MAGIC)
494 		panic("malloc type lacks magic");
495 
496 	if (type->ks_limit != 0)
497 		return;
498 
499 	if (cnt.v_page_count == 0)
500 		panic("malloc_init not allowed before vm init");
501 
502 	/*
503 	 * The default limits for each malloc region is 1/2 of the
504 	 * malloc portion of the kmem map size.
505 	 */
506 	type->ks_limit = vm_kmem_size / 2;
507 	type->ks_next = kmemstatistics;
508 	kmemstatistics = type;
509 }
510 
511 void
512 malloc_uninit(data)
513 	void *data;
514 {
515 	struct malloc_type *type = (struct malloc_type *)data;
516 	struct malloc_type *t;
517 #ifdef INVARIANTS
518 	struct kmembuckets *kbp;
519 	struct freelist *freep;
520 	long indx;
521 	int s;
522 #endif
523 
524 	if (type->ks_magic != M_MAGIC)
525 		panic("malloc type lacks magic");
526 
527 	if (cnt.v_page_count == 0)
528 		panic("malloc_uninit not allowed before vm init");
529 
530 	if (type->ks_limit == 0)
531 		panic("malloc_uninit on uninitialized type");
532 
533 #ifdef INVARIANTS
534 	s = splmem();
535 	mtx_lock(&malloc_mtx);
536 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
537 		kbp = bucket + indx;
538 		freep = (struct freelist*)kbp->kb_next;
539 		while (freep) {
540 			if (freep->type == type)
541 				freep->type = M_FREE;
542 			freep = (struct freelist*)freep->next;
543 		}
544 	}
545 	splx(s);
546 	mtx_unlock(&malloc_mtx);
547 
548 	if (type->ks_memuse != 0)
549 		printf("malloc_uninit: %ld bytes of '%s' still allocated\n",
550 		    type->ks_memuse, type->ks_shortdesc);
551 #endif
552 
553 	if (type == kmemstatistics)
554 		kmemstatistics = type->ks_next;
555 	else {
556 		for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
557 			if (t->ks_next == type) {
558 				t->ks_next = type->ks_next;
559 				break;
560 			}
561 		}
562 	}
563 	type->ks_next = NULL;
564 	type->ks_limit = 0;
565 }
566