Home | History | Annotate | Line # | Download | only in kern
kern_malloc.c revision 1.85
      1 /*	$NetBSD: kern_malloc.c,v 1.85 2003/08/31 12:59:05 fvdl 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. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  *
     31  *	@(#)kern_malloc.c	8.4 (Berkeley) 5/20/95
     32  */
     33 
     34 /*
     35  * Copyright (c) 1996 Christopher G. Demetriou.  All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  * 3. All advertising materials mentioning features or use of this software
     46  *    must display the following acknowledgement:
     47  *	This product includes software developed by the University of
     48  *	California, Berkeley and its contributors.
     49  * 4. Neither the name of the University nor the names of its contributors
     50  *    may be used to endorse or promote products derived from this software
     51  *    without specific prior written permission.
     52  *
     53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     63  * SUCH DAMAGE.
     64  *
     65  *	@(#)kern_malloc.c	8.4 (Berkeley) 5/20/95
     66  */
     67 
     68 #include <sys/cdefs.h>
     69 __KERNEL_RCSID(0, "$NetBSD: kern_malloc.c,v 1.85 2003/08/31 12:59:05 fvdl Exp $");
     70 
     71 #include "opt_lockdebug.h"
     72 
     73 #include <sys/param.h>
     74 #include <sys/proc.h>
     75 #include <sys/kernel.h>
     76 #include <sys/malloc.h>
     77 #include <sys/systm.h>
     78 
     79 #include <uvm/uvm_extern.h>
     80 
     81 static struct vm_map kmem_map_store;
     82 struct vm_map *kmem_map = NULL;
     83 
     84 #include "opt_kmempages.h"
     85 
     86 #ifdef NKMEMCLUSTERS
     87 #error NKMEMCLUSTERS is obsolete; remove it from your kernel config file and use NKMEMPAGES instead or let the kernel auto-size
     88 #endif
     89 
     90 /*
     91  * Default number of pages in kmem_map.  We attempt to calculate this
     92  * at run-time, but allow it to be either patched or set in the kernel
     93  * config file.
     94  */
     95 #ifndef NKMEMPAGES
     96 #define	NKMEMPAGES	0
     97 #endif
     98 int	nkmempages = NKMEMPAGES;
     99 
    100 /*
    101  * Defaults for lower- and upper-bounds for the kmem_map page count.
    102  * Can be overridden by kernel config options.
    103  */
    104 #ifndef	NKMEMPAGES_MIN
    105 #define	NKMEMPAGES_MIN	NKMEMPAGES_MIN_DEFAULT
    106 #endif
    107 
    108 #ifndef NKMEMPAGES_MAX
    109 #define	NKMEMPAGES_MAX	NKMEMPAGES_MAX_DEFAULT
    110 #endif
    111 
    112 #include "opt_kmemstats.h"
    113 #include "opt_malloclog.h"
    114 #include "opt_malloc_debug.h"
    115 
    116 struct kmembuckets bucket[MINBUCKET + 16];
    117 struct kmemusage *kmemusage;
    118 char *kmembase, *kmemlimit;
    119 
    120 struct malloc_type *kmemstatistics;
    121 
    122 #ifdef MALLOCLOG
    123 #ifndef MALLOCLOGSIZE
    124 #define	MALLOCLOGSIZE	100000
    125 #endif
    126 
    127 struct malloclog {
    128 	void *addr;
    129 	long size;
    130 	struct malloc_type *type;
    131 	int action;
    132 	const char *file;
    133 	long line;
    134 } malloclog[MALLOCLOGSIZE];
    135 
    136 long	malloclogptr;
    137 
    138 static void
    139 domlog(void *a, long size, struct malloc_type *type, int action,
    140     const char *file, long line)
    141 {
    142 
    143 	malloclog[malloclogptr].addr = a;
    144 	malloclog[malloclogptr].size = size;
    145 	malloclog[malloclogptr].type = type;
    146 	malloclog[malloclogptr].action = action;
    147 	malloclog[malloclogptr].file = file;
    148 	malloclog[malloclogptr].line = line;
    149 	malloclogptr++;
    150 	if (malloclogptr >= MALLOCLOGSIZE)
    151 		malloclogptr = 0;
    152 }
    153 
    154 static void
    155 hitmlog(void *a)
    156 {
    157 	struct malloclog *lp;
    158 	long l;
    159 
    160 #define	PRT do { \
    161 	if (malloclog[l].addr == a && malloclog[l].action) { \
    162 		lp = &malloclog[l]; \
    163 		printf("malloc log entry %ld:\n", l); \
    164 		printf("\taddr = %p\n", lp->addr); \
    165 		printf("\tsize = %ld\n", lp->size); \
    166 		printf("\ttype = %s\n", lp->type->ks_shortdesc); \
    167 		printf("\taction = %s\n", lp->action == 1 ? "alloc" : "free"); \
    168 		printf("\tfile = %s\n", lp->file); \
    169 		printf("\tline = %ld\n", lp->line); \
    170 	} \
    171 } while (/* CONSTCOND */0)
    172 
    173 	for (l = malloclogptr; l < MALLOCLOGSIZE; l++)
    174 		PRT;
    175 
    176 	for (l = 0; l < malloclogptr; l++)
    177 		PRT;
    178 }
    179 #endif /* MALLOCLOG */
    180 
    181 #ifdef DIAGNOSTIC
    182 /*
    183  * This structure provides a set of masks to catch unaligned frees.
    184  */
    185 const long addrmask[] = { 0,
    186 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
    187 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
    188 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
    189 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
    190 };
    191 
    192 /*
    193  * The WEIRD_ADDR is used as known text to copy into free objects so
    194  * that modifications after frees can be detected.
    195  */
    196 #define	WEIRD_ADDR	((uint32_t) 0xdeadbeef)
    197 #ifdef DEBUG
    198 #define	MAX_COPY	PAGE_SIZE
    199 #else
    200 #define	MAX_COPY	32
    201 #endif
    202 
    203 /*
    204  * Normally the freelist structure is used only to hold the list pointer
    205  * for free objects.  However, when running with diagnostics, the first
    206  * 8/16 bytes of the structure is unused except for diagnostic information,
    207  * and the free list pointer is at offset 8/16 in the structure.  Since the
    208  * first 8 bytes is the portion of the structure most often modified, this
    209  * helps to detect memory reuse problems and avoid free list corruption.
    210  */
    211 struct freelist {
    212 	uint32_t spare0;
    213 #ifdef _LP64
    214 	uint32_t spare1;		/* explicit padding */
    215 #endif
    216 	struct malloc_type *type;
    217 	caddr_t	next;
    218 };
    219 #else /* !DIAGNOSTIC */
    220 struct freelist {
    221 	caddr_t	next;
    222 };
    223 #endif /* DIAGNOSTIC */
    224 
    225 /*
    226  * The following are standard, build-in malloc types are are not
    227  * specific to any one subsystem.
    228  */
    229 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
    230 MALLOC_DEFINE(M_DMAMAP, "DMA map", "bus_dma(9) structures");
    231 MALLOC_DEFINE(M_FREE, "free", "should be on free list");
    232 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
    233 MALLOC_DEFINE(M_SOFTINTR, "softintr", "Softinterrupt structures");
    234 MALLOC_DEFINE(M_TEMP, "temp", "misc. temporary data buffers");
    235 
    236 /* XXX These should all be elsewhere. */
    237 MALLOC_DEFINE(M_RTABLE, "routetbl", "routing tables");
    238 MALLOC_DEFINE(M_FTABLE, "fragtbl", "fragment reassembly header");
    239 MALLOC_DEFINE(M_UFSMNT, "UFS mount", "UFS mount structure");
    240 MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
    241 MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
    242 MALLOC_DEFINE(M_IPMADDR, "in_multi", "internet multicast address");
    243 MALLOC_DEFINE(M_MRTABLE, "mrt", "multicast routing tables");
    244 MALLOC_DEFINE(M_1394DATA, "1394data", "IEEE 1394 data buffers");
    245 
    246 struct simplelock malloc_slock = SIMPLELOCK_INITIALIZER;
    247 
    248 /*
    249  * Allocate a block of memory
    250  */
    251 #ifdef MALLOCLOG
    252 void *
    253 _malloc(unsigned long size, struct malloc_type *ksp, int flags,
    254     const char *file, long line)
    255 #else
    256 void *
    257 malloc(unsigned long size, struct malloc_type *ksp, int flags)
    258 #endif /* MALLOCLOG */
    259 {
    260 	struct kmembuckets *kbp;
    261 	struct kmemusage *kup;
    262 	struct freelist *freep;
    263 	long indx, npg, allocsize;
    264 	int s;
    265 	caddr_t va, cp, savedlist;
    266 #ifdef DIAGNOSTIC
    267 	uint32_t *end, *lp;
    268 	int copysize;
    269 	const char *savedtype;
    270 #endif
    271 
    272 #ifdef LOCKDEBUG
    273 	if ((flags & M_NOWAIT) == 0)
    274 		simple_lock_only_held(NULL, "malloc");
    275 #endif
    276 #ifdef MALLOC_DEBUG
    277 	if (debug_malloc(size, ksp, flags, (void **) &va))
    278 		return ((void *) va);
    279 #endif
    280 	indx = BUCKETINDX(size);
    281 	kbp = &bucket[indx];
    282 	s = splvm();
    283 	simple_lock(&malloc_slock);
    284 #ifdef KMEMSTATS
    285 	while (ksp->ks_memuse >= ksp->ks_limit) {
    286 		if (flags & M_NOWAIT) {
    287 			simple_unlock(&malloc_slock);
    288 			splx(s);
    289 			return ((void *) NULL);
    290 		}
    291 		if (ksp->ks_limblocks < 65535)
    292 			ksp->ks_limblocks++;
    293 		ltsleep((caddr_t)ksp, PSWP+2, ksp->ks_shortdesc, 0,
    294 			&malloc_slock);
    295 	}
    296 	ksp->ks_size |= 1 << indx;
    297 #endif
    298 #ifdef DIAGNOSTIC
    299 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
    300 #endif
    301 	if (kbp->kb_next == NULL) {
    302 		kbp->kb_last = NULL;
    303 		if (size > MAXALLOCSAVE)
    304 			allocsize = round_page(size);
    305 		else
    306 			allocsize = 1 << indx;
    307 		npg = btoc(allocsize);
    308 		simple_unlock(&malloc_slock);
    309 		va = (caddr_t) uvm_km_kmemalloc(kmem_map, NULL,
    310 		    (vsize_t)ctob(npg),
    311 		    ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) |
    312 		    ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 0));
    313 		if (__predict_false(va == NULL)) {
    314 			/*
    315 			 * Kmem_malloc() can return NULL, even if it can
    316 			 * wait, if there is no map space avaiable, because
    317 			 * it can't fix that problem.  Neither can we,
    318 			 * right now.  (We should release pages which
    319 			 * are completely free and which are in buckets
    320 			 * with too many free elements.)
    321 			 */
    322 			if ((flags & (M_NOWAIT|M_CANFAIL)) == 0)
    323 				panic("malloc: out of space in kmem_map");
    324 			splx(s);
    325 			return (NULL);
    326 		}
    327 		simple_lock(&malloc_slock);
    328 #ifdef KMEMSTATS
    329 		kbp->kb_total += kbp->kb_elmpercl;
    330 #endif
    331 		kup = btokup(va);
    332 		kup->ku_indx = indx;
    333 		if (allocsize > MAXALLOCSAVE) {
    334 			if (npg > 65535)
    335 				panic("malloc: allocation too large");
    336 			kup->ku_pagecnt = npg;
    337 #ifdef KMEMSTATS
    338 			ksp->ks_memuse += allocsize;
    339 #endif
    340 			goto out;
    341 		}
    342 #ifdef KMEMSTATS
    343 		kup->ku_freecnt = kbp->kb_elmpercl;
    344 		kbp->kb_totalfree += kbp->kb_elmpercl;
    345 #endif
    346 		/*
    347 		 * Just in case we blocked while allocating memory,
    348 		 * and someone else also allocated memory for this
    349 		 * bucket, don't assume the list is still empty.
    350 		 */
    351 		savedlist = kbp->kb_next;
    352 		kbp->kb_next = cp = va + (npg << PAGE_SHIFT) - allocsize;
    353 		for (;;) {
    354 			freep = (struct freelist *)cp;
    355 #ifdef DIAGNOSTIC
    356 			/*
    357 			 * Copy in known text to detect modification
    358 			 * after freeing.
    359 			 */
    360 			end = (int32_t *)&cp[copysize];
    361 			for (lp = (int32_t *)cp; lp < end; lp++)
    362 				*lp = WEIRD_ADDR;
    363 			freep->type = M_FREE;
    364 #endif /* DIAGNOSTIC */
    365 			if (cp <= va)
    366 				break;
    367 			cp -= allocsize;
    368 			freep->next = cp;
    369 		}
    370 		freep->next = savedlist;
    371 		if (kbp->kb_last == NULL)
    372 			kbp->kb_last = (caddr_t)freep;
    373 	}
    374 	va = kbp->kb_next;
    375 	kbp->kb_next = ((struct freelist *)va)->next;
    376 #ifdef DIAGNOSTIC
    377 	freep = (struct freelist *)va;
    378 	/* XXX potential to get garbage pointer here. */
    379 	savedtype = freep->type->ks_shortdesc;
    380 	if (kbp->kb_next) {
    381 		int rv;
    382 		vaddr_t addr = (vaddr_t)kbp->kb_next;
    383 
    384 		vm_map_lock(kmem_map);
    385 		rv = uvm_map_checkprot(kmem_map, addr,
    386 		    addr + sizeof(struct freelist), VM_PROT_WRITE);
    387 		vm_map_unlock(kmem_map);
    388 
    389 		if (__predict_false(rv == 0)) {
    390 			printf("Data modified on freelist: "
    391 			    "word %ld of object %p size %ld previous type %s "
    392 			    "(invalid addr %p)\n",
    393 			    (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
    394 			    va, size, "foo", kbp->kb_next);
    395 #ifdef MALLOCLOG
    396 			hitmlog(va);
    397 #endif
    398 			kbp->kb_next = NULL;
    399 		}
    400 	}
    401 
    402 	/* Fill the fields that we've used with WEIRD_ADDR */
    403 #ifdef _LP64
    404 	freep->type = (struct malloc_type *)
    405 	    (WEIRD_ADDR | (((u_long) WEIRD_ADDR) << 32));
    406 #else
    407 	freep->type = (struct malloc_type *) WEIRD_ADDR;
    408 #endif
    409 	end = (int32_t *)&freep->next +
    410 	    (sizeof(freep->next) / sizeof(int32_t));
    411 	for (lp = (int32_t *)&freep->next; lp < end; lp++)
    412 		*lp = WEIRD_ADDR;
    413 
    414 	/* and check that the data hasn't been modified. */
    415 	end = (uint32_t *)&va[copysize];
    416 	for (lp = (int32_t *)va; lp < end; lp++) {
    417 		if (__predict_true(*lp == WEIRD_ADDR))
    418 			continue;
    419 		printf("Data modified on freelist: "
    420 		    "word %ld of object %p size %ld previous type %s "
    421 		    "(0x%x != 0x%x)\n",
    422 		    (long)(lp - (uint32_t *)va), va, size,
    423 		    "bar", *lp, WEIRD_ADDR);
    424 #ifdef MALLOCLOG
    425 		hitmlog(va);
    426 #endif
    427 		break;
    428 	}
    429 
    430 	freep->spare0 = 0;
    431 #endif /* DIAGNOSTIC */
    432 #ifdef KMEMSTATS
    433 	kup = btokup(va);
    434 	if (kup->ku_indx != indx)
    435 		panic("malloc: wrong bucket");
    436 	if (kup->ku_freecnt == 0)
    437 		panic("malloc: lost data");
    438 	kup->ku_freecnt--;
    439 	kbp->kb_totalfree--;
    440 	ksp->ks_memuse += 1 << indx;
    441 out:
    442 	kbp->kb_calls++;
    443 	ksp->ks_inuse++;
    444 	ksp->ks_calls++;
    445 	if (ksp->ks_memuse > ksp->ks_maxused)
    446 		ksp->ks_maxused = ksp->ks_memuse;
    447 #else
    448 out:
    449 #endif
    450 #ifdef MALLOCLOG
    451 	domlog(va, size, ksp, 1, file, line);
    452 #endif
    453 	simple_unlock(&malloc_slock);
    454 	splx(s);
    455 	if ((flags & M_ZERO) != 0)
    456 		memset(va, 0, size);
    457 	return ((void *) va);
    458 }
    459 
    460 /*
    461  * Free a block of memory allocated by malloc.
    462  */
    463 #ifdef MALLOCLOG
    464 void
    465 _free(void *addr, struct malloc_type *ksp, const char *file, long line)
    466 #else
    467 void
    468 free(void *addr, struct malloc_type *ksp)
    469 #endif /* MALLOCLOG */
    470 {
    471 	struct kmembuckets *kbp;
    472 	struct kmemusage *kup;
    473 	struct freelist *freep;
    474 	long size;
    475 	int s;
    476 #ifdef DIAGNOSTIC
    477 	caddr_t cp;
    478 	int32_t *end, *lp;
    479 	long alloc, copysize;
    480 #endif
    481 
    482 #ifdef MALLOC_DEBUG
    483 	if (debug_free(addr, ksp))
    484 		return;
    485 #endif
    486 
    487 #ifdef DIAGNOSTIC
    488 	/*
    489 	 * Ensure that we're free'ing something that we could
    490 	 * have allocated in the first place.  That is, check
    491 	 * to see that the address is within kmem_map.
    492 	 */
    493 	if (__predict_false((vaddr_t)addr < vm_map_min(kmem_map) ||
    494 	    (vaddr_t)addr >= vm_map_max(kmem_map)))
    495 		panic("free: addr %p not within kmem_map", addr);
    496 #endif
    497 
    498 	kup = btokup(addr);
    499 	size = 1 << kup->ku_indx;
    500 	kbp = &bucket[kup->ku_indx];
    501 	s = splvm();
    502 	simple_lock(&malloc_slock);
    503 #ifdef MALLOCLOG
    504 	domlog(addr, 0, ksp, 2, file, line);
    505 #endif
    506 #ifdef DIAGNOSTIC
    507 	/*
    508 	 * Check for returns of data that do not point to the
    509 	 * beginning of the allocation.
    510 	 */
    511 	if (size > PAGE_SIZE)
    512 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    513 	else
    514 		alloc = addrmask[kup->ku_indx];
    515 	if (((u_long)addr & alloc) != 0)
    516 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
    517 		    addr, size, ksp->ks_shortdesc, alloc);
    518 #endif /* DIAGNOSTIC */
    519 	if (size > MAXALLOCSAVE) {
    520 		uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
    521 #ifdef KMEMSTATS
    522 		size = kup->ku_pagecnt << PGSHIFT;
    523 		ksp->ks_memuse -= size;
    524 		kup->ku_indx = 0;
    525 		kup->ku_pagecnt = 0;
    526 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
    527 		    ksp->ks_memuse < ksp->ks_limit)
    528 			wakeup((caddr_t)ksp);
    529 #ifdef DIAGNOSTIC
    530 		if (ksp->ks_inuse == 0)
    531 			panic("free 1: inuse 0, probable double free");
    532 #endif
    533 		ksp->ks_inuse--;
    534 		kbp->kb_total -= 1;
    535 #endif
    536 		simple_unlock(&malloc_slock);
    537 		splx(s);
    538 		return;
    539 	}
    540 	freep = (struct freelist *)addr;
    541 #ifdef DIAGNOSTIC
    542 	/*
    543 	 * Check for multiple frees. Use a quick check to see if
    544 	 * it looks free before laboriously searching the freelist.
    545 	 */
    546 	if (__predict_false(freep->spare0 == WEIRD_ADDR)) {
    547 		for (cp = kbp->kb_next; cp;
    548 		    cp = ((struct freelist *)cp)->next) {
    549 			if (addr != cp)
    550 				continue;
    551 			printf("multiply freed item %p\n", addr);
    552 #ifdef MALLOCLOG
    553 			hitmlog(addr);
    554 #endif
    555 			panic("free: duplicated free");
    556 		}
    557 	}
    558 #ifdef LOCKDEBUG
    559 	/*
    560 	 * Check if we're freeing a locked simple lock.
    561 	 */
    562 	simple_lock_freecheck(addr, (char *)addr + size);
    563 #endif
    564 	/*
    565 	 * Copy in known text to detect modification after freeing
    566 	 * and to make it look free. Also, save the type being freed
    567 	 * so we can list likely culprit if modification is detected
    568 	 * when the object is reallocated.
    569 	 */
    570 	copysize = size < MAX_COPY ? size : MAX_COPY;
    571 	end = (int32_t *)&((caddr_t)addr)[copysize];
    572 	for (lp = (int32_t *)addr; lp < end; lp++)
    573 		*lp = WEIRD_ADDR;
    574 	freep->type = ksp;
    575 #endif /* DIAGNOSTIC */
    576 #ifdef KMEMSTATS
    577 	kup->ku_freecnt++;
    578 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
    579 		if (kup->ku_freecnt > kbp->kb_elmpercl)
    580 			panic("free: multiple frees");
    581 		else if (kbp->kb_totalfree > kbp->kb_highwat)
    582 			kbp->kb_couldfree++;
    583 	}
    584 	kbp->kb_totalfree++;
    585 	ksp->ks_memuse -= size;
    586 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
    587 	    ksp->ks_memuse < ksp->ks_limit)
    588 		wakeup((caddr_t)ksp);
    589 #ifdef DIAGNOSTIC
    590 	if (ksp->ks_inuse == 0)
    591 		panic("free 2: inuse 0, probable double free");
    592 #endif
    593 	ksp->ks_inuse--;
    594 #endif
    595 	if (kbp->kb_next == NULL)
    596 		kbp->kb_next = addr;
    597 	else
    598 		((struct freelist *)kbp->kb_last)->next = addr;
    599 	freep->next = NULL;
    600 	kbp->kb_last = addr;
    601 	simple_unlock(&malloc_slock);
    602 	splx(s);
    603 }
    604 
    605 /*
    606  * Change the size of a block of memory.
    607  */
    608 void *
    609 realloc(void *curaddr, unsigned long newsize, struct malloc_type *ksp,
    610     int flags)
    611 {
    612 	struct kmemusage *kup;
    613 	unsigned long cursize;
    614 	void *newaddr;
    615 #ifdef DIAGNOSTIC
    616 	long alloc;
    617 #endif
    618 
    619 	/*
    620 	 * realloc() with a NULL pointer is the same as malloc().
    621 	 */
    622 	if (curaddr == NULL)
    623 		return (malloc(newsize, ksp, flags));
    624 
    625 	/*
    626 	 * realloc() with zero size is the same as free().
    627 	 */
    628 	if (newsize == 0) {
    629 		free(curaddr, ksp);
    630 		return (NULL);
    631 	}
    632 
    633 #ifdef LOCKDEBUG
    634 	if ((flags & M_NOWAIT) == 0)
    635 		simple_lock_only_held(NULL, "realloc");
    636 #endif
    637 
    638 	/*
    639 	 * Find out how large the old allocation was (and do some
    640 	 * sanity checking).
    641 	 */
    642 	kup = btokup(curaddr);
    643 	cursize = 1 << kup->ku_indx;
    644 
    645 #ifdef DIAGNOSTIC
    646 	/*
    647 	 * Check for returns of data that do not point to the
    648 	 * beginning of the allocation.
    649 	 */
    650 	if (cursize > PAGE_SIZE)
    651 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    652 	else
    653 		alloc = addrmask[kup->ku_indx];
    654 	if (((u_long)curaddr & alloc) != 0)
    655 		panic("realloc: "
    656 		    "unaligned addr %p, size %ld, type %s, mask %ld\n",
    657 		    curaddr, cursize, ksp->ks_shortdesc, alloc);
    658 #endif /* DIAGNOSTIC */
    659 
    660 	if (cursize > MAXALLOCSAVE)
    661 		cursize = ctob(kup->ku_pagecnt);
    662 
    663 	/*
    664 	 * If we already actually have as much as they want, we're done.
    665 	 */
    666 	if (newsize <= cursize)
    667 		return (curaddr);
    668 
    669 	/*
    670 	 * Can't satisfy the allocation with the existing block.
    671 	 * Allocate a new one and copy the data.
    672 	 */
    673 	newaddr = malloc(newsize, ksp, flags);
    674 	if (__predict_false(newaddr == NULL)) {
    675 		/*
    676 		 * malloc() failed, because flags included M_NOWAIT.
    677 		 * Return NULL to indicate that failure.  The old
    678 		 * pointer is still valid.
    679 		 */
    680 		return (NULL);
    681 	}
    682 	memcpy(newaddr, curaddr, cursize);
    683 
    684 	/*
    685 	 * We were successful: free the old allocation and return
    686 	 * the new one.
    687 	 */
    688 	free(curaddr, ksp);
    689 	return (newaddr);
    690 }
    691 
    692 /*
    693  * Roundup size to the actual allocation size.
    694  */
    695 unsigned long
    696 malloc_roundup(unsigned long size)
    697 {
    698 
    699 	if (size > MAXALLOCSAVE)
    700 		return (roundup(size, PAGE_SIZE));
    701 	else
    702 		return (1 << BUCKETINDX(size));
    703 }
    704 
    705 /*
    706  * Add a malloc type to the system.
    707  */
    708 void
    709 malloc_type_attach(struct malloc_type *type)
    710 {
    711 
    712 	if (nkmempages == 0)
    713 		panic("malloc_type_attach: nkmempages == 0");
    714 
    715 	if (type->ks_magic != M_MAGIC)
    716 		panic("malloc_type_attach: bad magic");
    717 
    718 #ifdef DIAGNOSTIC
    719 	{
    720 		struct malloc_type *ksp;
    721 		for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
    722 			if (ksp == type)
    723 				panic("malloc_type_attach: already on list");
    724 		}
    725 	}
    726 #endif
    727 
    728 #ifdef KMEMSTATS
    729 	if (type->ks_limit == 0)
    730 		type->ks_limit = ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
    731 #else
    732 	type->ks_limit = 0;
    733 #endif
    734 
    735 	type->ks_next = kmemstatistics;
    736 	kmemstatistics = type;
    737 }
    738 
    739 /*
    740  * Remove a malloc type from the system..
    741  */
    742 void
    743 malloc_type_detach(struct malloc_type *type)
    744 {
    745 	struct malloc_type *ksp;
    746 
    747 #ifdef DIAGNOSTIC
    748 	if (type->ks_magic != M_MAGIC)
    749 		panic("malloc_type_detach: bad magic");
    750 #endif
    751 
    752 	if (type == kmemstatistics)
    753 		kmemstatistics = type->ks_next;
    754 	else {
    755 		for (ksp = kmemstatistics; ksp->ks_next != NULL;
    756 		     ksp = ksp->ks_next) {
    757 			if (ksp->ks_next == type) {
    758 				ksp->ks_next = type->ks_next;
    759 				break;
    760 			}
    761 		}
    762 #ifdef DIAGNOSTIC
    763 		if (ksp->ks_next == NULL)
    764 			panic("malloc_type_detach: not on list");
    765 #endif
    766 	}
    767 	type->ks_next = NULL;
    768 }
    769 
    770 /*
    771  * Set the limit on a malloc type.
    772  */
    773 void
    774 malloc_type_setlimit(struct malloc_type *type, u_long limit)
    775 {
    776 #ifdef KMEMSTATS
    777 	int s;
    778 
    779 	s = splvm();
    780 	type->ks_limit = limit;
    781 	splx(s);
    782 #endif
    783 }
    784 
    785 /*
    786  * Compute the number of pages that kmem_map will map, that is,
    787  * the size of the kernel malloc arena.
    788  */
    789 void
    790 kmeminit_nkmempages(void)
    791 {
    792 	int npages;
    793 
    794 	if (nkmempages != 0) {
    795 		/*
    796 		 * It's already been set (by us being here before, or
    797 		 * by patching or kernel config options), bail out now.
    798 		 */
    799 		return;
    800 	}
    801 
    802 	/*
    803 	 * We use the following (simple) formula:
    804 	 *
    805 	 *	- Starting point is physical memory / 4.
    806 	 *
    807 	 *	- Clamp it down to NKMEMPAGES_MAX.
    808 	 *
    809 	 *	- Round it up to NKMEMPAGES_MIN.
    810 	 */
    811 	npages = physmem / 4;
    812 
    813 	if (npages > NKMEMPAGES_MAX)
    814 		npages = NKMEMPAGES_MAX;
    815 
    816 	if (npages < NKMEMPAGES_MIN)
    817 		npages = NKMEMPAGES_MIN;
    818 
    819 	nkmempages = npages;
    820 }
    821 
    822 /*
    823  * Initialize the kernel memory allocator
    824  */
    825 void
    826 kmeminit(void)
    827 {
    828 	__link_set_decl(malloc_types, struct malloc_type);
    829 	struct malloc_type * const *ksp;
    830 	vaddr_t kmb, kml;
    831 #ifdef KMEMSTATS
    832 	long indx;
    833 #endif
    834 
    835 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
    836 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
    837 #endif
    838 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
    839 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
    840 #endif
    841 #if	(MAXALLOCSAVE < NBPG)
    842 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
    843 #endif
    844 
    845 	if (sizeof(struct freelist) > (1 << MINBUCKET))
    846 		panic("minbucket too small/struct freelist too big");
    847 
    848 	/*
    849 	 * Compute the number of kmem_map pages, if we have not
    850 	 * done so already.
    851 	 */
    852 	kmeminit_nkmempages();
    853 
    854 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
    855 	    (vsize_t)(nkmempages * sizeof(struct kmemusage)));
    856 	kmb = 0;
    857 	kmem_map = uvm_km_suballoc(kernel_map, &kmb,
    858 	    &kml, (vsize_t)(nkmempages << PAGE_SHIFT),
    859 	    VM_MAP_INTRSAFE, FALSE, &kmem_map_store);
    860 	kmembase = (char *)kmb;
    861 	kmemlimit = (char *)kml;
    862 #ifdef KMEMSTATS
    863 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
    864 		if (1 << indx >= PAGE_SIZE)
    865 			bucket[indx].kb_elmpercl = 1;
    866 		else
    867 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
    868 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
    869 	}
    870 #endif
    871 
    872 	/* Attach all of the statically-linked malloc types. */
    873 	__link_set_foreach(ksp, malloc_types)
    874 		malloc_type_attach(*ksp);
    875 
    876 #ifdef MALLOC_DEBUG
    877 	debug_malloc_init();
    878 #endif
    879 }
    880 
    881 #ifdef DDB
    882 #include <ddb/db_output.h>
    883 
    884 /*
    885  * Dump kmem statistics from ddb.
    886  *
    887  * usage: call dump_kmemstats
    888  */
    889 void	dump_kmemstats(void);
    890 
    891 void
    892 dump_kmemstats(void)
    893 {
    894 #ifdef KMEMSTATS
    895 	struct malloc_type *ksp;
    896 
    897 	for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
    898 		if (ksp->ks_memuse == 0)
    899 			continue;
    900 		db_printf("%s%.*s %ld\n", ksp->ks_shortdesc,
    901 		    (int)(20 - strlen(ksp->ks_shortdesc)),
    902 		    "                    ",
    903 		    ksp->ks_memuse);
    904 	}
    905 #else
    906 	db_printf("Kmem stats are not being collected.\n");
    907 #endif /* KMEMSTATS */
    908 }
    909 #endif /* DDB */
    910 
    911 
    912 #if 0
    913 /*
    914  * Diagnostic messages about "Data modified on
    915  * freelist" indicate a memory corruption, but
    916  * they do not help tracking it down.
    917  * This function can be called at various places
    918  * to sanity check malloc's freelist and discover
    919  * where does the corruption take place.
    920  */
    921 int
    922 freelist_sanitycheck(void) {
    923 	int i,j;
    924 	struct kmembuckets *kbp;
    925 	struct freelist *freep;
    926 	int rv = 0;
    927 
    928 	for (i = MINBUCKET; i <= MINBUCKET + 15; i++) {
    929 		kbp = &bucket[i];
    930 		freep = (struct freelist *)kbp->kb_next;
    931 		j = 0;
    932 		while(freep) {
    933 			vm_map_lock(kmem_map);
    934 			rv = uvm_map_checkprot(kmem_map, (vaddr_t)freep,
    935 			    (vaddr_t)freep + sizeof(struct freelist),
    936 			    VM_PROT_WRITE);
    937 			vm_map_unlock(kmem_map);
    938 
    939 			if ((rv == 0) || (*(int *)freep != WEIRD_ADDR)) {
    940 				printf("bucket %i, chunck %d at %p modified\n",
    941 				    i, j, freep);
    942 				return 1;
    943 			}
    944 			freep = (struct freelist *)freep->next;
    945 			j++;
    946 		}
    947 	}
    948 
    949 	return 0;
    950 }
    951 #endif
    952