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