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