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