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