xref: /netbsd-src/sys/kern/kern_malloc.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: kern_malloc.c,v 1.101 2005/12/11 12:24:29 christos 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.101 2005/12/11 12:24:29 christos 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_kernel 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 kmembuckets[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, built-in malloc types and are not
228  * specific to any 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 = &kmembuckets[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_alloc(kmem_map,
311 		    (vsize_t)ctob(npg), 0,
312 		    ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) |
313 		    ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 0) |
314 		    UVM_KMF_WIRED);
315 		if (__predict_false(va == NULL)) {
316 			/*
317 			 * Kmem_malloc() can return NULL, even if it can
318 			 * wait, if there is no map space available, because
319 			 * it can't fix that problem.  Neither can we,
320 			 * right now.  (We should release pages which
321 			 * are completely free and which are in kmembuckets
322 			 * with too many free elements.)
323 			 */
324 			if ((flags & (M_NOWAIT|M_CANFAIL)) == 0)
325 				panic("malloc: out of space in kmem_map");
326 			splx(s);
327 			return (NULL);
328 		}
329 		simple_lock(&malloc_slock);
330 #ifdef KMEMSTATS
331 		kbp->kb_total += kbp->kb_elmpercl;
332 #endif
333 		kup = btokup(va);
334 		kup->ku_indx = indx;
335 		if (allocsize > MAXALLOCSAVE) {
336 			if (npg > 65535)
337 				panic("malloc: allocation too large");
338 			kup->ku_pagecnt = npg;
339 #ifdef KMEMSTATS
340 			ksp->ks_memuse += allocsize;
341 #endif
342 			goto out;
343 		}
344 #ifdef KMEMSTATS
345 		kup->ku_freecnt = kbp->kb_elmpercl;
346 		kbp->kb_totalfree += kbp->kb_elmpercl;
347 #endif
348 		/*
349 		 * Just in case we blocked while allocating memory,
350 		 * and someone else also allocated memory for this
351 		 * kmembucket, don't assume the list is still empty.
352 		 */
353 		savedlist = kbp->kb_next;
354 		kbp->kb_next = cp = va + (npg << PAGE_SHIFT) - allocsize;
355 		for (;;) {
356 			freep = (struct freelist *)cp;
357 #ifdef DIAGNOSTIC
358 			/*
359 			 * Copy in known text to detect modification
360 			 * after freeing.
361 			 */
362 			end = (uint32_t *)&cp[copysize];
363 			for (lp = (uint32_t *)cp; lp < end; lp++)
364 				*lp = WEIRD_ADDR;
365 			freep->type = M_FREE;
366 #endif /* DIAGNOSTIC */
367 			if (cp <= va)
368 				break;
369 			cp -= allocsize;
370 			freep->next = cp;
371 		}
372 		freep->next = savedlist;
373 		if (kbp->kb_last == NULL)
374 			kbp->kb_last = (caddr_t)freep;
375 	}
376 	va = kbp->kb_next;
377 	kbp->kb_next = ((struct freelist *)va)->next;
378 #ifdef DIAGNOSTIC
379 	freep = (struct freelist *)va;
380 	/* XXX potential to get garbage pointer here. */
381 	if (kbp->kb_next) {
382 		int rv;
383 		vaddr_t addr = (vaddr_t)kbp->kb_next;
384 
385 		vm_map_lock(kmem_map);
386 		rv = uvm_map_checkprot(kmem_map, addr,
387 		    addr + sizeof(struct freelist), VM_PROT_WRITE);
388 		vm_map_unlock(kmem_map);
389 
390 		if (__predict_false(rv == 0)) {
391 			printf("Data modified on freelist: "
392 			    "word %ld of object %p size %ld previous type %s "
393 			    "(invalid addr %p)\n",
394 			    (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
395 			    va, size, "foo", kbp->kb_next);
396 #ifdef MALLOCLOG
397 			hitmlog(va);
398 #endif
399 			kbp->kb_next = NULL;
400 		}
401 	}
402 
403 	/* Fill the fields that we've used with WEIRD_ADDR */
404 #ifdef _LP64
405 	freep->type = (struct malloc_type *)
406 	    (WEIRD_ADDR | (((u_long) WEIRD_ADDR) << 32));
407 #else
408 	freep->type = (struct malloc_type *) WEIRD_ADDR;
409 #endif
410 	end = (uint32_t *)&freep->next +
411 	    (sizeof(freep->next) / sizeof(int32_t));
412 	for (lp = (uint32_t *)&freep->next; lp < end; lp++)
413 		*lp = WEIRD_ADDR;
414 
415 	/* and check that the data hasn't been modified. */
416 	end = (uint32_t *)&va[copysize];
417 	for (lp = (uint32_t *)va; lp < end; lp++) {
418 		if (__predict_true(*lp == WEIRD_ADDR))
419 			continue;
420 		printf("Data modified on freelist: "
421 		    "word %ld of object %p size %ld previous type %s "
422 		    "(0x%x != 0x%x)\n",
423 		    (long)(lp - (uint32_t *)va), va, size,
424 		    "bar", *lp, WEIRD_ADDR);
425 #ifdef MALLOCLOG
426 		hitmlog(va);
427 #endif
428 		break;
429 	}
430 
431 	freep->spare0 = 0;
432 #endif /* DIAGNOSTIC */
433 #ifdef KMEMSTATS
434 	kup = btokup(va);
435 	if (kup->ku_indx != indx)
436 		panic("malloc: wrong bucket");
437 	if (kup->ku_freecnt == 0)
438 		panic("malloc: lost data");
439 	kup->ku_freecnt--;
440 	kbp->kb_totalfree--;
441 	ksp->ks_memuse += 1 << indx;
442 out:
443 	kbp->kb_calls++;
444 	ksp->ks_inuse++;
445 	ksp->ks_calls++;
446 	if (ksp->ks_memuse > ksp->ks_maxused)
447 		ksp->ks_maxused = ksp->ks_memuse;
448 #else
449 out:
450 #endif
451 #ifdef MALLOCLOG
452 	domlog(va, size, ksp, 1, file, line);
453 #endif
454 	simple_unlock(&malloc_slock);
455 	splx(s);
456 	if ((flags & M_ZERO) != 0)
457 		memset(va, 0, size);
458 	return ((void *) va);
459 }
460 
461 /*
462  * Free a block of memory allocated by malloc.
463  */
464 #ifdef MALLOCLOG
465 void
466 _free(void *addr, struct malloc_type *ksp, const char *file, long line)
467 #else
468 void
469 free(void *addr, struct malloc_type *ksp)
470 #endif /* MALLOCLOG */
471 {
472 	struct kmembuckets *kbp;
473 	struct kmemusage *kup;
474 	struct freelist *freep;
475 	long size;
476 	int s;
477 #ifdef DIAGNOSTIC
478 	caddr_t cp;
479 	int32_t *end, *lp;
480 	long alloc, copysize;
481 #endif
482 
483 #ifdef MALLOC_DEBUG
484 	if (debug_free(addr, ksp))
485 		return;
486 #endif
487 
488 #ifdef DIAGNOSTIC
489 	/*
490 	 * Ensure that we're free'ing something that we could
491 	 * have allocated in the first place.  That is, check
492 	 * to see that the address is within kmem_map.
493 	 */
494 	if (__predict_false((vaddr_t)addr < vm_map_min(kmem_map) ||
495 	    (vaddr_t)addr >= vm_map_max(kmem_map)))
496 		panic("free: addr %p not within kmem_map", addr);
497 #endif
498 
499 	kup = btokup(addr);
500 	size = 1 << kup->ku_indx;
501 	kbp = &kmembuckets[kup->ku_indx];
502 	s = splvm();
503 	simple_lock(&malloc_slock);
504 #ifdef MALLOCLOG
505 	domlog(addr, 0, ksp, 2, file, line);
506 #endif
507 #ifdef DIAGNOSTIC
508 	/*
509 	 * Check for returns of data that do not point to the
510 	 * beginning of the allocation.
511 	 */
512 	if (size > PAGE_SIZE)
513 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
514 	else
515 		alloc = addrmask[kup->ku_indx];
516 	if (((u_long)addr & alloc) != 0)
517 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
518 		    addr, size, ksp->ks_shortdesc, alloc);
519 #endif /* DIAGNOSTIC */
520 	if (size > MAXALLOCSAVE) {
521 		uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt),
522 		    UVM_KMF_WIRED);
523 #ifdef KMEMSTATS
524 		size = kup->ku_pagecnt << PGSHIFT;
525 		ksp->ks_memuse -= size;
526 		kup->ku_indx = 0;
527 		kup->ku_pagecnt = 0;
528 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
529 		    ksp->ks_memuse < ksp->ks_limit)
530 			wakeup((caddr_t)ksp);
531 #ifdef DIAGNOSTIC
532 		if (ksp->ks_inuse == 0)
533 			panic("free 1: inuse 0, probable double free");
534 #endif
535 		ksp->ks_inuse--;
536 		kbp->kb_total -= 1;
537 #endif
538 		simple_unlock(&malloc_slock);
539 		splx(s);
540 		return;
541 	}
542 	freep = (struct freelist *)addr;
543 #ifdef DIAGNOSTIC
544 	/*
545 	 * Check for multiple frees. Use a quick check to see if
546 	 * it looks free before laboriously searching the freelist.
547 	 */
548 	if (__predict_false(freep->spare0 == WEIRD_ADDR)) {
549 		for (cp = kbp->kb_next; cp;
550 		    cp = ((struct freelist *)cp)->next) {
551 			if (addr != cp)
552 				continue;
553 			printf("multiply freed item %p\n", addr);
554 #ifdef MALLOCLOG
555 			hitmlog(addr);
556 #endif
557 			panic("free: duplicated free");
558 		}
559 	}
560 #ifdef LOCKDEBUG
561 	/*
562 	 * Check if we're freeing a locked simple lock.
563 	 */
564 	simple_lock_freecheck(addr, (char *)addr + size);
565 #endif
566 	/*
567 	 * Copy in known text to detect modification after freeing
568 	 * and to make it look free. Also, save the type being freed
569 	 * so we can list likely culprit if modification is detected
570 	 * when the object is reallocated.
571 	 */
572 	copysize = size < MAX_COPY ? size : MAX_COPY;
573 	end = (int32_t *)&((caddr_t)addr)[copysize];
574 	for (lp = (int32_t *)addr; lp < end; lp++)
575 		*lp = WEIRD_ADDR;
576 	freep->type = ksp;
577 #endif /* DIAGNOSTIC */
578 #ifdef KMEMSTATS
579 	kup->ku_freecnt++;
580 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
581 		if (kup->ku_freecnt > kbp->kb_elmpercl)
582 			panic("free: multiple frees");
583 		else if (kbp->kb_totalfree > kbp->kb_highwat)
584 			kbp->kb_couldfree++;
585 	}
586 	kbp->kb_totalfree++;
587 	ksp->ks_memuse -= size;
588 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
589 	    ksp->ks_memuse < ksp->ks_limit)
590 		wakeup((caddr_t)ksp);
591 #ifdef DIAGNOSTIC
592 	if (ksp->ks_inuse == 0)
593 		panic("free 2: inuse 0, probable double free");
594 #endif
595 	ksp->ks_inuse--;
596 #endif
597 	if (kbp->kb_next == NULL)
598 		kbp->kb_next = addr;
599 	else
600 		((struct freelist *)kbp->kb_last)->next = addr;
601 	freep->next = NULL;
602 	kbp->kb_last = addr;
603 	simple_unlock(&malloc_slock);
604 	splx(s);
605 }
606 
607 /*
608  * Change the size of a block of memory.
609  */
610 void *
611 realloc(void *curaddr, unsigned long newsize, struct malloc_type *ksp,
612     int flags)
613 {
614 	struct kmemusage *kup;
615 	unsigned long cursize;
616 	void *newaddr;
617 #ifdef DIAGNOSTIC
618 	long alloc;
619 #endif
620 
621 	/*
622 	 * realloc() with a NULL pointer is the same as malloc().
623 	 */
624 	if (curaddr == NULL)
625 		return (malloc(newsize, ksp, flags));
626 
627 	/*
628 	 * realloc() with zero size is the same as free().
629 	 */
630 	if (newsize == 0) {
631 		free(curaddr, ksp);
632 		return (NULL);
633 	}
634 
635 #ifdef LOCKDEBUG
636 	if ((flags & M_NOWAIT) == 0)
637 		simple_lock_only_held(NULL, "realloc");
638 #endif
639 
640 	/*
641 	 * Find out how large the old allocation was (and do some
642 	 * sanity checking).
643 	 */
644 	kup = btokup(curaddr);
645 	cursize = 1 << kup->ku_indx;
646 
647 #ifdef DIAGNOSTIC
648 	/*
649 	 * Check for returns of data that do not point to the
650 	 * beginning of the allocation.
651 	 */
652 	if (cursize > PAGE_SIZE)
653 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
654 	else
655 		alloc = addrmask[kup->ku_indx];
656 	if (((u_long)curaddr & alloc) != 0)
657 		panic("realloc: "
658 		    "unaligned addr %p, size %ld, type %s, mask %ld\n",
659 		    curaddr, cursize, ksp->ks_shortdesc, alloc);
660 #endif /* DIAGNOSTIC */
661 
662 	if (cursize > MAXALLOCSAVE)
663 		cursize = ctob(kup->ku_pagecnt);
664 
665 	/*
666 	 * If we already actually have as much as they want, we're done.
667 	 */
668 	if (newsize <= cursize)
669 		return (curaddr);
670 
671 	/*
672 	 * Can't satisfy the allocation with the existing block.
673 	 * Allocate a new one and copy the data.
674 	 */
675 	newaddr = malloc(newsize, ksp, flags);
676 	if (__predict_false(newaddr == NULL)) {
677 		/*
678 		 * malloc() failed, because flags included M_NOWAIT.
679 		 * Return NULL to indicate that failure.  The old
680 		 * pointer is still valid.
681 		 */
682 		return (NULL);
683 	}
684 	memcpy(newaddr, curaddr, cursize);
685 
686 	/*
687 	 * We were successful: free the old allocation and return
688 	 * the new one.
689 	 */
690 	free(curaddr, ksp);
691 	return (newaddr);
692 }
693 
694 /*
695  * Roundup size to the actual allocation size.
696  */
697 unsigned long
698 malloc_roundup(unsigned long size)
699 {
700 
701 	if (size > MAXALLOCSAVE)
702 		return (roundup(size, PAGE_SIZE));
703 	else
704 		return (1 << BUCKETINDX(size));
705 }
706 
707 /*
708  * Add a malloc type to the system.
709  */
710 void
711 malloc_type_attach(struct malloc_type *type)
712 {
713 
714 	if (nkmempages == 0)
715 		panic("malloc_type_attach: nkmempages == 0");
716 
717 	if (type->ks_magic != M_MAGIC)
718 		panic("malloc_type_attach: bad magic");
719 
720 #ifdef DIAGNOSTIC
721 	{
722 		struct malloc_type *ksp;
723 		for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
724 			if (ksp == type)
725 				panic("malloc_type_attach: already on list");
726 		}
727 	}
728 #endif
729 
730 #ifdef KMEMSTATS
731 	if (type->ks_limit == 0)
732 		type->ks_limit = ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
733 #else
734 	type->ks_limit = 0;
735 #endif
736 
737 	type->ks_next = kmemstatistics;
738 	kmemstatistics = type;
739 }
740 
741 /*
742  * Remove a malloc type from the system..
743  */
744 void
745 malloc_type_detach(struct malloc_type *type)
746 {
747 	struct malloc_type *ksp;
748 
749 #ifdef DIAGNOSTIC
750 	if (type->ks_magic != M_MAGIC)
751 		panic("malloc_type_detach: bad magic");
752 #endif
753 
754 	if (type == kmemstatistics)
755 		kmemstatistics = type->ks_next;
756 	else {
757 		for (ksp = kmemstatistics; ksp->ks_next != NULL;
758 		     ksp = ksp->ks_next) {
759 			if (ksp->ks_next == type) {
760 				ksp->ks_next = type->ks_next;
761 				break;
762 			}
763 		}
764 #ifdef DIAGNOSTIC
765 		if (ksp->ks_next == NULL)
766 			panic("malloc_type_detach: not on list");
767 #endif
768 	}
769 	type->ks_next = NULL;
770 }
771 
772 /*
773  * Set the limit on a malloc type.
774  */
775 void
776 malloc_type_setlimit(struct malloc_type *type, u_long limit)
777 {
778 #ifdef KMEMSTATS
779 	int s;
780 
781 	s = splvm();
782 	type->ks_limit = limit;
783 	splx(s);
784 #endif
785 }
786 
787 /*
788  * Compute the number of pages that kmem_map will map, that is,
789  * the size of the kernel malloc arena.
790  */
791 void
792 kmeminit_nkmempages(void)
793 {
794 	int npages;
795 
796 	if (nkmempages != 0) {
797 		/*
798 		 * It's already been set (by us being here before, or
799 		 * by patching or kernel config options), bail out now.
800 		 */
801 		return;
802 	}
803 
804 	npages = physmem;
805 
806 	if (npages > NKMEMPAGES_MAX)
807 		npages = NKMEMPAGES_MAX;
808 
809 	if (npages < NKMEMPAGES_MIN)
810 		npages = NKMEMPAGES_MIN;
811 
812 	nkmempages = npages;
813 }
814 
815 /*
816  * Initialize the kernel memory allocator
817  */
818 void
819 kmeminit(void)
820 {
821 	__link_set_decl(malloc_types, struct malloc_type);
822 	struct malloc_type * const *ksp;
823 	vaddr_t kmb, kml;
824 #ifdef KMEMSTATS
825 	long indx;
826 #endif
827 
828 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
829 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
830 #endif
831 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
832 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
833 #endif
834 #if	(MAXALLOCSAVE < NBPG)
835 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
836 #endif
837 
838 	if (sizeof(struct freelist) > (1 << MINBUCKET))
839 		panic("minbucket too small/struct freelist too big");
840 
841 	/*
842 	 * Compute the number of kmem_map pages, if we have not
843 	 * done so already.
844 	 */
845 	kmeminit_nkmempages();
846 
847 	kmemusage = (struct kmemusage *) uvm_km_alloc(kernel_map,
848 	    (vsize_t)(nkmempages * sizeof(struct kmemusage)), 0,
849 	    UVM_KMF_WIRED|UVM_KMF_ZERO);
850 	kmb = 0;
851 	kmem_map = uvm_km_suballoc(kernel_map, &kmb,
852 	    &kml, ((vsize_t)nkmempages << PAGE_SHIFT),
853 	    VM_MAP_INTRSAFE, FALSE, &kmem_map_store);
854 	uvm_km_vacache_init(kmem_map, "kvakmem", 0);
855 	kmembase = (char *)kmb;
856 	kmemlimit = (char *)kml;
857 #ifdef KMEMSTATS
858 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
859 		if (1 << indx >= PAGE_SIZE)
860 			kmembuckets[indx].kb_elmpercl = 1;
861 		else
862 			kmembuckets[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
863 		kmembuckets[indx].kb_highwat =
864 			5 * kmembuckets[indx].kb_elmpercl;
865 	}
866 #endif
867 
868 	/* Attach all of the statically-linked malloc types. */
869 	__link_set_foreach(ksp, malloc_types)
870 		malloc_type_attach(*ksp);
871 
872 #ifdef MALLOC_DEBUG
873 	debug_malloc_init();
874 #endif
875 }
876 
877 #ifdef DDB
878 #include <ddb/db_output.h>
879 
880 /*
881  * Dump kmem statistics from ddb.
882  *
883  * usage: call dump_kmemstats
884  */
885 void	dump_kmemstats(void);
886 
887 void
888 dump_kmemstats(void)
889 {
890 #ifdef KMEMSTATS
891 	struct malloc_type *ksp;
892 
893 	for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
894 		if (ksp->ks_memuse == 0)
895 			continue;
896 		db_printf("%s%.*s %ld\n", ksp->ks_shortdesc,
897 		    (int)(20 - strlen(ksp->ks_shortdesc)),
898 		    "                    ",
899 		    ksp->ks_memuse);
900 	}
901 #else
902 	db_printf("Kmem stats are not being collected.\n");
903 #endif /* KMEMSTATS */
904 }
905 #endif /* DDB */
906 
907 
908 #if 0
909 /*
910  * Diagnostic messages about "Data modified on
911  * freelist" indicate a memory corruption, but
912  * they do not help tracking it down.
913  * This function can be called at various places
914  * to sanity check malloc's freelist and discover
915  * where does the corruption take place.
916  */
917 int
918 freelist_sanitycheck(void) {
919 	int i,j;
920 	struct kmembuckets *kbp;
921 	struct freelist *freep;
922 	int rv = 0;
923 
924 	for (i = MINBUCKET; i <= MINBUCKET + 15; i++) {
925 		kbp = &kmembuckets[i];
926 		freep = (struct freelist *)kbp->kb_next;
927 		j = 0;
928 		while(freep) {
929 			vm_map_lock(kmem_map);
930 			rv = uvm_map_checkprot(kmem_map, (vaddr_t)freep,
931 			    (vaddr_t)freep + sizeof(struct freelist),
932 			    VM_PROT_WRITE);
933 			vm_map_unlock(kmem_map);
934 
935 			if ((rv == 0) || (*(int *)freep != WEIRD_ADDR)) {
936 				printf("bucket %i, chunck %d at %p modified\n",
937 				    i, j, freep);
938 				return 1;
939 			}
940 			freep = (struct freelist *)freep->next;
941 			j++;
942 		}
943 	}
944 
945 	return 0;
946 }
947 #endif
948