Home | History | Annotate | Line # | Download | only in kern
kern_malloc.c revision 1.129
      1 /*	$NetBSD: kern_malloc.c,v 1.129 2010/04/05 07:16:13 he 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.129 2010/04/05 07:16:13 he Exp $");
     70 
     71 #include <sys/param.h>
     72 #include <sys/proc.h>
     73 #include <sys/kernel.h>
     74 #include <sys/malloc.h>
     75 #include <sys/systm.h>
     76 #include <sys/debug.h>
     77 #include <sys/mutex.h>
     78 #include <sys/lockdebug.h>
     79 
     80 #include <uvm/uvm_extern.h>
     81 
     82 static struct vm_map_kernel kmem_map_store;
     83 struct vm_map *kmem_map = NULL;
     84 
     85 #include "opt_kmempages.h"
     86 
     87 #ifdef NKMEMCLUSTERS
     88 #error NKMEMCLUSTERS is obsolete; remove it from your kernel config file and use NKMEMPAGES instead or let the kernel auto-size
     89 #endif
     90 
     91 /*
     92  * Default number of pages in kmem_map.  We attempt to calculate this
     93  * at run-time, but allow it to be either patched or set in the kernel
     94  * config file.
     95  */
     96 #ifndef NKMEMPAGES
     97 #define	NKMEMPAGES	0
     98 #endif
     99 int	nkmempages = NKMEMPAGES;
    100 
    101 /*
    102  * Defaults for lower- and upper-bounds for the kmem_map page count.
    103  * Can be overridden by kernel config options.
    104  */
    105 #ifndef	NKMEMPAGES_MIN
    106 #define	NKMEMPAGES_MIN	NKMEMPAGES_MIN_DEFAULT
    107 #endif
    108 
    109 #ifndef NKMEMPAGES_MAX
    110 #define	NKMEMPAGES_MAX	NKMEMPAGES_MAX_DEFAULT
    111 #endif
    112 
    113 #include "opt_kmemstats.h"
    114 #include "opt_malloclog.h"
    115 #include "opt_malloc_debug.h"
    116 
    117 #define	MINALLOCSIZE	(1 << MINBUCKET)
    118 #define	BUCKETINDX(size) \
    119 	((size) <= (MINALLOCSIZE * 128) \
    120 		? (size) <= (MINALLOCSIZE * 8) \
    121 			? (size) <= (MINALLOCSIZE * 2) \
    122 				? (size) <= (MINALLOCSIZE * 1) \
    123 					? (MINBUCKET + 0) \
    124 					: (MINBUCKET + 1) \
    125 				: (size) <= (MINALLOCSIZE * 4) \
    126 					? (MINBUCKET + 2) \
    127 					: (MINBUCKET + 3) \
    128 			: (size) <= (MINALLOCSIZE* 32) \
    129 				? (size) <= (MINALLOCSIZE * 16) \
    130 					? (MINBUCKET + 4) \
    131 					: (MINBUCKET + 5) \
    132 				: (size) <= (MINALLOCSIZE * 64) \
    133 					? (MINBUCKET + 6) \
    134 					: (MINBUCKET + 7) \
    135 		: (size) <= (MINALLOCSIZE * 2048) \
    136 			? (size) <= (MINALLOCSIZE * 512) \
    137 				? (size) <= (MINALLOCSIZE * 256) \
    138 					? (MINBUCKET + 8) \
    139 					: (MINBUCKET + 9) \
    140 				: (size) <= (MINALLOCSIZE * 1024) \
    141 					? (MINBUCKET + 10) \
    142 					: (MINBUCKET + 11) \
    143 			: (size) <= (MINALLOCSIZE * 8192) \
    144 				? (size) <= (MINALLOCSIZE * 4096) \
    145 					? (MINBUCKET + 12) \
    146 					: (MINBUCKET + 13) \
    147 				: (size) <= (MINALLOCSIZE * 16384) \
    148 					? (MINBUCKET + 14) \
    149 					: (MINBUCKET + 15))
    150 
    151 /*
    152  * Array of descriptors that describe the contents of each page
    153  */
    154 struct kmemusage {
    155 	short ku_indx;		/* bucket index */
    156 	union {
    157 		u_short freecnt;/* for small allocations, free pieces in page */
    158 		u_short pagecnt;/* for large allocations, pages alloced */
    159 	} ku_un;
    160 };
    161 #define	ku_freecnt ku_un.freecnt
    162 #define	ku_pagecnt ku_un.pagecnt
    163 
    164 struct kmembuckets kmembuckets[MINBUCKET + 16];
    165 struct kmemusage *kmemusage;
    166 char *kmembase, *kmemlimit;
    167 
    168 #ifdef DEBUG
    169 static void *malloc_freecheck;
    170 #endif
    171 
    172 /*
    173  * Turn virtual addresses into kmem map indicies
    174  */
    175 #define	btokup(addr)	(&kmemusage[((char *)(addr) - kmembase) >> PGSHIFT])
    176 
    177 struct malloc_type *kmemstatistics;
    178 
    179 #ifdef MALLOCLOG
    180 #ifndef MALLOCLOGSIZE
    181 #define	MALLOCLOGSIZE	100000
    182 #endif
    183 
    184 struct malloclog {
    185 	void *addr;
    186 	long size;
    187 	struct malloc_type *type;
    188 	int action;
    189 	const char *file;
    190 	long line;
    191 } malloclog[MALLOCLOGSIZE];
    192 
    193 long	malloclogptr;
    194 
    195 /*
    196  * Fuzz factor for neighbour address match this must be a mask of the lower
    197  * bits we wish to ignore when comparing addresses
    198  */
    199 __uintptr_t malloclog_fuzz = 0x7FL;
    200 
    201 
    202 static void
    203 domlog(void *a, long size, struct malloc_type *type, int action,
    204     const char *file, long line)
    205 {
    206 
    207 	malloclog[malloclogptr].addr = a;
    208 	malloclog[malloclogptr].size = size;
    209 	malloclog[malloclogptr].type = type;
    210 	malloclog[malloclogptr].action = action;
    211 	malloclog[malloclogptr].file = file;
    212 	malloclog[malloclogptr].line = line;
    213 	malloclogptr++;
    214 	if (malloclogptr >= MALLOCLOGSIZE)
    215 		malloclogptr = 0;
    216 }
    217 
    218 #ifdef DIAGNOSTIC
    219 static void
    220 hitmlog(void *a)
    221 {
    222 	struct malloclog *lp;
    223 	long l;
    224 
    225 #define	PRT do { \
    226 	lp = &malloclog[l]; \
    227 	if (lp->addr == a && lp->action) { \
    228 		printf("malloc log entry %ld:\n", l); \
    229 		printf("\taddr = %p\n", lp->addr); \
    230 		printf("\tsize = %ld\n", lp->size); \
    231 		printf("\ttype = %s\n", lp->type->ks_shortdesc); \
    232 		printf("\taction = %s\n", lp->action == 1 ? "alloc" : "free"); \
    233 		printf("\tfile = %s\n", lp->file); \
    234 		printf("\tline = %ld\n", lp->line); \
    235 	} \
    236 } while (/* CONSTCOND */0)
    237 
    238 /*
    239  * Print fuzzy matched "neighbour" - look for the memory block that has
    240  * been allocated below the address we are interested in.  We look for a
    241  * base address + size that is within malloclog_fuzz of our target
    242  * address. If the base address and target address are the same then it is
    243  * likely we have found a free (size is 0 in this case) so we won't report
    244  * those, they will get reported by PRT anyway.
    245  */
    246 #define	NPRT do { \
    247 	__uintptr_t fuzz_mask = ~(malloclog_fuzz); \
    248 	lp = &malloclog[l]; \
    249 	if ((__uintptr_t)lp->addr != (__uintptr_t)a && \
    250 	    (((__uintptr_t)lp->addr + lp->size + malloclog_fuzz) & fuzz_mask) \
    251 	    == ((__uintptr_t)a & fuzz_mask) && lp->action) {		\
    252 		printf("neighbour malloc log entry %ld:\n", l); \
    253 		printf("\taddr = %p\n", lp->addr); \
    254 		printf("\tsize = %ld\n", lp->size); \
    255 		printf("\ttype = %s\n", lp->type->ks_shortdesc); \
    256 		printf("\taction = %s\n", lp->action == 1 ? "alloc" : "free"); \
    257 		printf("\tfile = %s\n", lp->file); \
    258 		printf("\tline = %ld\n", lp->line); \
    259 	} \
    260 } while (/* CONSTCOND */0)
    261 
    262 	for (l = malloclogptr; l < MALLOCLOGSIZE; l++) {
    263 		PRT;
    264 		NPRT;
    265 	}
    266 
    267 
    268 	for (l = 0; l < malloclogptr; l++) {
    269 		PRT;
    270 		NPRT;
    271 	}
    272 
    273 #undef PRT
    274 }
    275 #endif /* DIAGNOSTIC */
    276 #endif /* MALLOCLOG */
    277 
    278 #ifdef DIAGNOSTIC
    279 /*
    280  * This structure provides a set of masks to catch unaligned frees.
    281  */
    282 const long addrmask[] = { 0,
    283 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
    284 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
    285 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
    286 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
    287 };
    288 
    289 /*
    290  * The WEIRD_ADDR is used as known text to copy into free objects so
    291  * that modifications after frees can be detected.
    292  */
    293 #define	WEIRD_ADDR	((uint32_t) 0xdeadbeef)
    294 #ifdef DEBUG
    295 #define	MAX_COPY	PAGE_SIZE
    296 #else
    297 #define	MAX_COPY	32
    298 #endif
    299 
    300 /*
    301  * Normally the freelist structure is used only to hold the list pointer
    302  * for free objects.  However, when running with diagnostics, the first
    303  * 8/16 bytes of the structure is unused except for diagnostic information,
    304  * and the free list pointer is at offset 8/16 in the structure.  Since the
    305  * first 8 bytes is the portion of the structure most often modified, this
    306  * helps to detect memory reuse problems and avoid free list corruption.
    307  */
    308 struct freelist {
    309 	uint32_t spare0;
    310 #ifdef _LP64
    311 	uint32_t spare1;		/* explicit padding */
    312 #endif
    313 	struct malloc_type *type;
    314 	void *	next;
    315 };
    316 #else /* !DIAGNOSTIC */
    317 struct freelist {
    318 	void *	next;
    319 };
    320 #endif /* DIAGNOSTIC */
    321 
    322 kmutex_t malloc_lock;
    323 
    324 /*
    325  * Allocate a block of memory
    326  */
    327 #ifdef MALLOCLOG
    328 void *
    329 _kern_malloc(unsigned long size, struct malloc_type *ksp, int flags,
    330     const char *file, long line)
    331 #else
    332 void *
    333 kern_malloc(unsigned long size, struct malloc_type *ksp, int flags)
    334 #endif /* MALLOCLOG */
    335 {
    336 	struct kmembuckets *kbp;
    337 	struct kmemusage *kup;
    338 	struct freelist *freep;
    339 	long indx, npg, allocsize;
    340 	char *va, *cp, *savedlist;
    341 #ifdef DIAGNOSTIC
    342 	uint32_t *end, *lp;
    343 	int copysize;
    344 #endif
    345 
    346 #ifdef LOCKDEBUG
    347 	if ((flags & M_NOWAIT) == 0) {
    348 		ASSERT_SLEEPABLE();
    349 	}
    350 #endif
    351 #ifdef MALLOC_DEBUG
    352 	if (debug_malloc(size, ksp, flags, (void *) &va)) {
    353 		if (va != 0) {
    354 			FREECHECK_OUT(&malloc_freecheck, (void *)va);
    355 		}
    356 		return ((void *) va);
    357 	}
    358 #endif
    359 	indx = BUCKETINDX(size);
    360 	kbp = &kmembuckets[indx];
    361 	mutex_spin_enter(&malloc_lock);
    362 #ifdef KMEMSTATS
    363 	while (ksp->ks_memuse >= ksp->ks_limit) {
    364 		if (flags & M_NOWAIT) {
    365 			mutex_spin_exit(&malloc_lock);
    366 			return ((void *) NULL);
    367 		}
    368 		if (ksp->ks_limblocks < 65535)
    369 			ksp->ks_limblocks++;
    370 		mtsleep((void *)ksp, PSWP+2, ksp->ks_shortdesc, 0,
    371 			&malloc_lock);
    372 	}
    373 	ksp->ks_size |= 1 << indx;
    374 	ksp->ks_active[indx]++;
    375 #endif
    376 #ifdef DIAGNOSTIC
    377 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
    378 #endif
    379 	if (kbp->kb_next == NULL) {
    380 		int s;
    381 		kbp->kb_last = NULL;
    382 		if (size > MAXALLOCSAVE)
    383 			allocsize = round_page(size);
    384 		else
    385 			allocsize = 1 << indx;
    386 		npg = btoc(allocsize);
    387 		mutex_spin_exit(&malloc_lock);
    388 		s = splvm();
    389 		va = (void *) uvm_km_alloc(kmem_map,
    390 		    (vsize_t)ctob(npg), 0,
    391 		    ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) |
    392 		    ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 0) |
    393 		    UVM_KMF_WIRED);
    394 		splx(s);
    395 		if (__predict_false(va == NULL)) {
    396 			/*
    397 			 * Kmem_malloc() can return NULL, even if it can
    398 			 * wait, if there is no map space available, because
    399 			 * it can't fix that problem.  Neither can we,
    400 			 * right now.  (We should release pages which
    401 			 * are completely free and which are in kmembuckets
    402 			 * with too many free elements.)
    403 			 */
    404 			if ((flags & (M_NOWAIT|M_CANFAIL)) == 0)
    405 				panic("malloc: out of space in kmem_map");
    406 			return (NULL);
    407 		}
    408 		mutex_spin_enter(&malloc_lock);
    409 #ifdef KMEMSTATS
    410 		kbp->kb_total += kbp->kb_elmpercl;
    411 #endif
    412 		kup = btokup(va);
    413 		kup->ku_indx = indx;
    414 		if (allocsize > MAXALLOCSAVE) {
    415 			if (npg > 65535)
    416 				panic("malloc: allocation too large");
    417 			kup->ku_pagecnt = npg;
    418 #ifdef KMEMSTATS
    419 			ksp->ks_memuse += allocsize;
    420 #endif
    421 			goto out;
    422 		}
    423 #ifdef KMEMSTATS
    424 		kup->ku_freecnt = kbp->kb_elmpercl;
    425 		kbp->kb_totalfree += kbp->kb_elmpercl;
    426 #endif
    427 		/*
    428 		 * Just in case we blocked while allocating memory,
    429 		 * and someone else also allocated memory for this
    430 		 * kmembucket, don't assume the list is still empty.
    431 		 */
    432 		savedlist = kbp->kb_next;
    433 		kbp->kb_next = cp = va + (npg << PAGE_SHIFT) - allocsize;
    434 		for (;;) {
    435 			freep = (struct freelist *)cp;
    436 #ifdef DIAGNOSTIC
    437 			/*
    438 			 * Copy in known text to detect modification
    439 			 * after freeing.
    440 			 */
    441 			end = (uint32_t *)&cp[copysize];
    442 			for (lp = (uint32_t *)cp; lp < end; lp++)
    443 				*lp = WEIRD_ADDR;
    444 			freep->type = M_FREE;
    445 #endif /* DIAGNOSTIC */
    446 			if (cp <= va)
    447 				break;
    448 			cp -= allocsize;
    449 			freep->next = cp;
    450 		}
    451 		freep->next = savedlist;
    452 		if (savedlist == NULL)
    453 			kbp->kb_last = (void *)freep;
    454 	}
    455 	va = kbp->kb_next;
    456 	kbp->kb_next = ((struct freelist *)va)->next;
    457 #ifdef DIAGNOSTIC
    458 	freep = (struct freelist *)va;
    459 	/* XXX potential to get garbage pointer here. */
    460 	if (kbp->kb_next) {
    461 		int rv;
    462 		vaddr_t addr = (vaddr_t)kbp->kb_next;
    463 
    464 		vm_map_lock(kmem_map);
    465 		rv = uvm_map_checkprot(kmem_map, addr,
    466 		    addr + sizeof(struct freelist), VM_PROT_WRITE);
    467 		vm_map_unlock(kmem_map);
    468 
    469 		if (__predict_false(rv == 0)) {
    470 			printf("Data modified on freelist: "
    471 			    "word %ld of object %p size %ld previous type %s "
    472 			    "(invalid addr %p)\n",
    473 			    (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
    474 			    va, size, "foo", kbp->kb_next);
    475 #ifdef MALLOCLOG
    476 			hitmlog(va);
    477 #endif
    478 			kbp->kb_next = NULL;
    479 		}
    480 	}
    481 
    482 	/* Fill the fields that we've used with WEIRD_ADDR */
    483 #ifdef _LP64
    484 	freep->type = (struct malloc_type *)
    485 	    (WEIRD_ADDR | (((u_long) WEIRD_ADDR) << 32));
    486 #else
    487 	freep->type = (struct malloc_type *) WEIRD_ADDR;
    488 #endif
    489 	end = (uint32_t *)&freep->next +
    490 	    (sizeof(freep->next) / sizeof(int32_t));
    491 	for (lp = (uint32_t *)&freep->next; lp < end; lp++)
    492 		*lp = WEIRD_ADDR;
    493 
    494 	/* and check that the data hasn't been modified. */
    495 	end = (uint32_t *)&va[copysize];
    496 	for (lp = (uint32_t *)va; lp < end; lp++) {
    497 		if (__predict_true(*lp == WEIRD_ADDR))
    498 			continue;
    499 		printf("Data modified on freelist: "
    500 		    "word %ld of object %p size %ld previous type %s "
    501 		    "(0x%x != 0x%x)\n",
    502 		    (long)(lp - (uint32_t *)va), va, size,
    503 		    "bar", *lp, WEIRD_ADDR);
    504 #ifdef MALLOCLOG
    505 		hitmlog(va);
    506 #endif
    507 		break;
    508 	}
    509 
    510 	freep->spare0 = 0;
    511 #endif /* DIAGNOSTIC */
    512 #ifdef KMEMSTATS
    513 	kup = btokup(va);
    514 	if (kup->ku_indx != indx)
    515 		panic("malloc: wrong bucket");
    516 	if (kup->ku_freecnt == 0)
    517 		panic("malloc: lost data");
    518 	kup->ku_freecnt--;
    519 	kbp->kb_totalfree--;
    520 	ksp->ks_memuse += 1 << indx;
    521 out:
    522 	kbp->kb_calls++;
    523 	ksp->ks_inuse++;
    524 	ksp->ks_calls++;
    525 	if (ksp->ks_memuse > ksp->ks_maxused)
    526 		ksp->ks_maxused = ksp->ks_memuse;
    527 #else
    528 out:
    529 #endif
    530 #ifdef MALLOCLOG
    531 	domlog(va, size, ksp, 1, file, line);
    532 #endif
    533 	mutex_spin_exit(&malloc_lock);
    534 	if ((flags & M_ZERO) != 0)
    535 		memset(va, 0, size);
    536 	FREECHECK_OUT(&malloc_freecheck, (void *)va);
    537 	return ((void *) va);
    538 }
    539 
    540 /*
    541  * Free a block of memory allocated by malloc.
    542  */
    543 #ifdef MALLOCLOG
    544 void
    545 _kern_free(void *addr, struct malloc_type *ksp, const char *file, long line)
    546 #else
    547 void
    548 kern_free(void *addr, struct malloc_type *ksp)
    549 #endif /* MALLOCLOG */
    550 {
    551 	struct kmembuckets *kbp;
    552 	struct kmemusage *kup;
    553 	struct freelist *freep;
    554 	long size;
    555 #ifdef DIAGNOSTIC
    556 	void *cp;
    557 	int32_t *end, *lp;
    558 	long alloc, copysize;
    559 #endif
    560 
    561 	FREECHECK_IN(&malloc_freecheck, addr);
    562 #ifdef MALLOC_DEBUG
    563 	if (debug_free(addr, ksp))
    564 		return;
    565 #endif
    566 
    567 #ifdef DIAGNOSTIC
    568 	/*
    569 	 * Ensure that we're free'ing something that we could
    570 	 * have allocated in the first place.  That is, check
    571 	 * to see that the address is within kmem_map.
    572 	 */
    573 	if (__predict_false((vaddr_t)addr < vm_map_min(kmem_map) ||
    574 	    (vaddr_t)addr >= vm_map_max(kmem_map)))
    575 		panic("free: addr %p not within kmem_map", addr);
    576 #endif
    577 
    578 	kup = btokup(addr);
    579 	size = 1 << kup->ku_indx;
    580 	kbp = &kmembuckets[kup->ku_indx];
    581 
    582 	LOCKDEBUG_MEM_CHECK(addr,
    583 	    size <= MAXALLOCSAVE ? size : ctob(kup->ku_pagecnt));
    584 
    585 	mutex_spin_enter(&malloc_lock);
    586 #ifdef MALLOCLOG
    587 	domlog(addr, 0, ksp, 2, file, line);
    588 #endif
    589 #ifdef DIAGNOSTIC
    590 	/*
    591 	 * Check for returns of data that do not point to the
    592 	 * beginning of the allocation.
    593 	 */
    594 	if (size > PAGE_SIZE)
    595 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    596 	else
    597 		alloc = addrmask[kup->ku_indx];
    598 	if (((u_long)addr & alloc) != 0)
    599 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
    600 		    addr, size, ksp->ks_shortdesc, alloc);
    601 #endif /* DIAGNOSTIC */
    602 	if (size > MAXALLOCSAVE) {
    603 		uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt),
    604 		    UVM_KMF_WIRED);
    605 #ifdef KMEMSTATS
    606 		size = kup->ku_pagecnt << PGSHIFT;
    607 		ksp->ks_memuse -= size;
    608 		ksp->ks_active[kup->ku_indx]--;
    609 		kup->ku_indx = 0;
    610 		kup->ku_pagecnt = 0;
    611 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
    612 		    ksp->ks_memuse < ksp->ks_limit)
    613 			wakeup((void *)ksp);
    614 #ifdef DIAGNOSTIC
    615 		if (ksp->ks_inuse == 0)
    616 			panic("free 1: inuse 0, probable double free");
    617 #endif
    618 		ksp->ks_inuse--;
    619 		kbp->kb_total -= 1;
    620 #endif
    621 		mutex_spin_exit(&malloc_lock);
    622 		return;
    623 	}
    624 	freep = (struct freelist *)addr;
    625 #ifdef DIAGNOSTIC
    626 	/*
    627 	 * Check for multiple frees. Use a quick check to see if
    628 	 * it looks free before laboriously searching the freelist.
    629 	 */
    630 	if (__predict_false(freep->spare0 == WEIRD_ADDR)) {
    631 		for (cp = kbp->kb_next; cp;
    632 		    cp = ((struct freelist *)cp)->next) {
    633 			if (addr != cp)
    634 				continue;
    635 			printf("multiply freed item %p\n", addr);
    636 #ifdef MALLOCLOG
    637 			hitmlog(addr);
    638 #endif
    639 			panic("free: duplicated free");
    640 		}
    641 	}
    642 
    643 	/*
    644 	 * Copy in known text to detect modification after freeing
    645 	 * and to make it look free. Also, save the type being freed
    646 	 * so we can list likely culprit if modification is detected
    647 	 * when the object is reallocated.
    648 	 */
    649 	copysize = size < MAX_COPY ? size : MAX_COPY;
    650 	end = (int32_t *)&((char *)addr)[copysize];
    651 	for (lp = (int32_t *)addr; lp < end; lp++)
    652 		*lp = WEIRD_ADDR;
    653 	freep->type = ksp;
    654 #endif /* DIAGNOSTIC */
    655 #ifdef KMEMSTATS
    656 	kup->ku_freecnt++;
    657 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
    658 		if (kup->ku_freecnt > kbp->kb_elmpercl)
    659 			panic("free: multiple frees");
    660 		else if (kbp->kb_totalfree > kbp->kb_highwat)
    661 			kbp->kb_couldfree++;
    662 	}
    663 	kbp->kb_totalfree++;
    664 	ksp->ks_memuse -= size;
    665 	ksp->ks_active[kup->ku_indx]--;
    666 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
    667 	    ksp->ks_memuse < ksp->ks_limit)
    668 		wakeup((void *)ksp);
    669 #ifdef DIAGNOSTIC
    670 	if (ksp->ks_inuse == 0)
    671 		panic("free 2: inuse 0, probable double free");
    672 #endif
    673 	ksp->ks_inuse--;
    674 #endif
    675 	if (kbp->kb_next == NULL)
    676 		kbp->kb_next = addr;
    677 	else
    678 		((struct freelist *)kbp->kb_last)->next = addr;
    679 	freep->next = NULL;
    680 	kbp->kb_last = addr;
    681 	mutex_spin_exit(&malloc_lock);
    682 }
    683 
    684 /*
    685  * Change the size of a block of memory.
    686  */
    687 void *
    688 kern_realloc(void *curaddr, unsigned long newsize, struct malloc_type *ksp,
    689     int flags)
    690 {
    691 	struct kmemusage *kup;
    692 	unsigned long cursize;
    693 	void *newaddr;
    694 #ifdef DIAGNOSTIC
    695 	long alloc;
    696 #endif
    697 
    698 	/*
    699 	 * realloc() with a NULL pointer is the same as malloc().
    700 	 */
    701 	if (curaddr == NULL)
    702 		return (malloc(newsize, ksp, flags));
    703 
    704 	/*
    705 	 * realloc() with zero size is the same as free().
    706 	 */
    707 	if (newsize == 0) {
    708 		free(curaddr, ksp);
    709 		return (NULL);
    710 	}
    711 
    712 #ifdef LOCKDEBUG
    713 	if ((flags & M_NOWAIT) == 0) {
    714 		ASSERT_SLEEPABLE();
    715 	}
    716 #endif
    717 
    718 	/*
    719 	 * Find out how large the old allocation was (and do some
    720 	 * sanity checking).
    721 	 */
    722 	kup = btokup(curaddr);
    723 	cursize = 1 << kup->ku_indx;
    724 
    725 #ifdef DIAGNOSTIC
    726 	/*
    727 	 * Check for returns of data that do not point to the
    728 	 * beginning of the allocation.
    729 	 */
    730 	if (cursize > PAGE_SIZE)
    731 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    732 	else
    733 		alloc = addrmask[kup->ku_indx];
    734 	if (((u_long)curaddr & alloc) != 0)
    735 		panic("realloc: "
    736 		    "unaligned addr %p, size %ld, type %s, mask %ld\n",
    737 		    curaddr, cursize, ksp->ks_shortdesc, alloc);
    738 #endif /* DIAGNOSTIC */
    739 
    740 	if (cursize > MAXALLOCSAVE)
    741 		cursize = ctob(kup->ku_pagecnt);
    742 
    743 	/*
    744 	 * If we already actually have as much as they want, we're done.
    745 	 */
    746 	if (newsize <= cursize)
    747 		return (curaddr);
    748 
    749 	/*
    750 	 * Can't satisfy the allocation with the existing block.
    751 	 * Allocate a new one and copy the data.
    752 	 */
    753 	newaddr = malloc(newsize, ksp, flags);
    754 	if (__predict_false(newaddr == NULL)) {
    755 		/*
    756 		 * malloc() failed, because flags included M_NOWAIT.
    757 		 * Return NULL to indicate that failure.  The old
    758 		 * pointer is still valid.
    759 		 */
    760 		return (NULL);
    761 	}
    762 	memcpy(newaddr, curaddr, cursize);
    763 
    764 	/*
    765 	 * We were successful: free the old allocation and return
    766 	 * the new one.
    767 	 */
    768 	free(curaddr, ksp);
    769 	return (newaddr);
    770 }
    771 
    772 /*
    773  * Roundup size to the actual allocation size.
    774  */
    775 unsigned long
    776 malloc_roundup(unsigned long size)
    777 {
    778 
    779 	if (size > MAXALLOCSAVE)
    780 		return (roundup(size, PAGE_SIZE));
    781 	else
    782 		return (1 << BUCKETINDX(size));
    783 }
    784 
    785 /*
    786  * Add a malloc type to the system.
    787  */
    788 void
    789 malloc_type_attach(struct malloc_type *type)
    790 {
    791 
    792 	if (nkmempages == 0)
    793 		panic("malloc_type_attach: nkmempages == 0");
    794 
    795 	if (type->ks_magic != M_MAGIC)
    796 		panic("malloc_type_attach: bad magic");
    797 
    798 #ifdef DIAGNOSTIC
    799 	{
    800 		struct malloc_type *ksp;
    801 		for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
    802 			if (ksp == type)
    803 				panic("malloc_type_attach: already on list");
    804 		}
    805 	}
    806 #endif
    807 
    808 #ifdef KMEMSTATS
    809 	if (type->ks_limit == 0)
    810 		type->ks_limit = ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
    811 #else
    812 	type->ks_limit = 0;
    813 #endif
    814 
    815 	type->ks_next = kmemstatistics;
    816 	kmemstatistics = type;
    817 }
    818 
    819 /*
    820  * Remove a malloc type from the system..
    821  */
    822 void
    823 malloc_type_detach(struct malloc_type *type)
    824 {
    825 	struct malloc_type *ksp;
    826 
    827 #ifdef DIAGNOSTIC
    828 	if (type->ks_magic != M_MAGIC)
    829 		panic("malloc_type_detach: bad magic");
    830 #endif
    831 
    832 	if (type == kmemstatistics)
    833 		kmemstatistics = type->ks_next;
    834 	else {
    835 		for (ksp = kmemstatistics; ksp->ks_next != NULL;
    836 		     ksp = ksp->ks_next) {
    837 			if (ksp->ks_next == type) {
    838 				ksp->ks_next = type->ks_next;
    839 				break;
    840 			}
    841 		}
    842 #ifdef DIAGNOSTIC
    843 		if (ksp->ks_next == NULL)
    844 			panic("malloc_type_detach: not on list");
    845 #endif
    846 	}
    847 	type->ks_next = NULL;
    848 }
    849 
    850 /*
    851  * Set the limit on a malloc type.
    852  */
    853 void
    854 malloc_type_setlimit(struct malloc_type *type, u_long limit)
    855 {
    856 #ifdef KMEMSTATS
    857 	mutex_spin_enter(&malloc_lock);
    858 	type->ks_limit = limit;
    859 	mutex_spin_exit(&malloc_lock);
    860 #endif
    861 }
    862 
    863 /*
    864  * Compute the number of pages that kmem_map will map, that is,
    865  * the size of the kernel malloc arena.
    866  */
    867 void
    868 kmeminit_nkmempages(void)
    869 {
    870 	int npages;
    871 
    872 	if (nkmempages != 0) {
    873 		/*
    874 		 * It's already been set (by us being here before, or
    875 		 * by patching or kernel config options), bail out now.
    876 		 */
    877 		return;
    878 	}
    879 
    880 	npages = physmem;
    881 
    882 	if (npages > NKMEMPAGES_MAX)
    883 		npages = NKMEMPAGES_MAX;
    884 
    885 	if (npages < NKMEMPAGES_MIN)
    886 		npages = NKMEMPAGES_MIN;
    887 
    888 	nkmempages = npages;
    889 }
    890 
    891 /*
    892  * Initialize the kernel memory allocator
    893  */
    894 void
    895 kmeminit(void)
    896 {
    897 	__link_set_decl(malloc_types, struct malloc_type);
    898 	struct malloc_type * const *ksp;
    899 	vaddr_t kmb, kml;
    900 #ifdef KMEMSTATS
    901 	long indx;
    902 #endif
    903 
    904 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
    905 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
    906 #endif
    907 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
    908 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
    909 #endif
    910 #if	(MAXALLOCSAVE < NBPG)
    911 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
    912 #endif
    913 
    914 	if (sizeof(struct freelist) > (1 << MINBUCKET))
    915 		panic("minbucket too small/struct freelist too big");
    916 
    917 	mutex_init(&malloc_lock, MUTEX_DEFAULT, IPL_VM);
    918 
    919 	/*
    920 	 * Compute the number of kmem_map pages, if we have not
    921 	 * done so already.
    922 	 */
    923 	kmeminit_nkmempages();
    924 
    925 	kmemusage = (struct kmemusage *) uvm_km_alloc(kernel_map,
    926 	    (vsize_t)(nkmempages * sizeof(struct kmemusage)), 0,
    927 	    UVM_KMF_WIRED|UVM_KMF_ZERO);
    928 	kmb = 0;
    929 	kmem_map = uvm_km_suballoc(kernel_map, &kmb,
    930 	    &kml, ((vsize_t)nkmempages << PAGE_SHIFT),
    931 	    VM_MAP_INTRSAFE, false, &kmem_map_store);
    932 	uvm_km_vacache_init(kmem_map, "kvakmem", 0);
    933 	kmembase = (char *)kmb;
    934 	kmemlimit = (char *)kml;
    935 #ifdef KMEMSTATS
    936 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
    937 		if (1 << indx >= PAGE_SIZE)
    938 			kmembuckets[indx].kb_elmpercl = 1;
    939 		else
    940 			kmembuckets[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
    941 		kmembuckets[indx].kb_highwat =
    942 			5 * kmembuckets[indx].kb_elmpercl;
    943 	}
    944 #endif
    945 
    946 	/* Attach all of the statically-linked malloc types. */
    947 	__link_set_foreach(ksp, malloc_types)
    948 		malloc_type_attach(*ksp);
    949 
    950 #ifdef MALLOC_DEBUG
    951 	debug_malloc_init();
    952 #endif
    953 }
    954 
    955 #ifdef DDB
    956 #include <ddb/db_output.h>
    957 
    958 /*
    959  * Dump kmem statistics from ddb.
    960  *
    961  * usage: call dump_kmemstats
    962  */
    963 void	dump_kmemstats(void);
    964 
    965 void
    966 dump_kmemstats(void)
    967 {
    968 #ifdef KMEMSTATS
    969 	struct malloc_type *ksp;
    970 
    971 	for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
    972 		if (ksp->ks_memuse == 0)
    973 			continue;
    974 		db_printf("%s%.*s %ld\n", ksp->ks_shortdesc,
    975 		    (int)(20 - strlen(ksp->ks_shortdesc)),
    976 		    "                    ",
    977 		    ksp->ks_memuse);
    978 	}
    979 #else
    980 	db_printf("Kmem stats are not being collected.\n");
    981 #endif /* KMEMSTATS */
    982 }
    983 #endif /* DDB */
    984 
    985 
    986 #if 0
    987 /*
    988  * Diagnostic messages about "Data modified on
    989  * freelist" indicate a memory corruption, but
    990  * they do not help tracking it down.
    991  * This function can be called at various places
    992  * to sanity check malloc's freelist and discover
    993  * where does the corruption take place.
    994  */
    995 int
    996 freelist_sanitycheck(void) {
    997 	int i,j;
    998 	struct kmembuckets *kbp;
    999 	struct freelist *freep;
   1000 	int rv = 0;
   1001 
   1002 	for (i = MINBUCKET; i <= MINBUCKET + 15; i++) {
   1003 		kbp = &kmembuckets[i];
   1004 		freep = (struct freelist *)kbp->kb_next;
   1005 		j = 0;
   1006 		while(freep) {
   1007 			vm_map_lock(kmem_map);
   1008 			rv = uvm_map_checkprot(kmem_map, (vaddr_t)freep,
   1009 			    (vaddr_t)freep + sizeof(struct freelist),
   1010 			    VM_PROT_WRITE);
   1011 			vm_map_unlock(kmem_map);
   1012 
   1013 			if ((rv == 0) || (*(int *)freep != WEIRD_ADDR)) {
   1014 				printf("bucket %i, chunck %d at %p modified\n",
   1015 				    i, j, freep);
   1016 				return 1;
   1017 			}
   1018 			freep = (struct freelist *)freep->next;
   1019 			j++;
   1020 		}
   1021 	}
   1022 
   1023 	return 0;
   1024 }
   1025 #endif
   1026