Home | History | Annotate | Line # | Download | only in kern
kern_malloc.c revision 1.57.2.8
      1 /*	$NetBSD: kern_malloc.c,v 1.57.2.8 2002/09/17 21:22:06 nathanw 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.57.2.8 2002/09/17 21:22:06 nathanw 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 #include "opt_malloc_debug.h"
     87 
     88 struct kmembuckets bucket[MINBUCKET + 16];
     89 struct kmemstats kmemstats[M_LAST];
     90 struct kmemusage *kmemusage;
     91 char *kmembase, *kmemlimit;
     92 const char * const memname[] = INITKMEMNAMES;
     93 
     94 #ifdef MALLOCLOG
     95 #ifndef MALLOCLOGSIZE
     96 #define	MALLOCLOGSIZE	100000
     97 #endif
     98 
     99 struct malloclog {
    100 	void *addr;
    101 	long size;
    102 	int type;
    103 	int action;
    104 	const char *file;
    105 	long line;
    106 } malloclog[MALLOCLOGSIZE];
    107 
    108 long	malloclogptr;
    109 
    110 static void domlog(void *, long, int, int, const char *, long);
    111 static void hitmlog(void *);
    112 
    113 static void
    114 domlog(void *a, long size, int type, int action, const char *file, long line)
    115 {
    116 
    117 	malloclog[malloclogptr].addr = a;
    118 	malloclog[malloclogptr].size = size;
    119 	malloclog[malloclogptr].type = type;
    120 	malloclog[malloclogptr].action = action;
    121 	malloclog[malloclogptr].file = file;
    122 	malloclog[malloclogptr].line = line;
    123 	malloclogptr++;
    124 	if (malloclogptr >= MALLOCLOGSIZE)
    125 		malloclogptr = 0;
    126 }
    127 
    128 static void
    129 hitmlog(void *a)
    130 {
    131 	struct malloclog *lp;
    132 	long l;
    133 
    134 #define	PRT do { \
    135 	if (malloclog[l].addr == a && malloclog[l].action) { \
    136 		lp = &malloclog[l]; \
    137 		printf("malloc log entry %ld:\n", l); \
    138 		printf("\taddr = %p\n", lp->addr); \
    139 		printf("\tsize = %ld\n", lp->size); \
    140 		printf("\ttype = %s\n", memname[lp->type]); \
    141 		printf("\taction = %s\n", lp->action == 1 ? "alloc" : "free"); \
    142 		printf("\tfile = %s\n", lp->file); \
    143 		printf("\tline = %ld\n", lp->line); \
    144 	} \
    145 } while (/* CONSTCOND */0)
    146 
    147 	for (l = malloclogptr; l < MALLOCLOGSIZE; l++)
    148 		PRT;
    149 
    150 	for (l = 0; l < malloclogptr; l++)
    151 		PRT;
    152 }
    153 #endif /* MALLOCLOG */
    154 
    155 #ifdef DIAGNOSTIC
    156 /*
    157  * This structure provides a set of masks to catch unaligned frees.
    158  */
    159 const long addrmask[] = { 0,
    160 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
    161 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
    162 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
    163 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
    164 };
    165 
    166 /*
    167  * The WEIRD_ADDR is used as known text to copy into free objects so
    168  * that modifications after frees can be detected.
    169  */
    170 #define	WEIRD_ADDR	((unsigned) 0xdeadbeef)
    171 #ifdef DEBUG
    172 #define	MAX_COPY	PAGE_SIZE
    173 #else
    174 #define	MAX_COPY	32
    175 #endif
    176 
    177 /*
    178  * Normally the freelist structure is used only to hold the list pointer
    179  * for free objects.  However, when running with diagnostics, the first
    180  * 8 bytes of the structure is unused except for diagnostic information,
    181  * and the free list pointer is at offst 8 in the structure.  Since the
    182  * first 8 bytes is the portion of the structure most often modified, this
    183  * helps to detect memory reuse problems and avoid free list corruption.
    184  */
    185 struct freelist {
    186 	int32_t	spare0;
    187 	int16_t	type;
    188 	int16_t	spare1;
    189 	caddr_t	next;
    190 };
    191 #else /* !DIAGNOSTIC */
    192 struct freelist {
    193 	caddr_t	next;
    194 };
    195 #endif /* DIAGNOSTIC */
    196 
    197 /*
    198  * Allocate a block of memory
    199  */
    200 #ifdef MALLOCLOG
    201 void *
    202 _malloc(unsigned long size, int type, int flags, const char *file, long line)
    203 #else
    204 void *
    205 malloc(unsigned long size, int type, int flags)
    206 #endif /* MALLOCLOG */
    207 {
    208 	struct kmembuckets *kbp;
    209 	struct kmemusage *kup;
    210 	struct freelist *freep;
    211 	long indx, npg, allocsize;
    212 	int s;
    213 	caddr_t va, cp, savedlist;
    214 #ifdef DIAGNOSTIC
    215 	int32_t *end, *lp;
    216 	int copysize;
    217 	const char *savedtype;
    218 #endif
    219 #ifdef KMEMSTATS
    220 	struct kmemstats *ksp = &kmemstats[type];
    221 
    222 	if (__predict_false(((unsigned long)type) > M_LAST))
    223 		panic("malloc - bogus type");
    224 #endif
    225 #ifdef LOCKDEBUG
    226 	if ((flags & M_NOWAIT) == 0)
    227 		simple_lock_only_held(NULL, "malloc");
    228 #endif
    229 #ifdef MALLOC_DEBUG
    230 	if (debug_malloc(size, type, flags, (void **) &va))
    231 		return ((void *) va);
    232 #endif
    233 	indx = BUCKETINDX(size);
    234 	kbp = &bucket[indx];
    235 	s = splvm();
    236 #ifdef KMEMSTATS
    237 	while (ksp->ks_memuse >= ksp->ks_limit) {
    238 		if (flags & M_NOWAIT) {
    239 			splx(s);
    240 			return ((void *) NULL);
    241 		}
    242 		if (ksp->ks_limblocks < 65535)
    243 			ksp->ks_limblocks++;
    244 		tsleep((caddr_t)ksp, PSWP+2, memname[type], 0);
    245 	}
    246 	ksp->ks_size |= 1 << indx;
    247 #endif
    248 #ifdef DIAGNOSTIC
    249 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
    250 #endif
    251 	if (kbp->kb_next == NULL) {
    252 		kbp->kb_last = NULL;
    253 		if (size > MAXALLOCSAVE)
    254 			allocsize = round_page(size);
    255 		else
    256 			allocsize = 1 << indx;
    257 		npg = btoc(allocsize);
    258 		va = (caddr_t) uvm_km_kmemalloc(kmem_map, NULL,
    259 		    (vsize_t)ctob(npg),
    260 		    ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) |
    261 		    ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 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|M_CANFAIL)) == 0)
    272 				panic("malloc: out of space in kmem_map");
    273 			splx(s);
    274 			return (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), VM_PROT_WRITE);
    335 		vm_map_unlock(kmem_map);
    336 
    337 		if (__predict_false(rv == 0)) {
    338 			printf("Data modified on freelist: "
    339 			    "word %ld of object %p size %ld previous type %s "
    340 			    "(invalid addr %p)\n",
    341 			    (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
    342 			    va, size, savedtype, kbp->kb_next);
    343 #ifdef MALLOCLOG
    344 			hitmlog(va);
    345 #endif
    346 			kbp->kb_next = NULL;
    347 		}
    348 	}
    349 
    350 	/* Fill the fields that we've used with WEIRD_ADDR */
    351 #if BYTE_ORDER == BIG_ENDIAN
    352 	freep->type = WEIRD_ADDR >> 16;
    353 #endif
    354 #if BYTE_ORDER == LITTLE_ENDIAN
    355 	freep->type = (short)WEIRD_ADDR;
    356 #endif
    357 	end = (int32_t *)&freep->next +
    358 	    (sizeof(freep->next) / sizeof(int32_t));
    359 	for (lp = (int32_t *)&freep->next; lp < end; lp++)
    360 		*lp = WEIRD_ADDR;
    361 
    362 	/* and check that the data hasn't been modified. */
    363 	end = (int32_t *)&va[copysize];
    364 	for (lp = (int32_t *)va; lp < end; lp++) {
    365 		if (__predict_true(*lp == WEIRD_ADDR))
    366 			continue;
    367 		printf("Data modified on freelist: "
    368 		    "word %ld of object %p size %ld previous type %s "
    369 		    "(0x%x != 0x%x)\n",
    370 		    (long)(lp - (int32_t *)va), va, size,
    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 	if ((flags & M_ZERO) != 0)
    403 		memset(va, 0, size);
    404 	return ((void *) va);
    405 }
    406 
    407 /*
    408  * Free a block of memory allocated by malloc.
    409  */
    410 #ifdef MALLOCLOG
    411 void
    412 _free(void *addr, int type, const char *file, long line)
    413 #else
    414 void
    415 free(void *addr, int type)
    416 #endif /* MALLOCLOG */
    417 {
    418 	struct kmembuckets *kbp;
    419 	struct kmemusage *kup;
    420 	struct freelist *freep;
    421 	long size;
    422 	int s;
    423 #ifdef DIAGNOSTIC
    424 	caddr_t cp;
    425 	int32_t *end, *lp;
    426 	long alloc, copysize;
    427 #endif
    428 #ifdef KMEMSTATS
    429 	struct kmemstats *ksp = &kmemstats[type];
    430 #endif
    431 
    432 #ifdef MALLOC_DEBUG
    433 	if (debug_free(addr, type))
    434 		return;
    435 #endif
    436 
    437 #ifdef DIAGNOSTIC
    438 	/*
    439 	 * Ensure that we're free'ing something that we could
    440 	 * have allocated in the first place.  That is, check
    441 	 * to see that the address is within kmem_map.
    442 	 */
    443 	if (__predict_false((vaddr_t)addr < kmem_map->header.start ||
    444 	    (vaddr_t)addr >= kmem_map->header.end))
    445 		panic("free: addr %p not within kmem_map", addr);
    446 #endif
    447 
    448 	kup = btokup(addr);
    449 	size = 1 << kup->ku_indx;
    450 	kbp = &bucket[kup->ku_indx];
    451 	s = splvm();
    452 #ifdef MALLOCLOG
    453 	domlog(addr, 0, type, 2, file, line);
    454 #endif
    455 #ifdef DIAGNOSTIC
    456 	/*
    457 	 * Check for returns of data that do not point to the
    458 	 * beginning of the allocation.
    459 	 */
    460 	if (size > PAGE_SIZE)
    461 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    462 	else
    463 		alloc = addrmask[kup->ku_indx];
    464 	if (((u_long)addr & alloc) != 0)
    465 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld\n",
    466 		    addr, size, memname[type], alloc);
    467 #endif /* DIAGNOSTIC */
    468 	if (size > MAXALLOCSAVE) {
    469 		uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
    470 #ifdef KMEMSTATS
    471 		size = kup->ku_pagecnt << PGSHIFT;
    472 		ksp->ks_memuse -= size;
    473 		kup->ku_indx = 0;
    474 		kup->ku_pagecnt = 0;
    475 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
    476 		    ksp->ks_memuse < ksp->ks_limit)
    477 			wakeup((caddr_t)ksp);
    478 		ksp->ks_inuse--;
    479 		kbp->kb_total -= 1;
    480 #endif
    481 		splx(s);
    482 		return;
    483 	}
    484 	freep = (struct freelist *)addr;
    485 #ifdef DIAGNOSTIC
    486 	/*
    487 	 * Check for multiple frees. Use a quick check to see if
    488 	 * it looks free before laboriously searching the freelist.
    489 	 */
    490 	if (__predict_false(freep->spare0 == WEIRD_ADDR)) {
    491 		for (cp = kbp->kb_next; cp;
    492 		    cp = ((struct freelist *)cp)->next) {
    493 			if (addr != cp)
    494 				continue;
    495 			printf("multiply freed item %p\n", addr);
    496 #ifdef MALLOCLOG
    497 			hitmlog(addr);
    498 #endif
    499 			panic("free: duplicated free");
    500 		}
    501 	}
    502 #ifdef LOCKDEBUG
    503 	/*
    504 	 * Check if we're freeing a locked simple lock.
    505 	 */
    506 	simple_lock_freecheck(addr, (char *)addr + size);
    507 #endif
    508 	/*
    509 	 * Copy in known text to detect modification after freeing
    510 	 * and to make it look free. Also, save the type being freed
    511 	 * so we can list likely culprit if modification is detected
    512 	 * when the object is reallocated.
    513 	 */
    514 	copysize = size < MAX_COPY ? size : MAX_COPY;
    515 	end = (int32_t *)&((caddr_t)addr)[copysize];
    516 	for (lp = (int32_t *)addr; lp < end; lp++)
    517 		*lp = WEIRD_ADDR;
    518 	freep->type = type;
    519 #endif /* DIAGNOSTIC */
    520 #ifdef KMEMSTATS
    521 	kup->ku_freecnt++;
    522 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
    523 		if (kup->ku_freecnt > kbp->kb_elmpercl)
    524 			panic("free: multiple frees");
    525 		else if (kbp->kb_totalfree > kbp->kb_highwat)
    526 			kbp->kb_couldfree++;
    527 	}
    528 	kbp->kb_totalfree++;
    529 	ksp->ks_memuse -= size;
    530 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
    531 	    ksp->ks_memuse < ksp->ks_limit)
    532 		wakeup((caddr_t)ksp);
    533 	ksp->ks_inuse--;
    534 #endif
    535 	if (kbp->kb_next == NULL)
    536 		kbp->kb_next = addr;
    537 	else
    538 		((struct freelist *)kbp->kb_last)->next = addr;
    539 	freep->next = NULL;
    540 	kbp->kb_last = addr;
    541 	splx(s);
    542 }
    543 
    544 /*
    545  * Change the size of a block of memory.
    546  */
    547 void *
    548 realloc(void *curaddr, unsigned long newsize, int type, int flags)
    549 {
    550 	struct kmemusage *kup;
    551 	unsigned long cursize;
    552 	void *newaddr;
    553 #ifdef DIAGNOSTIC
    554 	long alloc;
    555 #endif
    556 
    557 	/*
    558 	 * realloc() with a NULL pointer is the same as malloc().
    559 	 */
    560 	if (curaddr == NULL)
    561 		return (malloc(newsize, type, flags));
    562 
    563 	/*
    564 	 * realloc() with zero size is the same as free().
    565 	 */
    566 	if (newsize == 0) {
    567 		free(curaddr, type);
    568 		return (NULL);
    569 	}
    570 
    571 #ifdef LOCKDEBUG
    572 	if ((flags & M_NOWAIT) == 0)
    573 		simple_lock_only_held(NULL, "realloc");
    574 #endif
    575 
    576 	/*
    577 	 * Find out how large the old allocation was (and do some
    578 	 * sanity checking).
    579 	 */
    580 	kup = btokup(curaddr);
    581 	cursize = 1 << kup->ku_indx;
    582 
    583 #ifdef DIAGNOSTIC
    584 	/*
    585 	 * Check for returns of data that do not point to the
    586 	 * beginning of the allocation.
    587 	 */
    588 	if (cursize > PAGE_SIZE)
    589 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
    590 	else
    591 		alloc = addrmask[kup->ku_indx];
    592 	if (((u_long)curaddr & alloc) != 0)
    593 		panic("realloc: "
    594 		    "unaligned addr %p, size %ld, type %s, mask %ld\n",
    595 		    curaddr, cursize, memname[type], alloc);
    596 #endif /* DIAGNOSTIC */
    597 
    598 	if (cursize > MAXALLOCSAVE)
    599 		cursize = ctob(kup->ku_pagecnt);
    600 
    601 	/*
    602 	 * If we already actually have as much as they want, we're done.
    603 	 */
    604 	if (newsize <= cursize)
    605 		return (curaddr);
    606 
    607 	/*
    608 	 * Can't satisfy the allocation with the existing block.
    609 	 * Allocate a new one and copy the data.
    610 	 */
    611 	newaddr = malloc(newsize, type, flags);
    612 	if (__predict_false(newaddr == NULL)) {
    613 		/*
    614 		 * malloc() failed, because flags included M_NOWAIT.
    615 		 * Return NULL to indicate that failure.  The old
    616 		 * pointer is still valid.
    617 		 */
    618 		return (NULL);
    619 	}
    620 	memcpy(newaddr, curaddr, cursize);
    621 
    622 	/*
    623 	 * We were successful: free the old allocation and return
    624 	 * the new one.
    625 	 */
    626 	free(curaddr, type);
    627 	return (newaddr);
    628 }
    629 
    630 /*
    631  * Roundup size to the actual allocation size.
    632  */
    633 unsigned long
    634 malloc_roundup(unsigned long size)
    635 {
    636 
    637 	if (size > MAXALLOCSAVE)
    638 		return (roundup(size, PAGE_SIZE));
    639 	else
    640 		return (1 << BUCKETINDX(size));
    641 }
    642 
    643 /*
    644  * Compute the number of pages that kmem_map will map, that is,
    645  * the size of the kernel malloc arena.
    646  */
    647 void
    648 kmeminit_nkmempages(void)
    649 {
    650 	int npages;
    651 
    652 	if (nkmempages != 0) {
    653 		/*
    654 		 * It's already been set (by us being here before, or
    655 		 * by patching or kernel config options), bail out now.
    656 		 */
    657 		return;
    658 	}
    659 
    660 	/*
    661 	 * We use the following (simple) formula:
    662 	 *
    663 	 *	- Starting point is physical memory / 4.
    664 	 *
    665 	 *	- Clamp it down to NKMEMPAGES_MAX.
    666 	 *
    667 	 *	- Round it up to NKMEMPAGES_MIN.
    668 	 */
    669 	npages = physmem / 4;
    670 
    671 	if (npages > NKMEMPAGES_MAX)
    672 		npages = NKMEMPAGES_MAX;
    673 
    674 	if (npages < NKMEMPAGES_MIN)
    675 		npages = NKMEMPAGES_MIN;
    676 
    677 	nkmempages = npages;
    678 }
    679 
    680 /*
    681  * Initialize the kernel memory allocator
    682  */
    683 void
    684 kmeminit(void)
    685 {
    686 #ifdef KMEMSTATS
    687 	long indx;
    688 #endif
    689 
    690 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
    691 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
    692 #endif
    693 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
    694 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
    695 #endif
    696 #if	(MAXALLOCSAVE < NBPG)
    697 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
    698 #endif
    699 
    700 	if (sizeof(struct freelist) > (1 << MINBUCKET))
    701 		panic("minbucket too small/struct freelist too big");
    702 
    703 	/*
    704 	 * Compute the number of kmem_map pages, if we have not
    705 	 * done so already.
    706 	 */
    707 	kmeminit_nkmempages();
    708 
    709 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
    710 	    (vsize_t)(nkmempages * sizeof(struct kmemusage)));
    711 	kmem_map = uvm_km_suballoc(kernel_map, (vaddr_t *)&kmembase,
    712 	    (vaddr_t *)&kmemlimit, (vsize_t)(nkmempages << PAGE_SHIFT),
    713 	    VM_MAP_INTRSAFE, FALSE, &kmem_map_store);
    714 #ifdef KMEMSTATS
    715 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
    716 		if (1 << indx >= PAGE_SIZE)
    717 			bucket[indx].kb_elmpercl = 1;
    718 		else
    719 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
    720 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
    721 	}
    722 	for (indx = 0; indx < M_LAST; indx++)
    723 		kmemstats[indx].ks_limit =
    724 		    ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
    725 #endif
    726 #ifdef MALLOC_DEBUG
    727 	debug_malloc_init();
    728 #endif
    729 }
    730 
    731 #ifdef DDB
    732 #include <ddb/db_output.h>
    733 
    734 /*
    735  * Dump kmem statistics from ddb.
    736  *
    737  * usage: call dump_kmemstats
    738  */
    739 void	dump_kmemstats(void);
    740 
    741 void
    742 dump_kmemstats(void)
    743 {
    744 #ifdef KMEMSTATS
    745 	const char *name;
    746 	int i;
    747 
    748 	for (i = 0; i < M_LAST; i++) {
    749 		name = memname[i] ? memname[i] : "";
    750 
    751 		db_printf("%2d %s%.*s %ld\n", i, name,
    752 		    (int)(20 - strlen(name)), "                    ",
    753 		    kmemstats[i].ks_memuse);
    754 	}
    755 #else
    756 	db_printf("Kmem stats are not being collected.\n");
    757 #endif /* KMEMSTATS */
    758 }
    759 #endif /* DDB */
    760