xref: /netbsd-src/sys/kern/kern_malloc.c (revision 06be8101a16cc95f40783b3cb7afd12112103a9a)
1 /*	$NetBSD: kern_malloc.c,v 1.64 2001/11/12 15:25:12 lukem 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.64 2001/11/12 15:25:12 lukem 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 = roundup(size, 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 	return ((void *) va);
414 }
415 
416 /*
417  * Free a block of memory allocated by malloc.
418  */
419 #ifdef MALLOCLOG
420 void
421 _free(addr, type, file, line)
422 	void *addr;
423 	int type;
424 	const char *file;
425 	long line;
426 #else
427 void
428 free(addr, type)
429 	void *addr;
430 	int type;
431 #endif /* MALLOCLOG */
432 {
433 	struct kmembuckets *kbp;
434 	struct kmemusage *kup;
435 	struct freelist *freep;
436 	long size;
437 	int s;
438 #ifdef DIAGNOSTIC
439 	caddr_t cp;
440 	int32_t *end, *lp;
441 	long alloc, copysize;
442 #endif
443 #ifdef KMEMSTATS
444 	struct kmemstats *ksp = &kmemstats[type];
445 #endif
446 
447 #ifdef MALLOC_DEBUG
448 	if (debug_free(addr, type))
449 		return;
450 #endif
451 
452 #ifdef DIAGNOSTIC
453 	/*
454 	 * Ensure that we're free'ing something that we could
455 	 * have allocated in the first place.  That is, check
456 	 * to see that the address is within kmem_map.
457 	 */
458 	if (__predict_false((vaddr_t)addr < kmem_map->header.start ||
459 			    (vaddr_t)addr >= kmem_map->header.end))
460 		panic("free: addr %p not within kmem_map", addr);
461 #endif
462 
463 	kup = btokup(addr);
464 	size = 1 << kup->ku_indx;
465 	kbp = &bucket[kup->ku_indx];
466 	s = splvm();
467 #ifdef MALLOCLOG
468 	domlog(addr, 0, type, 2, file, line);
469 #endif
470 #ifdef DIAGNOSTIC
471 	/*
472 	 * Check for returns of data that do not point to the
473 	 * beginning of the allocation.
474 	 */
475 	if (size > PAGE_SIZE)
476 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
477 	else
478 		alloc = addrmask[kup->ku_indx];
479 	if (((u_long)addr & alloc) != 0)
480 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld\n",
481 			addr, size, memname[type], alloc);
482 #endif /* DIAGNOSTIC */
483 	if (size > MAXALLOCSAVE) {
484 		uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
485 #ifdef KMEMSTATS
486 		size = kup->ku_pagecnt << PGSHIFT;
487 		ksp->ks_memuse -= size;
488 		kup->ku_indx = 0;
489 		kup->ku_pagecnt = 0;
490 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
491 		    ksp->ks_memuse < ksp->ks_limit)
492 			wakeup((caddr_t)ksp);
493 		ksp->ks_inuse--;
494 		kbp->kb_total -= 1;
495 #endif
496 		splx(s);
497 		return;
498 	}
499 	freep = (struct freelist *)addr;
500 #ifdef DIAGNOSTIC
501 	/*
502 	 * Check for multiple frees. Use a quick check to see if
503 	 * it looks free before laboriously searching the freelist.
504 	 */
505 	if (__predict_false(freep->spare0 == WEIRD_ADDR)) {
506 		for (cp = kbp->kb_next; cp;
507 		    cp = ((struct freelist *)cp)->next) {
508 			if (addr != cp)
509 				continue;
510 			printf("multiply freed item %p\n", addr);
511 #ifdef MALLOCLOG
512 			hitmlog(addr);
513 #endif
514 			panic("free: duplicated free");
515 		}
516 	}
517 #ifdef LOCKDEBUG
518 	/*
519 	 * Check if we're freeing a locked simple lock.
520 	 */
521 	simple_lock_freecheck(addr, (char *)addr + size);
522 #endif
523 	/*
524 	 * Copy in known text to detect modification after freeing
525 	 * and to make it look free. Also, save the type being freed
526 	 * so we can list likely culprit if modification is detected
527 	 * when the object is reallocated.
528 	 */
529 	copysize = size < MAX_COPY ? size : MAX_COPY;
530 	end = (int32_t *)&((caddr_t)addr)[copysize];
531 	for (lp = (int32_t *)addr; lp < end; lp++)
532 		*lp = WEIRD_ADDR;
533 	freep->type = type;
534 #endif /* DIAGNOSTIC */
535 #ifdef KMEMSTATS
536 	kup->ku_freecnt++;
537 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
538 		if (kup->ku_freecnt > kbp->kb_elmpercl)
539 			panic("free: multiple frees");
540 		else if (kbp->kb_totalfree > kbp->kb_highwat)
541 			kbp->kb_couldfree++;
542 	}
543 	kbp->kb_totalfree++;
544 	ksp->ks_memuse -= size;
545 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
546 	    ksp->ks_memuse < ksp->ks_limit)
547 		wakeup((caddr_t)ksp);
548 	ksp->ks_inuse--;
549 #endif
550 	if (kbp->kb_next == NULL)
551 		kbp->kb_next = addr;
552 	else
553 		((struct freelist *)kbp->kb_last)->next = addr;
554 	freep->next = NULL;
555 	kbp->kb_last = addr;
556 	splx(s);
557 }
558 
559 /*
560  * Change the size of a block of memory.
561  */
562 void *
563 realloc(curaddr, newsize, type, flags)
564 	void *curaddr;
565 	unsigned long newsize;
566 	int type, flags;
567 {
568 	struct kmemusage *kup;
569 	long cursize;
570 	void *newaddr;
571 #ifdef DIAGNOSTIC
572 	long alloc;
573 #endif
574 
575 	/*
576 	 * Realloc() with a NULL pointer is the same as malloc().
577 	 */
578 	if (curaddr == NULL)
579 		return (malloc(newsize, type, flags));
580 
581 	/*
582 	 * Realloc() with zero size is the same as free().
583 	 */
584 	if (newsize == 0) {
585 		free(curaddr, type);
586 		return (NULL);
587 	}
588 
589 #ifdef LOCKDEBUG
590 	if ((flags & M_NOWAIT) == 0)
591 		simple_lock_only_held(NULL, "realloc");
592 #endif
593 
594 	/*
595 	 * Find out how large the old allocation was (and do some
596 	 * sanity checking).
597 	 */
598 	kup = btokup(curaddr);
599 	cursize = 1 << kup->ku_indx;
600 
601 #ifdef DIAGNOSTIC
602 	/*
603 	 * Check for returns of data that do not point to the
604 	 * beginning of the allocation.
605 	 */
606 	if (cursize > PAGE_SIZE)
607 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
608 	else
609 		alloc = addrmask[kup->ku_indx];
610 	if (((u_long)curaddr & alloc) != 0)
611 		panic("realloc: unaligned addr %p, size %ld, type %s, mask %ld\n",
612 			curaddr, cursize, memname[type], alloc);
613 #endif /* DIAGNOSTIC */
614 
615 	if (cursize > MAXALLOCSAVE)
616 		cursize = ctob(kup->ku_pagecnt);
617 
618 	/*
619 	 * If we already actually have as much as they want, we're done.
620 	 */
621 	if (newsize <= cursize)
622 		return (curaddr);
623 
624 	/*
625 	 * Can't satisfy the allocation with the existing block.
626 	 * Allocate a new one and copy the data.
627 	 */
628 	newaddr = malloc(newsize, type, flags);
629 	if (__predict_false(newaddr == NULL)) {
630 		/*
631 		 * Malloc() failed, because flags included M_NOWAIT.
632 		 * Return NULL to indicate that failure.  The old
633 		 * pointer is still valid.
634 		 */
635 		return NULL;
636 	}
637 	memcpy(newaddr, curaddr, cursize);
638 
639 	/*
640 	 * We were successful: free the old allocation and return
641 	 * the new one.
642 	 */
643 	free(curaddr, type);
644 	return (newaddr);
645 }
646 
647 /*
648  * Compute the number of pages that kmem_map will map, that is,
649  * the size of the kernel malloc arena.
650  */
651 void
652 kmeminit_nkmempages()
653 {
654 	int npages;
655 
656 	if (nkmempages != 0) {
657 		/*
658 		 * It's already been set (by us being here before, or
659 		 * by patching or kernel config options), bail out now.
660 		 */
661 		return;
662 	}
663 
664 	/*
665 	 * We use the following (simple) formula:
666 	 *
667 	 *	- Starting point is physical memory / 4.
668 	 *
669 	 *	- Clamp it down to NKMEMPAGES_MAX.
670 	 *
671 	 *	- Round it up to NKMEMPAGES_MIN.
672 	 */
673 	npages = physmem / 4;
674 
675 	if (npages > NKMEMPAGES_MAX)
676 		npages = NKMEMPAGES_MAX;
677 
678 	if (npages < NKMEMPAGES_MIN)
679 		npages = NKMEMPAGES_MIN;
680 
681 	nkmempages = npages;
682 }
683 
684 /*
685  * Initialize the kernel memory allocator
686  */
687 void
688 kmeminit()
689 {
690 #ifdef KMEMSTATS
691 	long indx;
692 #endif
693 
694 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
695 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
696 #endif
697 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
698 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
699 #endif
700 #if	(MAXALLOCSAVE < NBPG)
701 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
702 #endif
703 
704 	if (sizeof(struct freelist) > (1 << MINBUCKET))
705 		panic("minbucket too small/struct freelist too big");
706 
707 	/*
708 	 * Compute the number of kmem_map pages, if we have not
709 	 * done so already.
710 	 */
711 	kmeminit_nkmempages();
712 
713 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
714 		(vsize_t)(nkmempages * sizeof(struct kmemusage)));
715 	kmem_map = uvm_km_suballoc(kernel_map, (vaddr_t *)&kmembase,
716 		(vaddr_t *)&kmemlimit, (vsize_t)(nkmempages << PAGE_SHIFT),
717 			VM_MAP_INTRSAFE, FALSE, &kmem_map_store);
718 #ifdef KMEMSTATS
719 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
720 		if (1 << indx >= PAGE_SIZE)
721 			bucket[indx].kb_elmpercl = 1;
722 		else
723 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
724 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
725 	}
726 	for (indx = 0; indx < M_LAST; indx++)
727 		kmemstats[indx].ks_limit =
728 		    ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
729 #endif
730 #ifdef MALLOC_DEBUG
731 	debug_malloc_init();
732 #endif
733 }
734 
735 #ifdef DDB
736 #include <ddb/db_output.h>
737 
738 /*
739  * Dump kmem statistics from ddb.
740  *
741  * usage: call dump_kmemstats
742  */
743 void	dump_kmemstats __P((void));
744 
745 void
746 dump_kmemstats()
747 {
748 #ifdef KMEMSTATS
749 	const char *name;
750 	int i;
751 
752 	for (i = 0; i < M_LAST; i++) {
753 		name = memname[i] ? memname[i] : "";
754 
755 		db_printf("%2d %s%.*s %ld\n", i, name,
756 		    (int)(20 - strlen(name)), "                    ",
757 		    kmemstats[i].ks_memuse);
758 	}
759 #else
760 	db_printf("Kmem stats are not being collected.\n");
761 #endif /* KMEMSTATS */
762 }
763 #endif /* DDB */
764