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