xref: /openbsd-src/sys/kern/kern_malloc.c (revision 1fc27e414118cd8922c6b93fbaeb7a5246bfd593)
1 /*	$OpenBSD: kern_malloc.c,v 1.18 1999/11/25 13:41:30 art 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 #if defined(UVM)
50 #include <uvm/uvm_extern.h>
51 
52 static struct vm_map kmem_map_store;
53 vm_map_t kmem_map = NULL;
54 #endif
55 
56 struct kmembuckets bucket[MINBUCKET + 16];
57 struct kmemstats kmemstats[M_LAST];
58 struct kmemusage *kmemusage;
59 char *kmembase, *kmemlimit;
60 #if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES)
61 char *memname[] = INITKMEMNAMES;
62 #endif
63 
64 #ifdef DIAGNOSTIC
65 /*
66  * This structure provides a set of masks to catch unaligned frees.
67  */
68 long addrmask[] = { 0,
69 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
70 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
71 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
72 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
73 };
74 
75 /*
76  * The WEIRD_ADDR is used as known text to copy into free objects so
77  * that modifications after frees can be detected.
78  */
79 #define WEIRD_ADDR	((unsigned) 0xdeadbeef)
80 #define MAX_COPY	32
81 
82 /*
83  * Normally the freelist structure is used only to hold the list pointer
84  * for free objects.  However, when running with diagnostics, the first
85  * 8 bytes of the structure is unused except for diagnostic information,
86  * and the free list pointer is at offst 8 in the structure.  Since the
87  * first 8 bytes is the portion of the structure most often modified, this
88  * helps to detect memory reuse problems and avoid free list corruption.
89  */
90 struct freelist {
91 	int32_t	spare0;
92 	int16_t	type;
93 	int16_t	spare1;
94 	caddr_t	next;
95 };
96 #else /* !DIAGNOSTIC */
97 struct freelist {
98 	caddr_t	next;
99 };
100 #endif /* DIAGNOSTIC */
101 
102 /*
103  * Allocate a block of memory
104  */
105 void *
106 malloc(size, type, flags)
107 	unsigned long size;
108 	int type, flags;
109 {
110 	register struct kmembuckets *kbp;
111 	register struct kmemusage *kup;
112 	register struct freelist *freep;
113 	long indx, npg, allocsize;
114 	int s;
115 	caddr_t va, cp, savedlist;
116 #ifdef DIAGNOSTIC
117 	int32_t *end, *lp;
118 	int copysize;
119 	char *savedtype;
120 #endif
121 #ifdef KMEMSTATS
122 	register struct kmemstats *ksp = &kmemstats[type];
123 
124 	if (((unsigned long)type) > M_LAST)
125 		panic("malloc - bogus type");
126 #endif
127 	indx = BUCKETINDX(size);
128 	kbp = &bucket[indx];
129 	s = splimp();
130 #ifdef KMEMSTATS
131 	while (ksp->ks_memuse >= ksp->ks_limit) {
132 		if (flags & M_NOWAIT) {
133 			splx(s);
134 			return ((void *) NULL);
135 		}
136 		if (ksp->ks_limblocks < 65535)
137 			ksp->ks_limblocks++;
138 		tsleep((caddr_t)ksp, PSWP+2, memname[type], 0);
139 	}
140 	ksp->ks_size |= 1 << indx;
141 #endif
142 #ifdef DIAGNOSTIC
143 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
144 #endif
145 	if (kbp->kb_next == NULL) {
146 		kbp->kb_last = NULL;
147 		if (size > MAXALLOCSAVE)
148 			allocsize = clrnd(round_page(size));
149 		else
150 			allocsize = 1 << indx;
151 		npg = clrnd(btoc(allocsize));
152 #if defined(UVM)
153 		va = (caddr_t) uvm_km_kmemalloc(kmem_map, uvmexp.kmem_object,
154 				(vsize_t)ctob(npg),
155 				(flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0);
156 #else
157 		va = (caddr_t) kmem_malloc(kmem_map, (vsize_t)ctob(npg),
158 					   !(flags & M_NOWAIT));
159 #endif
160 		if (va == NULL) {
161 			/*
162 			 * Kmem_malloc() can return NULL, even if it can
163 			 * wait, if there is no map space available, because
164 			 * it can't fix that problem.  Neither can we,
165 			 * right now.  (We should release pages which
166 			 * are completely free and which are in buckets
167 			 * with too many free elements.)
168 			 */
169 			if ((flags & M_NOWAIT) == 0)
170 				panic("malloc: out of space in kmem_map");
171 			splx(s);
172 			return ((void *) NULL);
173 		}
174 #ifdef KMEMSTATS
175 		kbp->kb_total += kbp->kb_elmpercl;
176 #endif
177 		kup = btokup(va);
178 		kup->ku_indx = indx;
179 		if (allocsize > MAXALLOCSAVE) {
180 			if (npg > 65535)
181 				panic("malloc: allocation too large");
182 			kup->ku_pagecnt = npg;
183 #ifdef KMEMSTATS
184 			ksp->ks_memuse += allocsize;
185 #endif
186 			goto out;
187 		}
188 #ifdef KMEMSTATS
189 		kup->ku_freecnt = kbp->kb_elmpercl;
190 		kbp->kb_totalfree += kbp->kb_elmpercl;
191 #endif
192 		/*
193 		 * Just in case we blocked while allocating memory,
194 		 * and someone else also allocated memory for this
195 		 * bucket, don't assume the list is still empty.
196 		 */
197 		savedlist = kbp->kb_next;
198 		kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
199 		for (;;) {
200 			freep = (struct freelist *)cp;
201 #ifdef DIAGNOSTIC
202 			/*
203 			 * Copy in known text to detect modification
204 			 * after freeing.
205 			 */
206 			end = (int32_t *)&cp[copysize];
207 			for (lp = (int32_t *)cp; lp < end; lp++)
208 				*lp = WEIRD_ADDR;
209 			freep->type = M_FREE;
210 #endif /* DIAGNOSTIC */
211 			if (cp <= va)
212 				break;
213 			cp -= allocsize;
214 			freep->next = cp;
215 		}
216 		freep->next = savedlist;
217 		if (kbp->kb_last == NULL)
218 			kbp->kb_last = (caddr_t)freep;
219 	}
220 	va = kbp->kb_next;
221 	kbp->kb_next = ((struct freelist *)va)->next;
222 #ifdef DIAGNOSTIC
223 	freep = (struct freelist *)va;
224 	savedtype = (unsigned)freep->type < M_LAST ?
225 		memname[freep->type] : "???";
226 #if defined(UVM)
227 	if (kbp->kb_next) {
228 		int rv;
229 		vaddr_t addr = (vaddr_t)kbp->kb_next;
230 
231 		vm_map_lock_read(kmem_map);
232 		rv = uvm_map_checkprot(kmem_map, addr,
233 				       addr + sizeof(struct freelist),
234 				       VM_PROT_WRITE);
235 		vm_map_unlock_read(kmem_map);
236 
237 		if (!rv)
238 #else
239 	if (kbp->kb_next &&
240 	    !kernacc(kbp->kb_next, sizeof(struct freelist), 0))
241 #endif
242 	  {
243 		printf("%s %d of object %p size %ld %s %s (invalid addr %p)\n",
244 			"Data modified on freelist: word",
245 			(int32_t *)&kbp->kb_next - (int32_t *)kbp, va, size,
246 			"previous type", savedtype, kbp->kb_next);
247 		kbp->kb_next = NULL;
248 #if defined(UVM)
249 		}
250 #endif
251 	}
252 
253 	/* Fill the fields that we've used with WEIRD_ADDR */
254 #if BYTE_ORDER == BIG_ENDIAN
255 	freep->type = WEIRD_ADDR >> 16;
256 #endif
257 #if BYTE_ORDER == LITTLE_ENDIAN
258 	freep->type = (short)WEIRD_ADDR;
259 #endif
260 	end = (int32_t *)&freep->next +
261 	    (sizeof(freep->next) / sizeof(int32_t));
262 	for (lp = (int32_t *)&freep->next; lp < end; lp++)
263 		*lp = WEIRD_ADDR;
264 
265 	/* and check that the data hasn't been modified. */
266 	end = (int32_t *)&va[copysize];
267 	for (lp = (int32_t *)va; lp < end; lp++) {
268 		if (*lp == WEIRD_ADDR)
269 			continue;
270 		printf("%s %d of object %p size %ld %s %s (0x%x != 0x%x)\n",
271 			"Data modified on freelist: word", lp - (int32_t *)va,
272 			va, size, "previous type", savedtype, *lp, WEIRD_ADDR);
273 		break;
274 	}
275 
276 	freep->spare0 = 0;
277 #endif /* DIAGNOSTIC */
278 #ifdef KMEMSTATS
279 	kup = btokup(va);
280 	if (kup->ku_indx != indx)
281 		panic("malloc: wrong bucket");
282 	if (kup->ku_freecnt == 0)
283 		panic("malloc: lost data");
284 	kup->ku_freecnt--;
285 	kbp->kb_totalfree--;
286 	ksp->ks_memuse += 1 << indx;
287 out:
288 	kbp->kb_calls++;
289 	ksp->ks_inuse++;
290 	ksp->ks_calls++;
291 	if (ksp->ks_memuse > ksp->ks_maxused)
292 		ksp->ks_maxused = ksp->ks_memuse;
293 #else
294 out:
295 #endif
296 	splx(s);
297 	return ((void *) va);
298 }
299 
300 /*
301  * Free a block of memory allocated by malloc.
302  */
303 void
304 free(addr, type)
305 	void *addr;
306 	int type;
307 {
308 	register struct kmembuckets *kbp;
309 	register struct kmemusage *kup;
310 	register struct freelist *freep;
311 	long size;
312 	int s;
313 #ifdef DIAGNOSTIC
314 	caddr_t cp;
315 	int32_t *end, *lp;
316 	long alloc, copysize;
317 #endif
318 #ifdef KMEMSTATS
319 	register struct kmemstats *ksp = &kmemstats[type];
320 #endif
321 
322 	kup = btokup(addr);
323 	size = 1 << kup->ku_indx;
324 	kbp = &bucket[kup->ku_indx];
325 	s = splimp();
326 #ifdef DIAGNOSTIC
327 	/*
328 	 * Check for returns of data that do not point to the
329 	 * beginning of the allocation.
330 	 */
331 	if (size > PAGE_SIZE * CLSIZE)
332 		alloc = addrmask[BUCKETINDX(PAGE_SIZE * CLSIZE)];
333 	else
334 		alloc = addrmask[kup->ku_indx];
335 	if (((u_long)addr & alloc) != 0)
336 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
337 			addr, size, memname[type], alloc);
338 #endif /* DIAGNOSTIC */
339 	if (size > MAXALLOCSAVE) {
340 #if defined(UVM)
341 		uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
342 #else
343 		kmem_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
344 #endif
345 #ifdef KMEMSTATS
346 		size = kup->ku_pagecnt << PGSHIFT;
347 		ksp->ks_memuse -= size;
348 		kup->ku_indx = 0;
349 		kup->ku_pagecnt = 0;
350 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
351 		    ksp->ks_memuse < ksp->ks_limit)
352 			wakeup((caddr_t)ksp);
353 		ksp->ks_inuse--;
354 		kbp->kb_total -= 1;
355 #endif
356 		splx(s);
357 		return;
358 	}
359 	freep = (struct freelist *)addr;
360 #ifdef DIAGNOSTIC
361 	/*
362 	 * Check for multiple frees. Use a quick check to see if
363 	 * it looks free before laboriously searching the freelist.
364 	 */
365 	if (freep->spare0 == WEIRD_ADDR) {
366 		for (cp = kbp->kb_next; cp;
367 		    cp = ((struct freelist *)cp)->next) {
368 			if (addr != cp)
369 				continue;
370 			printf("multiply freed item %p\n", addr);
371 			panic("free: duplicated free");
372 		}
373 	}
374 	/*
375 	 * Copy in known text to detect modification after freeing
376 	 * and to make it look free. Also, save the type being freed
377 	 * so we can list likely culprit if modification is detected
378 	 * when the object is reallocated.
379 	 */
380 	copysize = size < MAX_COPY ? size : MAX_COPY;
381 	end = (int32_t *)&((caddr_t)addr)[copysize];
382 	for (lp = (int32_t *)addr; lp < end; lp++)
383 		*lp = WEIRD_ADDR;
384 	freep->type = type;
385 #endif /* DIAGNOSTIC */
386 #ifdef KMEMSTATS
387 	kup->ku_freecnt++;
388 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
389 		if (kup->ku_freecnt > kbp->kb_elmpercl)
390 			panic("free: multiple frees");
391 		else if (kbp->kb_totalfree > kbp->kb_highwat)
392 			kbp->kb_couldfree++;
393 	}
394 	kbp->kb_totalfree++;
395 	ksp->ks_memuse -= size;
396 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
397 	    ksp->ks_memuse < ksp->ks_limit)
398 		wakeup((caddr_t)ksp);
399 	ksp->ks_inuse--;
400 #endif
401 	if (kbp->kb_next == NULL)
402 		kbp->kb_next = addr;
403 	else
404 		((struct freelist *)kbp->kb_last)->next = addr;
405 	freep->next = NULL;
406 	kbp->kb_last = addr;
407 	splx(s);
408 }
409 
410 /*
411  * Initialize the kernel memory allocator
412  */
413 void
414 kmeminit()
415 {
416 #ifdef KMEMSTATS
417 	register long indx;
418 #endif
419 	int npg;
420 
421 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
422 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
423 #endif
424 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
425 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
426 #endif
427 #if	(MAXALLOCSAVE < CLBYTES)
428 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
429 #endif
430 
431 #ifdef DIAGNOSTIC
432 	if (sizeof(struct freelist) > (1 << MINBUCKET))
433 		panic("kmeminit: minbucket too small/struct freelist too big");
434 #endif
435 
436 	npg = VM_KMEM_SIZE / PAGE_SIZE;
437 #if defined(UVM)
438 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
439 		(vsize_t)(npg * sizeof(struct kmemusage)));
440 	kmem_map = uvm_km_suballoc(kernel_map, (vaddr_t *)&kmembase,
441 		(vaddr_t *)&kmemlimit, (vsize_t)(npg * PAGE_SIZE),
442 			FALSE, FALSE, &kmem_map_store);
443 #else
444 	kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
445 		(vsize_t)(npg * sizeof(struct kmemusage)));
446 	kmem_map = kmem_suballoc(kernel_map, (vaddr_t *)&kmembase,
447 		(vaddr_t *)&kmemlimit, (vsize_t)(npg * PAGE_SIZE), FALSE);
448 #endif
449 #ifdef KMEMSTATS
450 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
451 		if (1 << indx >= CLBYTES)
452 			bucket[indx].kb_elmpercl = 1;
453 		else
454 			bucket[indx].kb_elmpercl = CLBYTES / (1 << indx);
455 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
456 	}
457 	for (indx = 0; indx < M_LAST; indx++)
458 		kmemstats[indx].ks_limit = npg * PAGE_SIZE * 6 / 10;
459 #endif
460 }
461