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