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