Home | History | Annotate | Line # | Download | only in kern
kern_malloc.c revision 1.88
      1 /*	$NetBSD: kern_malloc.c,v 1.88 2003/09/27 23:10:47 mycroft 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.88 2003/09/27 23:10:47 mycroft 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 	lp = &malloclog[l]; \
    162 	if (lp->addr == a && lp->action) { \
    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 #undef PRT
    179 }
    180 #endif /* MALLOCLOG */
    181 
    182 #ifdef DIAGNOSTIC
    183 /*
    184  * This structure provides a set of masks to catch unaligned frees.
    185  */
    186 const long addrmask[] = { 0,
    187 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
    188 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
    189 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
    190 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
    191 };
    192 
    193 /*
    194  * The WEIRD_ADDR is used as known text to copy into free objects so
    195  * that modifications after frees can be detected.
    196  */
    197 #define	WEIRD_ADDR	((uint32_t) 0xdeadbeef)
    198 #ifdef DEBUG
    199 #define	MAX_COPY	PAGE_SIZE
    200 #else
    201 #define	MAX_COPY	32
    202 #endif
    203 
    204 /*
    205  * Normally the freelist structure is used only to hold the list pointer
    206  * for free objects.  However, when running with diagnostics, the first
    207  * 8/16 bytes of the structure is unused except for diagnostic information,
    208  * and the free list pointer is at offset 8/16 in the structure.  Since the
    209  * first 8 bytes is the portion of the structure most often modified, this
    210  * helps to detect memory reuse problems and avoid free list corruption.
    211  */
    212 struct freelist {
    213 	uint32_t spare0;
    214 #ifdef _LP64
    215 	uint32_t spare1;		/* explicit padding */
    216 #endif
    217 	struct malloc_type *type;
    218 	caddr_t	next;
    219 };
    220 #else /* !DIAGNOSTIC */
    221 struct freelist {
    222 	caddr_t	next;
    223 };
    224 #endif /* DIAGNOSTIC */
    225 
    226 /*
    227  * The following are standard, build-in malloc types are are not
    228  * specific to any one subsystem.
    229  */
    230 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
    231 MALLOC_DEFINE(M_DMAMAP, "DMA map", "bus_dma(9) structures");
    232 MALLOC_DEFINE(M_FREE, "free", "should be on free list");
    233 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
    234 MALLOC_DEFINE(M_SOFTINTR, "softintr", "Softinterrupt structures");
    235 MALLOC_DEFINE(M_TEMP, "temp", "misc. temporary data buffers");
    236 
    237 /* XXX These should all be elsewhere. */
    238 MALLOC_DEFINE(M_RTABLE, "routetbl", "routing tables");
    239 MALLOC_DEFINE(M_FTABLE, "fragtbl", "fragment reassembly header");
    240 MALLOC_DEFINE(M_UFSMNT, "UFS mount", "UFS mount structure");
    241 MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
    242 MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
    243 MALLOC_DEFINE(M_IPMADDR, "in_multi", "internet multicast address");
    244 MALLOC_DEFINE(M_MRTABLE, "mrt", "multicast routing tables");
    245 MALLOC_DEFINE(M_1394DATA, "1394data", "IEEE 1394 data buffers");
    246 
    247 struct simplelock malloc_slock = SIMPLELOCK_INITIALIZER;
    248 
    249 /*
    250  * Allocate a block of memory
    251  */
    252 #ifdef MALLOCLOG
    253 void *
    254 _malloc(unsigned long size, struct malloc_type *ksp, int flags,
    255     const char *file, long line)
    256 #else
    257 void *
    258 malloc(unsigned long size, struct malloc_type *ksp, int flags)
    259 #endif /* MALLOCLOG */
    260 {
    261 	struct kmembuckets *kbp;
    262 	struct kmemusage *kup;
    263 	struct freelist *freep;
    264 	long indx, npg, allocsize;
    265 	int s;
    266 	caddr_t va, cp, savedlist;
    267 #ifdef DIAGNOSTIC
    268 	uint32_t *end, *lp;
    269 	int copysize;
    270 	const char *savedtype;
    271 #endif
    272 
    273 #ifdef LOCKDEBUG
    274 	if ((flags & M_NOWAIT) == 0)
    275 		simple_lock_only_held(NULL, "malloc");
    276 #endif
    277 #ifdef MALLOC_DEBUG
    278 	if (debug_malloc(size, ksp, flags, (void *) &va))
    279 		return ((void *) va);
    280 #endif
    281 	indx = BUCKETINDX(size);
    282 	kbp = &bucket[indx];
    283 	s = splvm();
    284 	simple_lock(&malloc_slock);
    285 #ifdef KMEMSTATS
    286 	while (ksp->ks_memuse >= ksp->ks_limit) {
    287 		if (flags & M_NOWAIT) {
    288 			simple_unlock(&malloc_slock);
    289 			splx(s);
    290 			return ((void *) NULL);
    291 		}
    292 		if (ksp->ks_limblocks < 65535)
    293 			ksp->ks_limblocks++;
    294 		ltsleep((caddr_t)ksp, PSWP+2, ksp->ks_shortdesc, 0,
    295 			&malloc_slock);
    296 	}
    297 	ksp->ks_size |= 1 << indx;
    298 #endif
    299 #ifdef DIAGNOSTIC
    300 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
    301 #endif
    302 	if (kbp->kb_next == NULL) {
    303 		kbp->kb_last = NULL;
    304 		if (size > MAXALLOCSAVE)
    305 			allocsize = round_page(size);
    306 		else
    307 			allocsize = 1 << indx;
    308 		npg = btoc(allocsize);
    309 		simple_unlock(&malloc_slock);
    310 		va = (caddr_t) uvm_km_kmemalloc(kmem_map, NULL,
    311 		    (vsize_t)ctob(npg),
    312 		    ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) |
    313 		    ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 0));
    314 		if (__predict_false(va == NULL)) {
    315 			/*
    316 			 * Kmem_malloc() can return NULL, even if it can
    317 			 * wait, if there is no map space avaiable, because
    318 			 * it can't fix that problem.  Neither can we,
    319 			 * right now.  (We should release pages which
    320 			 * are completely free and which are in buckets
    321 			 * with too many free elements.)
    322 			 */
    323 			if ((flags & (M_NOWAIT|M_CANFAIL)) == 0)
    324 				panic("malloc: out of space in kmem_map");
    325 			splx(s);
    326 			return (NULL);
    327 		}
    328 		simple_lock(&malloc_slock);
    329 #ifdef KMEMSTATS
    330 		kbp->kb_total += kbp->kb_elmpercl;
    331 #endif
    332 		kup = btokup(va);
    333 		kup->ku_indx = indx;
    334 		if (allocsize > MAXALLOCSAVE) {
    335 			if (npg > 65535)
    336 				panic("malloc: allocation too large");
    337 			kup->ku_pagecnt = npg;
    338 #ifdef KMEMSTATS
    339 			ksp->ks_memuse += allocsize;
    340 #endif
    341 			goto out;
    342 		}
    343 #ifdef KMEMSTATS
    344 		kup->ku_freecnt = kbp->kb_elmpercl;
    345 		kbp->kb_totalfree += kbp->kb_elmpercl;
    346 #endif
    347 		/*
    348 		 * Just in case we blocked while allocating memory,
    349 		 * and someone else also allocated memory for this
    350 		 * bucket, don't assume the list is still empty.
    351 		 */
    352 		savedlist = kbp->kb_next;
    353 		kbp->kb_next = cp = va + (npg << PAGE_SHIFT) - allocsize;
    354 		for (;;) {
    355 			freep = (struct freelist *)cp;
    356 #ifdef DIAGNOSTIC
    357 			/*
    358 			 * Copy in known text to detect modification
    359 			 * after freeing.
    360 			 */
    361 			end = (uint32_t *)&cp[copysize];
    362 			for (lp = (uint32_t *)cp; lp < end; lp++)
    363 				*lp = WEIRD_ADDR;
    364 			freep->type = M_FREE;
    365 #endif /* DIAGNOSTIC */
    366 			if (cp <= va)
    367 				break;
    368 			cp -= allocsize;
    369 			freep->next = cp;
    370 		}
    371 		freep->next = savedlist;
    372 		if (kbp->kb_last == NULL)
    373 			kbp->kb_last = (caddr_t)freep;
    374 	}
    375 	va = kbp->kb_next;
    376 	kbp->kb_next = ((struct freelist *)va)->next;
    377 #ifdef DIAGNOSTIC
    378 	freep = (struct freelist *)va;
    379 	/* XXX potential to get garbage pointer here. */
    380 	savedtype = freep->type->ks_shortdesc;
    381 	if (kbp->kb_next) {
    382 		int rv;
    383 		vaddr_t addr = (vaddr_t)kbp->kb_next;
    384 
    385 		vm_map_lock(kmem_map);
    386 		rv = uvm_map_checkprot(kmem_map, addr,
    387 		    addr + sizeof(struct freelist), VM_PROT_WRITE);
    388 		vm_map_unlock(kmem_map);
    389 
    390 		if (__predict_false(rv == 0)) {
    391 			printf("Data modified on freelist: "
    392 			    "word %ld of object %p size %ld previous type %s "
    393 			    "(invalid addr %p)\n",
    394 			    (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
    395 			    va, size, "foo", kbp->kb_next);
    396 #ifdef MALLOCLOG
    397 			hitmlog(va);
    398 #endif
    399 			kbp->kb_next = NULL;
    400 		}
    401 	}
    402 
    403 	/* Fill the fields that we've used with WEIRD_ADDR */
    404 #ifdef _LP64
    405 	freep->type = (struct malloc_type *)
    406 	    (WEIRD_ADDR | (((u_long) WEIRD_ADDR) << 32));
    407 #else
    408 	freep->type = (struct malloc_type *) WEIRD_ADDR;
    409 #endif
    410 	end = (uint32_t *)&freep->next +
    411 	    (sizeof(freep->next) / sizeof(int32_t));
    412 	for (lp = (uint32_t *)&freep->next; lp < end; lp++)
    413 		*lp = WEIRD_ADDR;
    414 
    415 	/* and check that the data hasn't been modified. */
    416 	end = (uint32_t *)&va[copysize];
    417 	for (lp = (uint32_t *)va; lp < end; lp++) {
    418 		if (__predict_true(*lp == WEIRD_ADDR))
    419 			continue;
    420 		printf("Data modified on freelist: "
    421 		    "word %ld of object %p size %ld previous type %s "
    422 		    "(0x%x != 0x%x)\n",
    423 		    (long)(lp - (uint32_t *)va), va, size,
    424 		    "bar", *lp, WEIRD_ADDR);
    425 #ifdef MALLOCLOG
    426 		hitmlog(va);
    427 #endif
    428 		break;
    429 	}
    430 
    431 	freep->spare0 = 0;
    432 #endif /* DIAGNOSTIC */
    433 #ifdef KMEMSTATS
    434 	kup = btokup(va);
    435 	if (kup->ku_indx != indx)
    436 		panic("malloc: wrong bucket");
    437 	if (kup->ku_freecnt == 0)
    438 		panic("malloc: lost data");
    439 	kup->ku_freecnt--;
    440 	kbp->kb_totalfree--;
    441 	ksp->ks_memuse += 1 << indx;
    442 out:
    443 	kbp->kb_calls++;
    444 	ksp->ks_inuse++;
    445 	ksp->ks_calls++;
    446 	if (ksp->ks_memuse > ksp->ks_maxused)
    447 		ksp->ks_maxused = ksp->ks_memuse;
    448 #else
    449 out:
    450 #endif
    451 #ifdef MALLOCLOG
    452 	domlog(va, size, ksp, 1, file, line);
    453 #endif
    454 	simple_unlock(&malloc_slock);
    455 	splx(s);
    456 	if ((flags & M_ZERO) != 0)
    457 		memset(va, 0, size);
    458 	return ((void *) va);
    459 }
    460 
    461 /*
    462  * Free a block of memory allocated by malloc.
    463  */
    464 #ifdef MALLOCLOG
    465 void
    466 _free(void *addr, struct malloc_type *ksp, const char *file, long line)
    467 #else
    468 void
    469 free(void *addr, struct malloc_type *ksp)
    470 #endif /* MALLOCLOG */
    471 {
    472 	struct kmembuckets *kbp;
    473 	struct kmemusage *kup;
    474 	struct freelist *freep;
    475 	long size;
    476 	int s;
    477 #ifdef DIAGNOSTIC
    478 	caddr_t cp;
    479 	int32_t *end, *lp;
    480 	long alloc, copysize;
    481 #endif
    482 
    483 #ifdef MALLOC_DEBUG
    484 	if (debug_free(addr, ksp))
    485 		return;
    486 #endif
    487 
    488 #ifdef DIAGNOSTIC
    489 	/*
    490 	 * Ensure that we're free'ing something that we could
    491 	 * have allocated in the first place.  That is, check
    492 	 * to see that the address is within kmem_map.
    493 	 */
    494 	if (__predict_false((vaddr_t)addr < vm_map_min(kmem_map) ||
    495 	    (vaddr_t)addr >= vm_map_max(kmem_map)))
    496 		panic("free: addr %p not within kmem_map", addr);
    497 #endif
    498 
    499 	kup = btokup(addr);
    500 	size = 1 << kup->ku_indx;
    501 	kbp = &bucket[kup->ku_indx];
    502 	s = splvm();
    503 	simple_lock(&malloc_slock);
    504 #ifdef MALLOCLOG
    505 	domlog(addr, 0, ksp, 2, file, line);
    506 #endif
    507 #ifdef DIAGNOSTIC
    508 	/*
    509 	 * Check for returns of data that do not point to the
    510 	 * beginning of the allocation.
    511 	 */
    512 	if (size > PAGE_SIZE)
    513 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    514 	else
    515 		alloc = addrmask[kup->ku_indx];
    516 	if (((u_long)addr & alloc) != 0)
    517 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
    518 		    addr, size, ksp->ks_shortdesc, alloc);
    519 #endif /* DIAGNOSTIC */
    520 	if (size > MAXALLOCSAVE) {
    521 		uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
    522 #ifdef KMEMSTATS
    523 		size = kup->ku_pagecnt << PGSHIFT;
    524 		ksp->ks_memuse -= size;
    525 		kup->ku_indx = 0;
    526 		kup->ku_pagecnt = 0;
    527 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
    528 		    ksp->ks_memuse < ksp->ks_limit)
    529 			wakeup((caddr_t)ksp);
    530 #ifdef DIAGNOSTIC
    531 		if (ksp->ks_inuse == 0)
    532 			panic("free 1: inuse 0, probable double free");
    533 #endif
    534 		ksp->ks_inuse--;
    535 		kbp->kb_total -= 1;
    536 #endif
    537 		simple_unlock(&malloc_slock);
    538 		splx(s);
    539 		return;
    540 	}
    541 	freep = (struct freelist *)addr;
    542 #ifdef DIAGNOSTIC
    543 	/*
    544 	 * Check for multiple frees. Use a quick check to see if
    545 	 * it looks free before laboriously searching the freelist.
    546 	 */
    547 	if (__predict_false(freep->spare0 == WEIRD_ADDR)) {
    548 		for (cp = kbp->kb_next; cp;
    549 		    cp = ((struct freelist *)cp)->next) {
    550 			if (addr != cp)
    551 				continue;
    552 			printf("multiply freed item %p\n", addr);
    553 #ifdef MALLOCLOG
    554 			hitmlog(addr);
    555 #endif
    556 			panic("free: duplicated free");
    557 		}
    558 	}
    559 #ifdef LOCKDEBUG
    560 	/*
    561 	 * Check if we're freeing a locked simple lock.
    562 	 */
    563 	simple_lock_freecheck(addr, (char *)addr + size);
    564 #endif
    565 	/*
    566 	 * Copy in known text to detect modification after freeing
    567 	 * and to make it look free. Also, save the type being freed
    568 	 * so we can list likely culprit if modification is detected
    569 	 * when the object is reallocated.
    570 	 */
    571 	copysize = size < MAX_COPY ? size : MAX_COPY;
    572 	end = (int32_t *)&((caddr_t)addr)[copysize];
    573 	for (lp = (int32_t *)addr; lp < end; lp++)
    574 		*lp = WEIRD_ADDR;
    575 	freep->type = ksp;
    576 #endif /* DIAGNOSTIC */
    577 #ifdef KMEMSTATS
    578 	kup->ku_freecnt++;
    579 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
    580 		if (kup->ku_freecnt > kbp->kb_elmpercl)
    581 			panic("free: multiple frees");
    582 		else if (kbp->kb_totalfree > kbp->kb_highwat)
    583 			kbp->kb_couldfree++;
    584 	}
    585 	kbp->kb_totalfree++;
    586 	ksp->ks_memuse -= size;
    587 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
    588 	    ksp->ks_memuse < ksp->ks_limit)
    589 		wakeup((caddr_t)ksp);
    590 #ifdef DIAGNOSTIC
    591 	if (ksp->ks_inuse == 0)
    592 		panic("free 2: inuse 0, probable double free");
    593 #endif
    594 	ksp->ks_inuse--;
    595 #endif
    596 	if (kbp->kb_next == NULL)
    597 		kbp->kb_next = addr;
    598 	else
    599 		((struct freelist *)kbp->kb_last)->next = addr;
    600 	freep->next = NULL;
    601 	kbp->kb_last = addr;
    602 	simple_unlock(&malloc_slock);
    603 	splx(s);
    604 }
    605 
    606 /*
    607  * Change the size of a block of memory.
    608  */
    609 void *
    610 realloc(void *curaddr, unsigned long newsize, struct malloc_type *ksp,
    611     int flags)
    612 {
    613 	struct kmemusage *kup;
    614 	unsigned long cursize;
    615 	void *newaddr;
    616 #ifdef DIAGNOSTIC
    617 	long alloc;
    618 #endif
    619 
    620 	/*
    621 	 * realloc() with a NULL pointer is the same as malloc().
    622 	 */
    623 	if (curaddr == NULL)
    624 		return (malloc(newsize, ksp, flags));
    625 
    626 	/*
    627 	 * realloc() with zero size is the same as free().
    628 	 */
    629 	if (newsize == 0) {
    630 		free(curaddr, ksp);
    631 		return (NULL);
    632 	}
    633 
    634 #ifdef LOCKDEBUG
    635 	if ((flags & M_NOWAIT) == 0)
    636 		simple_lock_only_held(NULL, "realloc");
    637 #endif
    638 
    639 	/*
    640 	 * Find out how large the old allocation was (and do some
    641 	 * sanity checking).
    642 	 */
    643 	kup = btokup(curaddr);
    644 	cursize = 1 << kup->ku_indx;
    645 
    646 #ifdef DIAGNOSTIC
    647 	/*
    648 	 * Check for returns of data that do not point to the
    649 	 * beginning of the allocation.
    650 	 */
    651 	if (cursize > PAGE_SIZE)
    652 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    653 	else
    654 		alloc = addrmask[kup->ku_indx];
    655 	if (((u_long)curaddr & alloc) != 0)
    656 		panic("realloc: "
    657 		    "unaligned addr %p, size %ld, type %s, mask %ld\n",
    658 		    curaddr, cursize, ksp->ks_shortdesc, alloc);
    659 #endif /* DIAGNOSTIC */
    660 
    661 	if (cursize > MAXALLOCSAVE)
    662 		cursize = ctob(kup->ku_pagecnt);
    663 
    664 	/*
    665 	 * If we already actually have as much as they want, we're done.
    666 	 */
    667 	if (newsize <= cursize)
    668 		return (curaddr);
    669 
    670 	/*
    671 	 * Can't satisfy the allocation with the existing block.
    672 	 * Allocate a new one and copy the data.
    673 	 */
    674 	newaddr = malloc(newsize, ksp, flags);
    675 	if (__predict_false(newaddr == NULL)) {
    676 		/*
    677 		 * malloc() failed, because flags included M_NOWAIT.
    678 		 * Return NULL to indicate that failure.  The old
    679 		 * pointer is still valid.
    680 		 */
    681 		return (NULL);
    682 	}
    683 	memcpy(newaddr, curaddr, cursize);
    684 
    685 	/*
    686 	 * We were successful: free the old allocation and return
    687 	 * the new one.
    688 	 */
    689 	free(curaddr, ksp);
    690 	return (newaddr);
    691 }
    692 
    693 /*
    694  * Roundup size to the actual allocation size.
    695  */
    696 unsigned long
    697 malloc_roundup(unsigned long size)
    698 {
    699 
    700 	if (size > MAXALLOCSAVE)
    701 		return (roundup(size, PAGE_SIZE));
    702 	else
    703 		return (1 << BUCKETINDX(size));
    704 }
    705 
    706 /*
    707  * Add a malloc type to the system.
    708  */
    709 void
    710 malloc_type_attach(struct malloc_type *type)
    711 {
    712 
    713 	if (nkmempages == 0)
    714 		panic("malloc_type_attach: nkmempages == 0");
    715 
    716 	if (type->ks_magic != M_MAGIC)
    717 		panic("malloc_type_attach: bad magic");
    718 
    719 #ifdef DIAGNOSTIC
    720 	{
    721 		struct malloc_type *ksp;
    722 		for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
    723 			if (ksp == type)
    724 				panic("malloc_type_attach: already on list");
    725 		}
    726 	}
    727 #endif
    728 
    729 #ifdef KMEMSTATS
    730 	if (type->ks_limit == 0)
    731 		type->ks_limit = ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
    732 #else
    733 	type->ks_limit = 0;
    734 #endif
    735 
    736 	type->ks_next = kmemstatistics;
    737 	kmemstatistics = type;
    738 }
    739 
    740 /*
    741  * Remove a malloc type from the system..
    742  */
    743 void
    744 malloc_type_detach(struct malloc_type *type)
    745 {
    746 	struct malloc_type *ksp;
    747 
    748 #ifdef DIAGNOSTIC
    749 	if (type->ks_magic != M_MAGIC)
    750 		panic("malloc_type_detach: bad magic");
    751 #endif
    752 
    753 	if (type == kmemstatistics)
    754 		kmemstatistics = type->ks_next;
    755 	else {
    756 		for (ksp = kmemstatistics; ksp->ks_next != NULL;
    757 		     ksp = ksp->ks_next) {
    758 			if (ksp->ks_next == type) {
    759 				ksp->ks_next = type->ks_next;
    760 				break;
    761 			}
    762 		}
    763 #ifdef DIAGNOSTIC
    764 		if (ksp->ks_next == NULL)
    765 			panic("malloc_type_detach: not on list");
    766 #endif
    767 	}
    768 	type->ks_next = NULL;
    769 }
    770 
    771 /*
    772  * Set the limit on a malloc type.
    773  */
    774 void
    775 malloc_type_setlimit(struct malloc_type *type, u_long limit)
    776 {
    777 #ifdef KMEMSTATS
    778 	int s;
    779 
    780 	s = splvm();
    781 	type->ks_limit = limit;
    782 	splx(s);
    783 #endif
    784 }
    785 
    786 /*
    787  * Compute the number of pages that kmem_map will map, that is,
    788  * the size of the kernel malloc arena.
    789  */
    790 void
    791 kmeminit_nkmempages(void)
    792 {
    793 	int npages;
    794 
    795 	if (nkmempages != 0) {
    796 		/*
    797 		 * It's already been set (by us being here before, or
    798 		 * by patching or kernel config options), bail out now.
    799 		 */
    800 		return;
    801 	}
    802 
    803 	/*
    804 	 * We use the following (simple) formula:
    805 	 *
    806 	 *	- Starting point is physical memory / 4.
    807 	 *
    808 	 *	- Clamp it down to NKMEMPAGES_MAX.
    809 	 *
    810 	 *	- Round it up to NKMEMPAGES_MIN.
    811 	 */
    812 	npages = physmem / 4;
    813 
    814 	if (npages > NKMEMPAGES_MAX)
    815 		npages = NKMEMPAGES_MAX;
    816 
    817 	if (npages < NKMEMPAGES_MIN)
    818 		npages = NKMEMPAGES_MIN;
    819 
    820 	nkmempages = npages;
    821 }
    822 
    823 /*
    824  * Initialize the kernel memory allocator
    825  */
    826 void
    827 kmeminit(void)
    828 {
    829 	__link_set_decl(malloc_types, struct malloc_type);
    830 	struct malloc_type * const *ksp;
    831 	vaddr_t kmb, kml;
    832 #ifdef KMEMSTATS
    833 	long indx;
    834 #endif
    835 
    836 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
    837 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
    838 #endif
    839 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
    840 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
    841 #endif
    842 #if	(MAXALLOCSAVE < NBPG)
    843 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
    844 #endif
    845 
    846 	if (sizeof(struct freelist) > (1 << MINBUCKET))
    847 		panic("minbucket too small/struct freelist too big");
    848 
    849 	/*
    850 	 * Compute the number of kmem_map pages, if we have not
    851 	 * done so already.
    852 	 */
    853 	kmeminit_nkmempages();
    854 
    855 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
    856 	    (vsize_t)(nkmempages * sizeof(struct kmemusage)));
    857 	kmb = 0;
    858 	kmem_map = uvm_km_suballoc(kernel_map, &kmb,
    859 	    &kml, (vsize_t)(nkmempages << PAGE_SHIFT),
    860 	    VM_MAP_INTRSAFE, FALSE, &kmem_map_store);
    861 	kmembase = (char *)kmb;
    862 	kmemlimit = (char *)kml;
    863 #ifdef KMEMSTATS
    864 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
    865 		if (1 << indx >= PAGE_SIZE)
    866 			bucket[indx].kb_elmpercl = 1;
    867 		else
    868 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
    869 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
    870 	}
    871 #endif
    872 
    873 	/* Attach all of the statically-linked malloc types. */
    874 	__link_set_foreach(ksp, malloc_types)
    875 		malloc_type_attach(*ksp);
    876 
    877 #ifdef MALLOC_DEBUG
    878 	debug_malloc_init();
    879 #endif
    880 }
    881 
    882 #ifdef DDB
    883 #include <ddb/db_output.h>
    884 
    885 /*
    886  * Dump kmem statistics from ddb.
    887  *
    888  * usage: call dump_kmemstats
    889  */
    890 void	dump_kmemstats(void);
    891 
    892 void
    893 dump_kmemstats(void)
    894 {
    895 #ifdef KMEMSTATS
    896 	struct malloc_type *ksp;
    897 
    898 	for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
    899 		if (ksp->ks_memuse == 0)
    900 			continue;
    901 		db_printf("%s%.*s %ld\n", ksp->ks_shortdesc,
    902 		    (int)(20 - strlen(ksp->ks_shortdesc)),
    903 		    "                    ",
    904 		    ksp->ks_memuse);
    905 	}
    906 #else
    907 	db_printf("Kmem stats are not being collected.\n");
    908 #endif /* KMEMSTATS */
    909 }
    910 #endif /* DDB */
    911 
    912 
    913 #if 0
    914 /*
    915  * Diagnostic messages about "Data modified on
    916  * freelist" indicate a memory corruption, but
    917  * they do not help tracking it down.
    918  * This function can be called at various places
    919  * to sanity check malloc's freelist and discover
    920  * where does the corruption take place.
    921  */
    922 int
    923 freelist_sanitycheck(void) {
    924 	int i,j;
    925 	struct kmembuckets *kbp;
    926 	struct freelist *freep;
    927 	int rv = 0;
    928 
    929 	for (i = MINBUCKET; i <= MINBUCKET + 15; i++) {
    930 		kbp = &bucket[i];
    931 		freep = (struct freelist *)kbp->kb_next;
    932 		j = 0;
    933 		while(freep) {
    934 			vm_map_lock(kmem_map);
    935 			rv = uvm_map_checkprot(kmem_map, (vaddr_t)freep,
    936 			    (vaddr_t)freep + sizeof(struct freelist),
    937 			    VM_PROT_WRITE);
    938 			vm_map_unlock(kmem_map);
    939 
    940 			if ((rv == 0) || (*(int *)freep != WEIRD_ADDR)) {
    941 				printf("bucket %i, chunck %d at %p modified\n",
    942 				    i, j, freep);
    943 				return 1;
    944 			}
    945 			freep = (struct freelist *)freep->next;
    946 			j++;
    947 		}
    948 	}
    949 
    950 	return 0;
    951 }
    952 #endif
    953