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