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