Home | History | Annotate | Line # | Download | only in kern
kern_malloc.c revision 1.108.2.2
      1 /*	$NetBSD: kern_malloc.c,v 1.108.2.2 2007/03/21 20:10:21 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.2 2007/03/21 20:10:21 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 
     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 
    615 	/*
    616 	 * Copy in known text to detect modification after freeing
    617 	 * and to make it look free. Also, save the type being freed
    618 	 * so we can list likely culprit if modification is detected
    619 	 * when the object is reallocated.
    620 	 */
    621 	copysize = size < MAX_COPY ? size : MAX_COPY;
    622 	end = (int32_t *)&((char *)addr)[copysize];
    623 	for (lp = (int32_t *)addr; lp < end; lp++)
    624 		*lp = WEIRD_ADDR;
    625 	freep->type = ksp;
    626 #endif /* DIAGNOSTIC */
    627 #ifdef KMEMSTATS
    628 	kup->ku_freecnt++;
    629 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
    630 		if (kup->ku_freecnt > kbp->kb_elmpercl)
    631 			panic("free: multiple frees");
    632 		else if (kbp->kb_totalfree > kbp->kb_highwat)
    633 			kbp->kb_couldfree++;
    634 	}
    635 	kbp->kb_totalfree++;
    636 	ksp->ks_memuse -= size;
    637 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
    638 	    ksp->ks_memuse < ksp->ks_limit)
    639 		wakeup((void *)ksp);
    640 #ifdef DIAGNOSTIC
    641 	if (ksp->ks_inuse == 0)
    642 		panic("free 2: inuse 0, probable double free");
    643 #endif
    644 	ksp->ks_inuse--;
    645 #endif
    646 	if (kbp->kb_next == NULL)
    647 		kbp->kb_next = addr;
    648 	else
    649 		((struct freelist *)kbp->kb_last)->next = addr;
    650 	freep->next = NULL;
    651 	kbp->kb_last = addr;
    652 	mutex_exit(&malloc_lock);
    653 }
    654 
    655 /*
    656  * Change the size of a block of memory.
    657  */
    658 void *
    659 realloc(void *curaddr, unsigned long newsize, struct malloc_type *ksp,
    660     int flags)
    661 {
    662 	struct kmemusage *kup;
    663 	unsigned long cursize;
    664 	void *newaddr;
    665 #ifdef DIAGNOSTIC
    666 	long alloc;
    667 #endif
    668 
    669 	/*
    670 	 * realloc() with a NULL pointer is the same as malloc().
    671 	 */
    672 	if (curaddr == NULL)
    673 		return (malloc(newsize, ksp, flags));
    674 
    675 	/*
    676 	 * realloc() with zero size is the same as free().
    677 	 */
    678 	if (newsize == 0) {
    679 		free(curaddr, ksp);
    680 		return (NULL);
    681 	}
    682 
    683 #ifdef LOCKDEBUG
    684 	if ((flags & M_NOWAIT) == 0)
    685 		ASSERT_SLEEPABLE(NULL, "realloc");
    686 #endif
    687 
    688 	/*
    689 	 * Find out how large the old allocation was (and do some
    690 	 * sanity checking).
    691 	 */
    692 	kup = btokup(curaddr);
    693 	cursize = 1 << kup->ku_indx;
    694 
    695 #ifdef DIAGNOSTIC
    696 	/*
    697 	 * Check for returns of data that do not point to the
    698 	 * beginning of the allocation.
    699 	 */
    700 	if (cursize > PAGE_SIZE)
    701 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    702 	else
    703 		alloc = addrmask[kup->ku_indx];
    704 	if (((u_long)curaddr & alloc) != 0)
    705 		panic("realloc: "
    706 		    "unaligned addr %p, size %ld, type %s, mask %ld\n",
    707 		    curaddr, cursize, ksp->ks_shortdesc, alloc);
    708 #endif /* DIAGNOSTIC */
    709 
    710 	if (cursize > MAXALLOCSAVE)
    711 		cursize = ctob(kup->ku_pagecnt);
    712 
    713 	/*
    714 	 * If we already actually have as much as they want, we're done.
    715 	 */
    716 	if (newsize <= cursize)
    717 		return (curaddr);
    718 
    719 	/*
    720 	 * Can't satisfy the allocation with the existing block.
    721 	 * Allocate a new one and copy the data.
    722 	 */
    723 	newaddr = malloc(newsize, ksp, flags);
    724 	if (__predict_false(newaddr == NULL)) {
    725 		/*
    726 		 * malloc() failed, because flags included M_NOWAIT.
    727 		 * Return NULL to indicate that failure.  The old
    728 		 * pointer is still valid.
    729 		 */
    730 		return (NULL);
    731 	}
    732 	memcpy(newaddr, curaddr, cursize);
    733 
    734 	/*
    735 	 * We were successful: free the old allocation and return
    736 	 * the new one.
    737 	 */
    738 	free(curaddr, ksp);
    739 	return (newaddr);
    740 }
    741 
    742 /*
    743  * Roundup size to the actual allocation size.
    744  */
    745 unsigned long
    746 malloc_roundup(unsigned long size)
    747 {
    748 
    749 	if (size > MAXALLOCSAVE)
    750 		return (roundup(size, PAGE_SIZE));
    751 	else
    752 		return (1 << BUCKETINDX(size));
    753 }
    754 
    755 /*
    756  * Add a malloc type to the system.
    757  */
    758 void
    759 malloc_type_attach(struct malloc_type *type)
    760 {
    761 
    762 	if (nkmempages == 0)
    763 		panic("malloc_type_attach: nkmempages == 0");
    764 
    765 	if (type->ks_magic != M_MAGIC)
    766 		panic("malloc_type_attach: bad magic");
    767 
    768 #ifdef DIAGNOSTIC
    769 	{
    770 		struct malloc_type *ksp;
    771 		for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
    772 			if (ksp == type)
    773 				panic("malloc_type_attach: already on list");
    774 		}
    775 	}
    776 #endif
    777 
    778 #ifdef KMEMSTATS
    779 	if (type->ks_limit == 0)
    780 		type->ks_limit = ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
    781 #else
    782 	type->ks_limit = 0;
    783 #endif
    784 
    785 	type->ks_next = kmemstatistics;
    786 	kmemstatistics = type;
    787 }
    788 
    789 /*
    790  * Remove a malloc type from the system..
    791  */
    792 void
    793 malloc_type_detach(struct malloc_type *type)
    794 {
    795 	struct malloc_type *ksp;
    796 
    797 #ifdef DIAGNOSTIC
    798 	if (type->ks_magic != M_MAGIC)
    799 		panic("malloc_type_detach: bad magic");
    800 #endif
    801 
    802 	if (type == kmemstatistics)
    803 		kmemstatistics = type->ks_next;
    804 	else {
    805 		for (ksp = kmemstatistics; ksp->ks_next != NULL;
    806 		     ksp = ksp->ks_next) {
    807 			if (ksp->ks_next == type) {
    808 				ksp->ks_next = type->ks_next;
    809 				break;
    810 			}
    811 		}
    812 #ifdef DIAGNOSTIC
    813 		if (ksp->ks_next == NULL)
    814 			panic("malloc_type_detach: not on list");
    815 #endif
    816 	}
    817 	type->ks_next = NULL;
    818 }
    819 
    820 /*
    821  * Set the limit on a malloc type.
    822  */
    823 void
    824 malloc_type_setlimit(struct malloc_type *type, u_long limit)
    825 {
    826 #ifdef KMEMSTATS
    827 	mutex_enter(&malloc_lock);
    828 	type->ks_limit = limit;
    829 	mutex_exit(&malloc_lock);
    830 #endif
    831 }
    832 
    833 /*
    834  * Compute the number of pages that kmem_map will map, that is,
    835  * the size of the kernel malloc arena.
    836  */
    837 void
    838 kmeminit_nkmempages(void)
    839 {
    840 	int npages;
    841 
    842 	if (nkmempages != 0) {
    843 		/*
    844 		 * It's already been set (by us being here before, or
    845 		 * by patching or kernel config options), bail out now.
    846 		 */
    847 		return;
    848 	}
    849 
    850 	npages = physmem;
    851 
    852 	if (npages > NKMEMPAGES_MAX)
    853 		npages = NKMEMPAGES_MAX;
    854 
    855 	if (npages < NKMEMPAGES_MIN)
    856 		npages = NKMEMPAGES_MIN;
    857 
    858 	nkmempages = npages;
    859 }
    860 
    861 /*
    862  * Initialize the kernel memory allocator
    863  */
    864 void
    865 kmeminit(void)
    866 {
    867 	__link_set_decl(malloc_types, struct malloc_type);
    868 	struct malloc_type * const *ksp;
    869 	vaddr_t kmb, kml;
    870 #ifdef KMEMSTATS
    871 	long indx;
    872 #endif
    873 
    874 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
    875 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
    876 #endif
    877 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
    878 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
    879 #endif
    880 #if	(MAXALLOCSAVE < NBPG)
    881 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
    882 #endif
    883 
    884 	if (sizeof(struct freelist) > (1 << MINBUCKET))
    885 		panic("minbucket too small/struct freelist too big");
    886 
    887 	mutex_init(&malloc_lock, MUTEX_DRIVER, IPL_VM);
    888 
    889 	/*
    890 	 * Compute the number of kmem_map pages, if we have not
    891 	 * done so already.
    892 	 */
    893 	kmeminit_nkmempages();
    894 
    895 	kmemusage = (struct kmemusage *) uvm_km_alloc(kernel_map,
    896 	    (vsize_t)(nkmempages * sizeof(struct kmemusage)), 0,
    897 	    UVM_KMF_WIRED|UVM_KMF_ZERO);
    898 	kmb = 0;
    899 	kmem_map = uvm_km_suballoc(kernel_map, &kmb,
    900 	    &kml, ((vsize_t)nkmempages << PAGE_SHIFT),
    901 	    VM_MAP_INTRSAFE, false, &kmem_map_store);
    902 	uvm_km_vacache_init(kmem_map, "kvakmem", 0);
    903 	kmembase = (char *)kmb;
    904 	kmemlimit = (char *)kml;
    905 #ifdef KMEMSTATS
    906 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
    907 		if (1 << indx >= PAGE_SIZE)
    908 			kmembuckets[indx].kb_elmpercl = 1;
    909 		else
    910 			kmembuckets[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
    911 		kmembuckets[indx].kb_highwat =
    912 			5 * kmembuckets[indx].kb_elmpercl;
    913 	}
    914 #endif
    915 
    916 	/* Attach all of the statically-linked malloc types. */
    917 	__link_set_foreach(ksp, malloc_types)
    918 		malloc_type_attach(*ksp);
    919 
    920 #ifdef MALLOC_DEBUG
    921 	debug_malloc_init();
    922 #endif
    923 }
    924 
    925 #ifdef DDB
    926 #include <ddb/db_output.h>
    927 
    928 /*
    929  * Dump kmem statistics from ddb.
    930  *
    931  * usage: call dump_kmemstats
    932  */
    933 void	dump_kmemstats(void);
    934 
    935 void
    936 dump_kmemstats(void)
    937 {
    938 #ifdef KMEMSTATS
    939 	struct malloc_type *ksp;
    940 
    941 	for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
    942 		if (ksp->ks_memuse == 0)
    943 			continue;
    944 		db_printf("%s%.*s %ld\n", ksp->ks_shortdesc,
    945 		    (int)(20 - strlen(ksp->ks_shortdesc)),
    946 		    "                    ",
    947 		    ksp->ks_memuse);
    948 	}
    949 #else
    950 	db_printf("Kmem stats are not being collected.\n");
    951 #endif /* KMEMSTATS */
    952 }
    953 #endif /* DDB */
    954 
    955 
    956 #if 0
    957 /*
    958  * Diagnostic messages about "Data modified on
    959  * freelist" indicate a memory corruption, but
    960  * they do not help tracking it down.
    961  * This function can be called at various places
    962  * to sanity check malloc's freelist and discover
    963  * where does the corruption take place.
    964  */
    965 int
    966 freelist_sanitycheck(void) {
    967 	int i,j;
    968 	struct kmembuckets *kbp;
    969 	struct freelist *freep;
    970 	int rv = 0;
    971 
    972 	for (i = MINBUCKET; i <= MINBUCKET + 15; i++) {
    973 		kbp = &kmembuckets[i];
    974 		freep = (struct freelist *)kbp->kb_next;
    975 		j = 0;
    976 		while(freep) {
    977 			vm_map_lock(kmem_map);
    978 			rv = uvm_map_checkprot(kmem_map, (vaddr_t)freep,
    979 			    (vaddr_t)freep + sizeof(struct freelist),
    980 			    VM_PROT_WRITE);
    981 			vm_map_unlock(kmem_map);
    982 
    983 			if ((rv == 0) || (*(int *)freep != WEIRD_ADDR)) {
    984 				printf("bucket %i, chunck %d at %p modified\n",
    985 				    i, j, freep);
    986 				return 1;
    987 			}
    988 			freep = (struct freelist *)freep->next;
    989 			j++;
    990 		}
    991 	}
    992 
    993 	return 0;
    994 }
    995 #endif
    996