xref: /openbsd-src/sys/kern/kern_malloc.c (revision a4afd6dad3fba28f80e70208181c06c482259988)
1 /*	$OpenBSD: kern_malloc.c,v 1.6 1996/06/20 10:53:06 deraadt Exp $	*/
2 /*	$NetBSD: kern_malloc.c,v 1.15.4.2 1996/06/13 17:10:56 cgd Exp $	*/
3 
4 /*
5  * Copyright (c) 1987, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)kern_malloc.c	8.3 (Berkeley) 1/4/94
37  */
38 
39 #include <sys/param.h>
40 #include <sys/proc.h>
41 #include <sys/map.h>
42 #include <sys/kernel.h>
43 #include <sys/malloc.h>
44 #include <sys/systm.h>
45 
46 #include <vm/vm.h>
47 #include <vm/vm_kern.h>
48 
49 struct kmembuckets bucket[MINBUCKET + 16];
50 struct kmemstats kmemstats[M_LAST];
51 struct kmemusage *kmemusage;
52 char *kmembase, *kmemlimit;
53 char *memname[] = INITKMEMNAMES;
54 
55 #ifdef DIAGNOSTIC
56 /*
57  * This structure provides a set of masks to catch unaligned frees.
58  */
59 long addrmask[] = { 0,
60 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
61 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
62 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
63 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
64 };
65 
66 /*
67  * The WEIRD_ADDR is used as known text to copy into free objects so
68  * that modifications after frees can be detected.
69  */
70 #define WEIRD_ADDR	((unsigned) 0xdeadbeef)
71 #define MAX_COPY	32
72 
73 /*
74  * Normally the freelist structure is used only to hold the list pointer
75  * for free objects.  However, when running with diagnostics, the first
76  * 8 bytes of the structure is unused except for diagnostic information,
77  * and the free list pointer is at offst 8 in the structure.  Since the
78  * first 8 bytes is the portion of the structure most often modified, this
79  * helps to detect memory reuse problems and avoid free list corruption.
80  */
81 struct freelist {
82 	int32_t	spare0;
83 	int16_t	type;
84 	int16_t	spare1;
85 	caddr_t	next;
86 };
87 #else /* !DIAGNOSTIC */
88 struct freelist {
89 	caddr_t	next;
90 };
91 #endif /* DIAGNOSTIC */
92 
93 /*
94  * Allocate a block of memory
95  */
96 void *
97 malloc(size, type, flags)
98 	unsigned long size;
99 	int type, flags;
100 {
101 	register struct kmembuckets *kbp;
102 	register struct kmemusage *kup;
103 	register struct freelist *freep;
104 	long indx, npg, allocsize;
105 	int s;
106 	caddr_t va, cp, savedlist;
107 #ifdef DIAGNOSTIC
108 	int32_t *end, *lp;
109 	int copysize;
110 	char *savedtype;
111 #endif
112 #ifdef KMEMSTATS
113 	register struct kmemstats *ksp = &kmemstats[type];
114 
115 	if (((unsigned long)type) > M_LAST)
116 		panic("malloc - bogus type");
117 #endif
118 	indx = BUCKETINDX(size);
119 	kbp = &bucket[indx];
120 	s = splimp();
121 #ifdef KMEMSTATS
122 	while (ksp->ks_memuse >= ksp->ks_limit) {
123 		if (flags & M_NOWAIT) {
124 			splx(s);
125 			return ((void *) NULL);
126 		}
127 		if (ksp->ks_limblocks < 65535)
128 			ksp->ks_limblocks++;
129 		tsleep((caddr_t)ksp, PSWP+2, memname[type], 0);
130 	}
131 	ksp->ks_size |= 1 << indx;
132 #endif
133 #ifdef DIAGNOSTIC
134 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
135 #endif
136 	if (kbp->kb_next == NULL) {
137 		kbp->kb_last = NULL;
138 		if (size > MAXALLOCSAVE)
139 			allocsize = roundup(size, CLBYTES);
140 		else
141 			allocsize = 1 << indx;
142 		npg = clrnd(btoc(allocsize));
143 		va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg),
144 					   !(flags & M_NOWAIT));
145 		if (va == NULL) {
146 			/*
147 			 * Kmem_malloc() can return NULL, even if it can
148 			 * wait, if there is no map space avaiable, because
149 			 * it can't fix that problem.  Neither can we,
150 			 * right now.  (We should release pages which
151 			 * are completely free and which are in buckets
152 			 * with too many free elements.)
153 			 */
154 			if ((flags & M_NOWAIT) == 0)
155 				panic("malloc: out of space in kmem_map");
156 			splx(s);
157 			return ((void *) NULL);
158 		}
159 #ifdef KMEMSTATS
160 		kbp->kb_total += kbp->kb_elmpercl;
161 #endif
162 		kup = btokup(va);
163 		kup->ku_indx = indx;
164 		if (allocsize > MAXALLOCSAVE) {
165 			if (npg > 65535)
166 				panic("malloc: allocation too large");
167 			kup->ku_pagecnt = npg;
168 #ifdef KMEMSTATS
169 			ksp->ks_memuse += allocsize;
170 #endif
171 			goto out;
172 		}
173 #ifdef KMEMSTATS
174 		kup->ku_freecnt = kbp->kb_elmpercl;
175 		kbp->kb_totalfree += kbp->kb_elmpercl;
176 #endif
177 		/*
178 		 * Just in case we blocked while allocating memory,
179 		 * and someone else also allocated memory for this
180 		 * bucket, don't assume the list is still empty.
181 		 */
182 		savedlist = kbp->kb_next;
183 		kbp->kb_next = cp = va + (npg * NBPG) - allocsize;
184 		for (;;) {
185 			freep = (struct freelist *)cp;
186 #ifdef DIAGNOSTIC
187 			/*
188 			 * Copy in known text to detect modification
189 			 * after freeing.
190 			 */
191 			end = (int32_t *)&cp[copysize];
192 			for (lp = (int32_t *)cp; lp < end; lp++)
193 				*lp = WEIRD_ADDR;
194 			freep->type = M_FREE;
195 #endif /* DIAGNOSTIC */
196 			if (cp <= va)
197 				break;
198 			cp -= allocsize;
199 			freep->next = cp;
200 		}
201 		freep->next = savedlist;
202 		if (kbp->kb_last == NULL)
203 			kbp->kb_last = (caddr_t)freep;
204 	}
205 	va = kbp->kb_next;
206 	kbp->kb_next = ((struct freelist *)va)->next;
207 #ifdef DIAGNOSTIC
208 	freep = (struct freelist *)va;
209 	savedtype = (unsigned)freep->type < M_LAST ?
210 		memname[freep->type] : "???";
211 	if (kbp->kb_next &&
212 	    !kernacc(kbp->kb_next, sizeof(struct freelist), 0)) {
213 		printf("%s %d of object %p size %ld %s %s (invalid addr %p)\n",
214 			"Data modified on freelist: word",
215 			(int32_t *)&kbp->kb_next - (int32_t *)kbp, va, size,
216 			"previous type", savedtype, kbp->kb_next);
217 		kbp->kb_next = NULL;
218 	}
219 
220 	/* Fill the fields that we've used with WEIRD_ADDR */
221 #if BYTE_ORDER == BIG_ENDIAN
222 	freep->type = WEIRD_ADDR >> 16;
223 #endif
224 #if BYTE_ORDER == LITTLE_ENDIAN
225 	freep->type = (short)WEIRD_ADDR;
226 #endif
227 	end = (int32_t *)&freep->next +
228 	    (sizeof(freep->next) / sizeof(int32_t));
229 	for (lp = (int32_t *)&freep->next; lp < end; lp++)
230 		*lp = WEIRD_ADDR;
231 
232 	/* and check that the data hasn't been modified. */
233 	end = (int32_t *)&va[copysize];
234 	for (lp = (int32_t *)va; lp < end; lp++) {
235 		if (*lp == WEIRD_ADDR)
236 			continue;
237 		printf("%s %d of object %p size %ld %s %s (0x%x != 0x%x)\n",
238 			"Data modified on freelist: word", lp - (int32_t *)va,
239 			va, size, "previous type", savedtype, *lp, WEIRD_ADDR);
240 		break;
241 	}
242 
243 	freep->spare0 = 0;
244 #endif /* DIAGNOSTIC */
245 #ifdef KMEMSTATS
246 	kup = btokup(va);
247 	if (kup->ku_indx != indx)
248 		panic("malloc: wrong bucket");
249 	if (kup->ku_freecnt == 0)
250 		panic("malloc: lost data");
251 	kup->ku_freecnt--;
252 	kbp->kb_totalfree--;
253 	ksp->ks_memuse += 1 << indx;
254 out:
255 	kbp->kb_calls++;
256 	ksp->ks_inuse++;
257 	ksp->ks_calls++;
258 	if (ksp->ks_memuse > ksp->ks_maxused)
259 		ksp->ks_maxused = ksp->ks_memuse;
260 #else
261 out:
262 #endif
263 	splx(s);
264 	return ((void *) va);
265 }
266 
267 /*
268  * Free a block of memory allocated by malloc.
269  */
270 void
271 free(addr, type)
272 	void *addr;
273 	int type;
274 {
275 	register struct kmembuckets *kbp;
276 	register struct kmemusage *kup;
277 	register struct freelist *freep;
278 	long size;
279 	int s;
280 #ifdef DIAGNOSTIC
281 	caddr_t cp;
282 	int32_t *end, *lp;
283 	long alloc, copysize;
284 #endif
285 #ifdef KMEMSTATS
286 	register struct kmemstats *ksp = &kmemstats[type];
287 #endif
288 
289 	kup = btokup(addr);
290 	size = 1 << kup->ku_indx;
291 	kbp = &bucket[kup->ku_indx];
292 	s = splimp();
293 #ifdef DIAGNOSTIC
294 	/*
295 	 * Check for returns of data that do not point to the
296 	 * beginning of the allocation.
297 	 */
298 	if (size > NBPG * CLSIZE)
299 		alloc = addrmask[BUCKETINDX(NBPG * CLSIZE)];
300 	else
301 		alloc = addrmask[kup->ku_indx];
302 	if (((u_long)addr & alloc) != 0)
303 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld\n",
304 			addr, size, memname[type], alloc);
305 #endif /* DIAGNOSTIC */
306 	if (size > MAXALLOCSAVE) {
307 		kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
308 #ifdef KMEMSTATS
309 		size = kup->ku_pagecnt << PGSHIFT;
310 		ksp->ks_memuse -= size;
311 		kup->ku_indx = 0;
312 		kup->ku_pagecnt = 0;
313 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
314 		    ksp->ks_memuse < ksp->ks_limit)
315 			wakeup((caddr_t)ksp);
316 		ksp->ks_inuse--;
317 		kbp->kb_total -= 1;
318 #endif
319 		splx(s);
320 		return;
321 	}
322 	freep = (struct freelist *)addr;
323 #ifdef DIAGNOSTIC
324 	/*
325 	 * Check for multiple frees. Use a quick check to see if
326 	 * it looks free before laboriously searching the freelist.
327 	 */
328 	if (freep->spare0 == WEIRD_ADDR) {
329 		for (cp = kbp->kb_next; cp;
330 		    cp = ((struct freelist *)cp)->next) {
331 			if (addr != cp)
332 				continue;
333 			printf("multiply freed item %p\n", addr);
334 			panic("free: duplicated free");
335 		}
336 	}
337 	/*
338 	 * Copy in known text to detect modification after freeing
339 	 * and to make it look free. Also, save the type being freed
340 	 * so we can list likely culprit if modification is detected
341 	 * when the object is reallocated.
342 	 */
343 	copysize = size < MAX_COPY ? size : MAX_COPY;
344 	end = (int32_t *)&((caddr_t)addr)[copysize];
345 	for (lp = (int32_t *)addr; lp < end; lp++)
346 		*lp = WEIRD_ADDR;
347 	freep->type = type;
348 #endif /* DIAGNOSTIC */
349 #ifdef KMEMSTATS
350 	kup->ku_freecnt++;
351 	if (kup->ku_freecnt >= kbp->kb_elmpercl)
352 		if (kup->ku_freecnt > kbp->kb_elmpercl)
353 			panic("free: multiple frees");
354 		else if (kbp->kb_totalfree > kbp->kb_highwat)
355 			kbp->kb_couldfree++;
356 	kbp->kb_totalfree++;
357 	ksp->ks_memuse -= size;
358 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
359 	    ksp->ks_memuse < ksp->ks_limit)
360 		wakeup((caddr_t)ksp);
361 	ksp->ks_inuse--;
362 #endif
363 	if (kbp->kb_next == NULL)
364 		kbp->kb_next = addr;
365 	else
366 		((struct freelist *)kbp->kb_last)->next = addr;
367 	freep->next = NULL;
368 	kbp->kb_last = addr;
369 	splx(s);
370 }
371 
372 /*
373  * Initialize the kernel memory allocator
374  */
375 void
376 kmeminit()
377 {
378 	register long indx;
379 	int npg;
380 
381 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
382 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
383 #endif
384 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
385 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
386 #endif
387 #if	(MAXALLOCSAVE < CLBYTES)
388 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
389 #endif
390 
391 	if (sizeof(struct freelist) > (1 << MINBUCKET))
392 		panic("minbucket too small/struct freelist too big");
393 
394 	npg = VM_KMEM_SIZE/ NBPG;
395 	kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
396 		(vm_size_t)(npg * sizeof(struct kmemusage)));
397 	kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
398 		(vm_offset_t *)&kmemlimit, (vm_size_t)(npg * NBPG), FALSE);
399 #ifdef KMEMSTATS
400 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
401 		if (1 << indx >= CLBYTES)
402 			bucket[indx].kb_elmpercl = 1;
403 		else
404 			bucket[indx].kb_elmpercl = CLBYTES / (1 << indx);
405 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
406 	}
407 	for (indx = 0; indx < M_LAST; indx++)
408 		kmemstats[indx].ks_limit = npg * NBPG * 6 / 10;
409 #endif
410 }
411