xref: /freebsd/sys/kern/kern_malloc.c (revision 0c43d89a0d8e976ca494d4837f4c1f3734d2c300)
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  * $Id$
35  */
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/proc.h>
40 #include <sys/map.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 
44 #include <vm/vm.h>
45 #include <vm/vm_kern.h>
46 
47 struct kmembuckets bucket[MINBUCKET + 16];
48 struct kmemstats kmemstats[M_LAST];
49 struct kmemusage *kmemusage;
50 char *kmembase, *kmemlimit;
51 char *memname[] = INITKMEMNAMES;
52 
53 #ifdef DIAGNOSTIC
54 /*
55  * This structure provides a set of masks to catch unaligned frees.
56  */
57 long addrmask[] = { 0,
58 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
59 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
60 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
61 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
62 };
63 
64 /*
65  * The WEIRD_ADDR is used as known text to copy into free objects so
66  * that modifications after frees can be detected.
67  */
68 #define WEIRD_ADDR	0xdeadbeef
69 #define MAX_COPY	32
70 
71 /*
72  * Normally the first word of the structure is used to hold the list
73  * pointer for free objects. However, when running with diagnostics,
74  * we use the third and fourth fields, so as to catch modifications
75  * in the most commonly trashed first two words.
76  */
77 struct freelist {
78 	long	spare0;
79 	short	type;
80 	long	spare1;
81 	caddr_t	next;
82 };
83 #else /* !DIAGNOSTIC */
84 struct freelist {
85 	caddr_t	next;
86 };
87 #endif /* DIAGNOSTIC */
88 
89 /*
90  * Allocate a block of memory
91  */
92 void *
93 malloc(size, type, flags)
94 	unsigned long size;
95 	int type, flags;
96 {
97 	register struct kmembuckets *kbp;
98 	register struct kmemusage *kup;
99 	register struct freelist *freep;
100 	long indx, npg, allocsize;
101 	int s;
102 	caddr_t va, cp, savedlist;
103 #ifdef DIAGNOSTIC
104 	long *end, *lp;
105 	int copysize;
106 	char *savedtype;
107 #endif
108 #ifdef KMEMSTATS
109 	register struct kmemstats *ksp = &kmemstats[type];
110 
111 	if (((unsigned long)type) > M_LAST)
112 		panic("malloc - bogus type");
113 #endif
114 	indx = BUCKETINDX(size);
115 	kbp = &bucket[indx];
116 	s = splimp();
117 #ifdef KMEMSTATS
118 	while (ksp->ks_memuse >= ksp->ks_limit) {
119 		if (flags & M_NOWAIT) {
120 			splx(s);
121 			return ((void *) NULL);
122 		}
123 		if (ksp->ks_limblocks < 65535)
124 			ksp->ks_limblocks++;
125 		tsleep((caddr_t)ksp, PSWP+2, memname[type], 0);
126 	}
127 	ksp->ks_size |= 1 << indx;
128 #endif
129 #ifdef DIAGNOSTIC
130 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
131 #endif
132 	if (kbp->kb_next == NULL) {
133 		kbp->kb_last = NULL;
134 		if (size > MAXALLOCSAVE)
135 			allocsize = roundup(size, CLBYTES);
136 		else
137 			allocsize = 1 << indx;
138 		npg = clrnd(btoc(allocsize));
139 		va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg),
140 					   !(flags & M_NOWAIT));
141 		if (va == NULL) {
142 			splx(s);
143 			return ((void *) NULL);
144 		}
145 #ifdef KMEMSTATS
146 		kbp->kb_total += kbp->kb_elmpercl;
147 #endif
148 		kup = btokup(va);
149 		kup->ku_indx = indx;
150 		if (allocsize > MAXALLOCSAVE) {
151 			if (npg > 65535)
152 				panic("malloc: allocation too large");
153 			kup->ku_pagecnt = npg;
154 #ifdef KMEMSTATS
155 			ksp->ks_memuse += allocsize;
156 #endif
157 			goto out;
158 		}
159 #ifdef KMEMSTATS
160 		kup->ku_freecnt = kbp->kb_elmpercl;
161 		kbp->kb_totalfree += kbp->kb_elmpercl;
162 #endif
163 		/*
164 		 * Just in case we blocked while allocating memory,
165 		 * and someone else also allocated memory for this
166 		 * bucket, don't assume the list is still empty.
167 		 */
168 		savedlist = kbp->kb_next;
169 		kbp->kb_next = cp = va + (npg * NBPG) - allocsize;
170 		for (;;) {
171 			freep = (struct freelist *)cp;
172 #ifdef DIAGNOSTIC
173 			/*
174 			 * Copy in known text to detect modification
175 			 * after freeing.
176 			 */
177 			end = (long *)&cp[copysize];
178 			for (lp = (long *)cp; lp < end; lp++)
179 				*lp = WEIRD_ADDR;
180 			freep->type = M_FREE;
181 #endif /* DIAGNOSTIC */
182 			if (cp <= va)
183 				break;
184 			cp -= allocsize;
185 			freep->next = cp;
186 		}
187 		freep->next = savedlist;
188 		if (kbp->kb_last == NULL)
189 			kbp->kb_last = (caddr_t)freep;
190 	}
191 	va = kbp->kb_next;
192 	kbp->kb_next = ((struct freelist *)va)->next;
193 #ifdef DIAGNOSTIC
194 	freep = (struct freelist *)va;
195 	savedtype = (unsigned)freep->type < M_LAST ?
196 		memname[freep->type] : "???";
197 	if (kbp->kb_next &&
198 	    !kernacc(kbp->kb_next, sizeof(struct freelist), 0)) {
199 		printf("%s of object 0x%x size %d %s %s (invalid addr 0x%x)\n",
200 			"Data modified on freelist: word 2.5", va, size,
201 			"previous type", savedtype, kbp->kb_next);
202 		kbp->kb_next = NULL;
203 	}
204 #if BYTE_ORDER == BIG_ENDIAN
205 	freep->type = WEIRD_ADDR >> 16;
206 #endif
207 #if BYTE_ORDER == LITTLE_ENDIAN
208 	freep->type = (short)WEIRD_ADDR;
209 #endif
210 	if (((long)(&freep->next)) & 0x2)
211 		freep->next = (caddr_t)((WEIRD_ADDR >> 16)|(WEIRD_ADDR << 16));
212 	else
213 		freep->next = (caddr_t)WEIRD_ADDR;
214 	end = (long *)&va[copysize];
215 	for (lp = (long *)va; lp < end; lp++) {
216 		if (*lp == WEIRD_ADDR)
217 			continue;
218 		printf("%s %d of object 0x%x size %d %s %s (0x%x != 0x%x)\n",
219 			"Data modified on freelist: word", lp - (long *)va,
220 			va, size, "previous type", savedtype, *lp, WEIRD_ADDR);
221 		break;
222 	}
223 	freep->spare0 = 0;
224 #endif /* DIAGNOSTIC */
225 #ifdef KMEMSTATS
226 	kup = btokup(va);
227 	if (kup->ku_indx != indx)
228 		panic("malloc: wrong bucket");
229 	if (kup->ku_freecnt == 0)
230 		panic("malloc: lost data");
231 	kup->ku_freecnt--;
232 	kbp->kb_totalfree--;
233 	ksp->ks_memuse += 1 << indx;
234 out:
235 	kbp->kb_calls++;
236 	ksp->ks_inuse++;
237 	ksp->ks_calls++;
238 	if (ksp->ks_memuse > ksp->ks_maxused)
239 		ksp->ks_maxused = ksp->ks_memuse;
240 #else
241 out:
242 #endif
243 	splx(s);
244 	return ((void *) va);
245 }
246 
247 /*
248  * Free a block of memory allocated by malloc.
249  */
250 void
251 free(addr, type)
252 	void *addr;
253 	int type;
254 {
255 	register struct kmembuckets *kbp;
256 	register struct kmemusage *kup;
257 	register struct freelist *freep;
258 	long size;
259 	int s;
260 #ifdef DIAGNOSTIC
261 	caddr_t cp;
262 	long *end, *lp, alloc, copysize;
263 #endif
264 #ifdef KMEMSTATS
265 	register struct kmemstats *ksp = &kmemstats[type];
266 #endif
267 
268 	kup = btokup(addr);
269 	size = 1 << kup->ku_indx;
270 	kbp = &bucket[kup->ku_indx];
271 	s = splimp();
272 #ifdef DIAGNOSTIC
273 	/*
274 	 * Check for returns of data that do not point to the
275 	 * beginning of the allocation.
276 	 */
277 	if (size > NBPG * CLSIZE)
278 		alloc = addrmask[BUCKETINDX(NBPG * CLSIZE)];
279 	else
280 		alloc = addrmask[kup->ku_indx];
281 	if (((u_long)addr & alloc) != 0)
282 		panic("free: unaligned addr 0x%x, size %d, type %s, mask %d\n",
283 			addr, size, memname[type], alloc);
284 #endif /* DIAGNOSTIC */
285 	if (size > MAXALLOCSAVE) {
286 		kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
287 #ifdef KMEMSTATS
288 		size = kup->ku_pagecnt << PGSHIFT;
289 		ksp->ks_memuse -= size;
290 		kup->ku_indx = 0;
291 		kup->ku_pagecnt = 0;
292 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
293 		    ksp->ks_memuse < ksp->ks_limit)
294 			wakeup((caddr_t)ksp);
295 		ksp->ks_inuse--;
296 		kbp->kb_total -= 1;
297 #endif
298 		splx(s);
299 		return;
300 	}
301 	freep = (struct freelist *)addr;
302 #ifdef DIAGNOSTIC
303 	/*
304 	 * Check for multiple frees. Use a quick check to see if
305 	 * it looks free before laboriously searching the freelist.
306 	 */
307 	if (freep->spare0 == WEIRD_ADDR) {
308 		for (cp = kbp->kb_next; cp; cp = *(caddr_t *)cp) {
309 			if (addr != cp)
310 				continue;
311 			printf("multiply freed item 0x%x\n", addr);
312 			panic("free: duplicated free");
313 		}
314 	}
315 	/*
316 	 * Copy in known text to detect modification after freeing
317 	 * and to make it look free. Also, save the type being freed
318 	 * so we can list likely culprit if modification is detected
319 	 * when the object is reallocated.
320 	 */
321 	copysize = size < MAX_COPY ? size : MAX_COPY;
322 	end = (long *)&((caddr_t)addr)[copysize];
323 	for (lp = (long *)addr; lp < end; lp++)
324 		*lp = WEIRD_ADDR;
325 	freep->type = type;
326 #endif /* DIAGNOSTIC */
327 #ifdef KMEMSTATS
328 	kup->ku_freecnt++;
329 	if (kup->ku_freecnt >= kbp->kb_elmpercl)
330 		if (kup->ku_freecnt > kbp->kb_elmpercl)
331 			panic("free: multiple frees");
332 		else if (kbp->kb_totalfree > kbp->kb_highwat)
333 			kbp->kb_couldfree++;
334 	kbp->kb_totalfree++;
335 	ksp->ks_memuse -= size;
336 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
337 	    ksp->ks_memuse < ksp->ks_limit)
338 		wakeup((caddr_t)ksp);
339 	ksp->ks_inuse--;
340 #endif
341 	if (kbp->kb_next == NULL)
342 		kbp->kb_next = addr;
343 	else
344 		((struct freelist *)kbp->kb_last)->next = addr;
345 	freep->next = NULL;
346 	kbp->kb_last = addr;
347 	splx(s);
348 }
349 
350 /*
351  * Initialize the kernel memory allocator
352  */
353 void
354 kmeminit()
355 {
356 	register long indx;
357 	int npg;
358 
359 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
360 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
361 #endif
362 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
363 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
364 #endif
365 #if	(MAXALLOCSAVE < CLBYTES)
366 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
367 #endif
368 	npg = VM_KMEM_SIZE/ NBPG;
369 	kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
370 		(vm_size_t)(npg * sizeof(struct kmemusage)));
371 	kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
372 		(vm_offset_t *)&kmemlimit, (vm_size_t)(npg * NBPG), FALSE);
373 #ifdef KMEMSTATS
374 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
375 		if (1 << indx >= CLBYTES)
376 			bucket[indx].kb_elmpercl = 1;
377 		else
378 			bucket[indx].kb_elmpercl = CLBYTES / (1 << indx);
379 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
380 	}
381 	for (indx = 0; indx < M_LAST; indx++)
382 		kmemstats[indx].ks_limit = npg * NBPG * 6 / 10;
383 #endif
384 }
385