Home | History | Annotate | Line # | Download | only in kern
kern_malloc.c revision 1.66
      1 /*	$NetBSD: kern_malloc.c,v 1.66 2001/11/21 01:30:04 enami Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1996 Christopher G. Demetriou.  All rights reserved.
      5  * Copyright (c) 1987, 1991, 1993
      6  *	The Regents of the University of California.  All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. All advertising materials mentioning features or use of this software
     17  *    must display the following acknowledgement:
     18  *	This product includes software developed by the University of
     19  *	California, Berkeley and its contributors.
     20  * 4. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)kern_malloc.c	8.4 (Berkeley) 5/20/95
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: kern_malloc.c,v 1.66 2001/11/21 01:30:04 enami Exp $");
     41 
     42 #include "opt_lockdebug.h"
     43 
     44 #include <sys/param.h>
     45 #include <sys/proc.h>
     46 #include <sys/map.h>
     47 #include <sys/kernel.h>
     48 #include <sys/malloc.h>
     49 #include <sys/systm.h>
     50 
     51 #include <uvm/uvm_extern.h>
     52 
     53 static struct vm_map kmem_map_store;
     54 struct vm_map *kmem_map = NULL;
     55 
     56 #include "opt_kmempages.h"
     57 
     58 #ifdef NKMEMCLUSTERS
     59 #error NKMEMCLUSTERS is obsolete; remove it from your kernel config file and use NKMEMPAGES instead or let the kernel auto-size
     60 #endif
     61 
     62 /*
     63  * Default number of pages in kmem_map.  We attempt to calculate this
     64  * at run-time, but allow it to be either patched or set in the kernel
     65  * config file.
     66  */
     67 #ifndef NKMEMPAGES
     68 #define	NKMEMPAGES	0
     69 #endif
     70 int	nkmempages = NKMEMPAGES;
     71 
     72 /*
     73  * Defaults for lower- and upper-bounds for the kmem_map page count.
     74  * Can be overridden by kernel config options.
     75  */
     76 #ifndef	NKMEMPAGES_MIN
     77 #define	NKMEMPAGES_MIN	NKMEMPAGES_MIN_DEFAULT
     78 #endif
     79 
     80 #ifndef NKMEMPAGES_MAX
     81 #define	NKMEMPAGES_MAX	NKMEMPAGES_MAX_DEFAULT
     82 #endif
     83 
     84 #include "opt_kmemstats.h"
     85 #include "opt_malloclog.h"
     86 
     87 struct kmembuckets bucket[MINBUCKET + 16];
     88 struct kmemstats kmemstats[M_LAST];
     89 struct kmemusage *kmemusage;
     90 char *kmembase, *kmemlimit;
     91 const char * const memname[] = INITKMEMNAMES;
     92 
     93 #ifdef MALLOCLOG
     94 #ifndef MALLOCLOGSIZE
     95 #define	MALLOCLOGSIZE	100000
     96 #endif
     97 
     98 struct malloclog {
     99 	void *addr;
    100 	long size;
    101 	int type;
    102 	int action;
    103 	const char *file;
    104 	long line;
    105 } malloclog[MALLOCLOGSIZE];
    106 
    107 long	malloclogptr;
    108 
    109 static void domlog __P((void *a, long size, int type, int action,
    110 	const char *file, long line));
    111 static void hitmlog __P((void *a));
    112 
    113 static void
    114 domlog(a, size, type, action, file, line)
    115 	void *a;
    116 	long size;
    117 	int type;
    118 	int action;
    119 	const char *file;
    120 	long line;
    121 {
    122 
    123 	malloclog[malloclogptr].addr = a;
    124 	malloclog[malloclogptr].size = size;
    125 	malloclog[malloclogptr].type = type;
    126 	malloclog[malloclogptr].action = action;
    127 	malloclog[malloclogptr].file = file;
    128 	malloclog[malloclogptr].line = line;
    129 	malloclogptr++;
    130 	if (malloclogptr >= MALLOCLOGSIZE)
    131 		malloclogptr = 0;
    132 }
    133 
    134 static void
    135 hitmlog(a)
    136 	void *a;
    137 {
    138 	struct malloclog *lp;
    139 	long l;
    140 
    141 #define	PRT \
    142 	if (malloclog[l].addr == a && malloclog[l].action) { \
    143 		lp = &malloclog[l]; \
    144 		printf("malloc log entry %ld:\n", l); \
    145 		printf("\taddr = %p\n", lp->addr); \
    146 		printf("\tsize = %ld\n", lp->size); \
    147 		printf("\ttype = %s\n", memname[lp->type]); \
    148 		printf("\taction = %s\n", lp->action == 1 ? "alloc" : "free"); \
    149 		printf("\tfile = %s\n", lp->file); \
    150 		printf("\tline = %ld\n", lp->line); \
    151 	}
    152 
    153 	for (l = malloclogptr; l < MALLOCLOGSIZE; l++)
    154 		PRT
    155 
    156 	for (l = 0; l < malloclogptr; l++)
    157 		PRT
    158 }
    159 #endif /* MALLOCLOG */
    160 
    161 #ifdef DIAGNOSTIC
    162 /*
    163  * This structure provides a set of masks to catch unaligned frees.
    164  */
    165 const long addrmask[] = { 0,
    166 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
    167 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
    168 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
    169 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
    170 };
    171 
    172 /*
    173  * The WEIRD_ADDR is used as known text to copy into free objects so
    174  * that modifications after frees can be detected.
    175  */
    176 #define WEIRD_ADDR	((unsigned) 0xdeadbeef)
    177 #ifdef DEBUG
    178 #define MAX_COPY	PAGE_SIZE
    179 #else
    180 #define MAX_COPY	32
    181 #endif
    182 
    183 /*
    184  * Normally the freelist structure is used only to hold the list pointer
    185  * for free objects.  However, when running with diagnostics, the first
    186  * 8 bytes of the structure is unused except for diagnostic information,
    187  * and the free list pointer is at offst 8 in the structure.  Since the
    188  * first 8 bytes is the portion of the structure most often modified, this
    189  * helps to detect memory reuse problems and avoid free list corruption.
    190  */
    191 struct freelist {
    192 	int32_t	spare0;
    193 	int16_t	type;
    194 	int16_t	spare1;
    195 	caddr_t	next;
    196 };
    197 #else /* !DIAGNOSTIC */
    198 struct freelist {
    199 	caddr_t	next;
    200 };
    201 #endif /* DIAGNOSTIC */
    202 
    203 /*
    204  * Allocate a block of memory
    205  */
    206 #ifdef MALLOCLOG
    207 void *
    208 _malloc(size, type, flags, file, line)
    209 	unsigned long size;
    210 	int type, flags;
    211 	const char *file;
    212 	long line;
    213 #else
    214 void *
    215 malloc(size, type, flags)
    216 	unsigned long size;
    217 	int type, flags;
    218 #endif /* MALLOCLOG */
    219 {
    220 	struct kmembuckets *kbp;
    221 	struct kmemusage *kup;
    222 	struct freelist *freep;
    223 	long indx, npg, allocsize;
    224 	int s;
    225 	caddr_t va, cp, savedlist;
    226 #ifdef DIAGNOSTIC
    227 	int32_t *end, *lp;
    228 	int copysize;
    229 	const char *savedtype;
    230 #endif
    231 #ifdef KMEMSTATS
    232 	struct kmemstats *ksp = &kmemstats[type];
    233 
    234 	if (__predict_false(((unsigned long)type) > M_LAST))
    235 		panic("malloc - bogus type");
    236 #endif
    237 #ifdef LOCKDEBUG
    238 	if ((flags & M_NOWAIT) == 0)
    239 		simple_lock_only_held(NULL, "malloc");
    240 #endif
    241 #ifdef MALLOC_DEBUG
    242 	if (debug_malloc(size, type, flags, (void **) &va))
    243 		return ((void *) va);
    244 #endif
    245 	indx = BUCKETINDX(size);
    246 	kbp = &bucket[indx];
    247 	s = splvm();
    248 #ifdef KMEMSTATS
    249 	while (ksp->ks_memuse >= ksp->ks_limit) {
    250 		if (flags & M_NOWAIT) {
    251 			splx(s);
    252 			return ((void *) NULL);
    253 		}
    254 		if (ksp->ks_limblocks < 65535)
    255 			ksp->ks_limblocks++;
    256 		tsleep((caddr_t)ksp, PSWP+2, memname[type], 0);
    257 	}
    258 	ksp->ks_size |= 1 << indx;
    259 #endif
    260 #ifdef DIAGNOSTIC
    261 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
    262 #endif
    263 	if (kbp->kb_next == NULL) {
    264 		kbp->kb_last = NULL;
    265 		if (size > MAXALLOCSAVE)
    266 			allocsize = round_page(size);
    267 		else
    268 			allocsize = 1 << indx;
    269 		npg = btoc(allocsize);
    270 		va = (caddr_t) uvm_km_kmemalloc(kmem_map, NULL,
    271 				(vsize_t)ctob(npg),
    272 				(flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0);
    273 		if (__predict_false(va == NULL)) {
    274 			/*
    275 			 * Kmem_malloc() can return NULL, even if it can
    276 			 * wait, if there is no map space avaiable, because
    277 			 * it can't fix that problem.  Neither can we,
    278 			 * right now.  (We should release pages which
    279 			 * are completely free and which are in buckets
    280 			 * with too many free elements.)
    281 			 */
    282 			if ((flags & M_NOWAIT) == 0)
    283 				panic("malloc: out of space in kmem_map");
    284 			splx(s);
    285 			return ((void *) NULL);
    286 		}
    287 #ifdef KMEMSTATS
    288 		kbp->kb_total += kbp->kb_elmpercl;
    289 #endif
    290 		kup = btokup(va);
    291 		kup->ku_indx = indx;
    292 		if (allocsize > MAXALLOCSAVE) {
    293 			if (npg > 65535)
    294 				panic("malloc: allocation too large");
    295 			kup->ku_pagecnt = npg;
    296 #ifdef KMEMSTATS
    297 			ksp->ks_memuse += allocsize;
    298 #endif
    299 			goto out;
    300 		}
    301 #ifdef KMEMSTATS
    302 		kup->ku_freecnt = kbp->kb_elmpercl;
    303 		kbp->kb_totalfree += kbp->kb_elmpercl;
    304 #endif
    305 		/*
    306 		 * Just in case we blocked while allocating memory,
    307 		 * and someone else also allocated memory for this
    308 		 * bucket, don't assume the list is still empty.
    309 		 */
    310 		savedlist = kbp->kb_next;
    311 		kbp->kb_next = cp = va + (npg << PAGE_SHIFT) - allocsize;
    312 		for (;;) {
    313 			freep = (struct freelist *)cp;
    314 #ifdef DIAGNOSTIC
    315 			/*
    316 			 * Copy in known text to detect modification
    317 			 * after freeing.
    318 			 */
    319 			end = (int32_t *)&cp[copysize];
    320 			for (lp = (int32_t *)cp; lp < end; lp++)
    321 				*lp = WEIRD_ADDR;
    322 			freep->type = M_FREE;
    323 #endif /* DIAGNOSTIC */
    324 			if (cp <= va)
    325 				break;
    326 			cp -= allocsize;
    327 			freep->next = cp;
    328 		}
    329 		freep->next = savedlist;
    330 		if (kbp->kb_last == NULL)
    331 			kbp->kb_last = (caddr_t)freep;
    332 	}
    333 	va = kbp->kb_next;
    334 	kbp->kb_next = ((struct freelist *)va)->next;
    335 #ifdef DIAGNOSTIC
    336 	freep = (struct freelist *)va;
    337 	savedtype = (unsigned)freep->type < M_LAST ?
    338 		memname[freep->type] : "???";
    339 	if (kbp->kb_next) {
    340 		int rv;
    341 		vaddr_t addr = (vaddr_t)kbp->kb_next;
    342 
    343 		vm_map_lock(kmem_map);
    344 		rv = uvm_map_checkprot(kmem_map, addr,
    345 				       addr + sizeof(struct freelist),
    346 				       VM_PROT_WRITE);
    347 		vm_map_unlock(kmem_map);
    348 
    349 		if (__predict_false(rv == 0)) {
    350 			printf(
    351 		    "%s %ld of object %p size %ld %s %s (invalid addr %p)\n",
    352 			    "Data modified on freelist: word",
    353 			    (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
    354 			    va, size, "previous type", savedtype, kbp->kb_next);
    355 #ifdef MALLOCLOG
    356 			hitmlog(va);
    357 #endif
    358 			kbp->kb_next = NULL;
    359 		}
    360 	}
    361 
    362 	/* Fill the fields that we've used with WEIRD_ADDR */
    363 #if BYTE_ORDER == BIG_ENDIAN
    364 	freep->type = WEIRD_ADDR >> 16;
    365 #endif
    366 #if BYTE_ORDER == LITTLE_ENDIAN
    367 	freep->type = (short)WEIRD_ADDR;
    368 #endif
    369 	end = (int32_t *)&freep->next +
    370 	    (sizeof(freep->next) / sizeof(int32_t));
    371 	for (lp = (int32_t *)&freep->next; lp < end; lp++)
    372 		*lp = WEIRD_ADDR;
    373 
    374 	/* and check that the data hasn't been modified. */
    375 	end = (int32_t *)&va[copysize];
    376 	for (lp = (int32_t *)va; lp < end; lp++) {
    377 		if (__predict_true(*lp == WEIRD_ADDR))
    378 			continue;
    379 		printf("%s %ld of object %p size %ld %s %s (0x%x != 0x%x)\n",
    380 		    "Data modified on freelist: word",
    381 		    (long)(lp - (int32_t *)va), va, size, "previous type",
    382 		    savedtype, *lp, WEIRD_ADDR);
    383 #ifdef MALLOCLOG
    384 		hitmlog(va);
    385 #endif
    386 		break;
    387 	}
    388 
    389 	freep->spare0 = 0;
    390 #endif /* DIAGNOSTIC */
    391 #ifdef KMEMSTATS
    392 	kup = btokup(va);
    393 	if (kup->ku_indx != indx)
    394 		panic("malloc: wrong bucket");
    395 	if (kup->ku_freecnt == 0)
    396 		panic("malloc: lost data");
    397 	kup->ku_freecnt--;
    398 	kbp->kb_totalfree--;
    399 	ksp->ks_memuse += 1 << indx;
    400 out:
    401 	kbp->kb_calls++;
    402 	ksp->ks_inuse++;
    403 	ksp->ks_calls++;
    404 	if (ksp->ks_memuse > ksp->ks_maxused)
    405 		ksp->ks_maxused = ksp->ks_memuse;
    406 #else
    407 out:
    408 #endif
    409 #ifdef MALLOCLOG
    410 	domlog(va, size, type, 1, file, line);
    411 #endif
    412 	splx(s);
    413 	if (va != NULL && (flags & M_ZERO))
    414 		memset(va, 0, size);
    415 	return ((void *) va);
    416 }
    417 
    418 /*
    419  * Free a block of memory allocated by malloc.
    420  */
    421 #ifdef MALLOCLOG
    422 void
    423 _free(addr, type, file, line)
    424 	void *addr;
    425 	int type;
    426 	const char *file;
    427 	long line;
    428 #else
    429 void
    430 free(addr, type)
    431 	void *addr;
    432 	int type;
    433 #endif /* MALLOCLOG */
    434 {
    435 	struct kmembuckets *kbp;
    436 	struct kmemusage *kup;
    437 	struct freelist *freep;
    438 	long size;
    439 	int s;
    440 #ifdef DIAGNOSTIC
    441 	caddr_t cp;
    442 	int32_t *end, *lp;
    443 	long alloc, copysize;
    444 #endif
    445 #ifdef KMEMSTATS
    446 	struct kmemstats *ksp = &kmemstats[type];
    447 #endif
    448 
    449 #ifdef MALLOC_DEBUG
    450 	if (debug_free(addr, type))
    451 		return;
    452 #endif
    453 
    454 #ifdef DIAGNOSTIC
    455 	/*
    456 	 * Ensure that we're free'ing something that we could
    457 	 * have allocated in the first place.  That is, check
    458 	 * to see that the address is within kmem_map.
    459 	 */
    460 	if (__predict_false((vaddr_t)addr < kmem_map->header.start ||
    461 			    (vaddr_t)addr >= kmem_map->header.end))
    462 		panic("free: addr %p not within kmem_map", addr);
    463 #endif
    464 
    465 	kup = btokup(addr);
    466 	size = 1 << kup->ku_indx;
    467 	kbp = &bucket[kup->ku_indx];
    468 	s = splvm();
    469 #ifdef MALLOCLOG
    470 	domlog(addr, 0, type, 2, file, line);
    471 #endif
    472 #ifdef DIAGNOSTIC
    473 	/*
    474 	 * Check for returns of data that do not point to the
    475 	 * beginning of the allocation.
    476 	 */
    477 	if (size > PAGE_SIZE)
    478 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    479 	else
    480 		alloc = addrmask[kup->ku_indx];
    481 	if (((u_long)addr & alloc) != 0)
    482 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld\n",
    483 			addr, size, memname[type], alloc);
    484 #endif /* DIAGNOSTIC */
    485 	if (size > MAXALLOCSAVE) {
    486 		uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
    487 #ifdef KMEMSTATS
    488 		size = kup->ku_pagecnt << PGSHIFT;
    489 		ksp->ks_memuse -= size;
    490 		kup->ku_indx = 0;
    491 		kup->ku_pagecnt = 0;
    492 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
    493 		    ksp->ks_memuse < ksp->ks_limit)
    494 			wakeup((caddr_t)ksp);
    495 		ksp->ks_inuse--;
    496 		kbp->kb_total -= 1;
    497 #endif
    498 		splx(s);
    499 		return;
    500 	}
    501 	freep = (struct freelist *)addr;
    502 #ifdef DIAGNOSTIC
    503 	/*
    504 	 * Check for multiple frees. Use a quick check to see if
    505 	 * it looks free before laboriously searching the freelist.
    506 	 */
    507 	if (__predict_false(freep->spare0 == WEIRD_ADDR)) {
    508 		for (cp = kbp->kb_next; cp;
    509 		    cp = ((struct freelist *)cp)->next) {
    510 			if (addr != cp)
    511 				continue;
    512 			printf("multiply freed item %p\n", addr);
    513 #ifdef MALLOCLOG
    514 			hitmlog(addr);
    515 #endif
    516 			panic("free: duplicated free");
    517 		}
    518 	}
    519 #ifdef LOCKDEBUG
    520 	/*
    521 	 * Check if we're freeing a locked simple lock.
    522 	 */
    523 	simple_lock_freecheck(addr, (char *)addr + size);
    524 #endif
    525 	/*
    526 	 * Copy in known text to detect modification after freeing
    527 	 * and to make it look free. Also, save the type being freed
    528 	 * so we can list likely culprit if modification is detected
    529 	 * when the object is reallocated.
    530 	 */
    531 	copysize = size < MAX_COPY ? size : MAX_COPY;
    532 	end = (int32_t *)&((caddr_t)addr)[copysize];
    533 	for (lp = (int32_t *)addr; lp < end; lp++)
    534 		*lp = WEIRD_ADDR;
    535 	freep->type = type;
    536 #endif /* DIAGNOSTIC */
    537 #ifdef KMEMSTATS
    538 	kup->ku_freecnt++;
    539 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
    540 		if (kup->ku_freecnt > kbp->kb_elmpercl)
    541 			panic("free: multiple frees");
    542 		else if (kbp->kb_totalfree > kbp->kb_highwat)
    543 			kbp->kb_couldfree++;
    544 	}
    545 	kbp->kb_totalfree++;
    546 	ksp->ks_memuse -= size;
    547 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
    548 	    ksp->ks_memuse < ksp->ks_limit)
    549 		wakeup((caddr_t)ksp);
    550 	ksp->ks_inuse--;
    551 #endif
    552 	if (kbp->kb_next == NULL)
    553 		kbp->kb_next = addr;
    554 	else
    555 		((struct freelist *)kbp->kb_last)->next = addr;
    556 	freep->next = NULL;
    557 	kbp->kb_last = addr;
    558 	splx(s);
    559 }
    560 
    561 /*
    562  * Change the size of a block of memory.
    563  */
    564 void *
    565 realloc(curaddr, newsize, type, flags)
    566 	void *curaddr;
    567 	unsigned long newsize;
    568 	int type, flags;
    569 {
    570 	struct kmemusage *kup;
    571 	long cursize;
    572 	void *newaddr;
    573 #ifdef DIAGNOSTIC
    574 	long alloc;
    575 #endif
    576 
    577 	/*
    578 	 * Realloc() with a NULL pointer is the same as malloc().
    579 	 */
    580 	if (curaddr == NULL)
    581 		return (malloc(newsize, type, flags));
    582 
    583 	/*
    584 	 * Realloc() with zero size is the same as free().
    585 	 */
    586 	if (newsize == 0) {
    587 		free(curaddr, type);
    588 		return (NULL);
    589 	}
    590 
    591 #ifdef LOCKDEBUG
    592 	if ((flags & M_NOWAIT) == 0)
    593 		simple_lock_only_held(NULL, "realloc");
    594 #endif
    595 
    596 	/*
    597 	 * Find out how large the old allocation was (and do some
    598 	 * sanity checking).
    599 	 */
    600 	kup = btokup(curaddr);
    601 	cursize = 1 << kup->ku_indx;
    602 
    603 #ifdef DIAGNOSTIC
    604 	/*
    605 	 * Check for returns of data that do not point to the
    606 	 * beginning of the allocation.
    607 	 */
    608 	if (cursize > PAGE_SIZE)
    609 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    610 	else
    611 		alloc = addrmask[kup->ku_indx];
    612 	if (((u_long)curaddr & alloc) != 0)
    613 		panic("realloc: unaligned addr %p, size %ld, type %s, mask %ld\n",
    614 			curaddr, cursize, memname[type], alloc);
    615 #endif /* DIAGNOSTIC */
    616 
    617 	if (cursize > MAXALLOCSAVE)
    618 		cursize = ctob(kup->ku_pagecnt);
    619 
    620 	/*
    621 	 * If we already actually have as much as they want, we're done.
    622 	 */
    623 	if (newsize <= cursize)
    624 		return (curaddr);
    625 
    626 	/*
    627 	 * Can't satisfy the allocation with the existing block.
    628 	 * Allocate a new one and copy the data.
    629 	 */
    630 	newaddr = malloc(newsize, type, flags);
    631 	if (__predict_false(newaddr == NULL)) {
    632 		/*
    633 		 * Malloc() failed, because flags included M_NOWAIT.
    634 		 * Return NULL to indicate that failure.  The old
    635 		 * pointer is still valid.
    636 		 */
    637 		return NULL;
    638 	}
    639 	memcpy(newaddr, curaddr, cursize);
    640 
    641 	/*
    642 	 * We were successful: free the old allocation and return
    643 	 * the new one.
    644 	 */
    645 	free(curaddr, type);
    646 	return (newaddr);
    647 }
    648 
    649 /*
    650  * Compute the number of pages that kmem_map will map, that is,
    651  * the size of the kernel malloc arena.
    652  */
    653 void
    654 kmeminit_nkmempages()
    655 {
    656 	int npages;
    657 
    658 	if (nkmempages != 0) {
    659 		/*
    660 		 * It's already been set (by us being here before, or
    661 		 * by patching or kernel config options), bail out now.
    662 		 */
    663 		return;
    664 	}
    665 
    666 	/*
    667 	 * We use the following (simple) formula:
    668 	 *
    669 	 *	- Starting point is physical memory / 4.
    670 	 *
    671 	 *	- Clamp it down to NKMEMPAGES_MAX.
    672 	 *
    673 	 *	- Round it up to NKMEMPAGES_MIN.
    674 	 */
    675 	npages = physmem / 4;
    676 
    677 	if (npages > NKMEMPAGES_MAX)
    678 		npages = NKMEMPAGES_MAX;
    679 
    680 	if (npages < NKMEMPAGES_MIN)
    681 		npages = NKMEMPAGES_MIN;
    682 
    683 	nkmempages = npages;
    684 }
    685 
    686 /*
    687  * Initialize the kernel memory allocator
    688  */
    689 void
    690 kmeminit()
    691 {
    692 #ifdef KMEMSTATS
    693 	long indx;
    694 #endif
    695 
    696 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
    697 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
    698 #endif
    699 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
    700 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
    701 #endif
    702 #if	(MAXALLOCSAVE < NBPG)
    703 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
    704 #endif
    705 
    706 	if (sizeof(struct freelist) > (1 << MINBUCKET))
    707 		panic("minbucket too small/struct freelist too big");
    708 
    709 	/*
    710 	 * Compute the number of kmem_map pages, if we have not
    711 	 * done so already.
    712 	 */
    713 	kmeminit_nkmempages();
    714 
    715 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
    716 		(vsize_t)(nkmempages * sizeof(struct kmemusage)));
    717 	kmem_map = uvm_km_suballoc(kernel_map, (vaddr_t *)&kmembase,
    718 		(vaddr_t *)&kmemlimit, (vsize_t)(nkmempages << PAGE_SHIFT),
    719 			VM_MAP_INTRSAFE, FALSE, &kmem_map_store);
    720 #ifdef KMEMSTATS
    721 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
    722 		if (1 << indx >= PAGE_SIZE)
    723 			bucket[indx].kb_elmpercl = 1;
    724 		else
    725 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
    726 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
    727 	}
    728 	for (indx = 0; indx < M_LAST; indx++)
    729 		kmemstats[indx].ks_limit =
    730 		    ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
    731 #endif
    732 #ifdef MALLOC_DEBUG
    733 	debug_malloc_init();
    734 #endif
    735 }
    736 
    737 #ifdef DDB
    738 #include <ddb/db_output.h>
    739 
    740 /*
    741  * Dump kmem statistics from ddb.
    742  *
    743  * usage: call dump_kmemstats
    744  */
    745 void	dump_kmemstats __P((void));
    746 
    747 void
    748 dump_kmemstats()
    749 {
    750 #ifdef KMEMSTATS
    751 	const char *name;
    752 	int i;
    753 
    754 	for (i = 0; i < M_LAST; i++) {
    755 		name = memname[i] ? memname[i] : "";
    756 
    757 		db_printf("%2d %s%.*s %ld\n", i, name,
    758 		    (int)(20 - strlen(name)), "                    ",
    759 		    kmemstats[i].ks_memuse);
    760 	}
    761 #else
    762 	db_printf("Kmem stats are not being collected.\n");
    763 #endif /* KMEMSTATS */
    764 }
    765 #endif /* DDB */
    766