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