xref: /netbsd-src/sys/kern/kern_malloc.c (revision 1ffa7b76c40339c17a0fb2a09fac93f287cfc046)
1 /*	$NetBSD: kern_malloc.c,v 1.78 2003/02/14 21:51:36 pk 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.78 2003/02/14 21:51:36 pk 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 kmemusage *kmemusage;
89 char *kmembase, *kmemlimit;
90 
91 struct malloc_type *kmemstatistics;
92 
93 #ifdef MALLOCLOG
94 #ifndef MALLOCLOGSIZE
95 #define	MALLOCLOGSIZE	100000
96 #endif
97 
98 struct malloclog {
99 	void *addr;
100 	long size;
101 	struct malloc_type *type;
102 	int action;
103 	const char *file;
104 	long line;
105 } malloclog[MALLOCLOGSIZE];
106 
107 long	malloclogptr;
108 
109 static void
110 domlog(void *a, long size, struct malloc_type *type, int action,
111     const char *file, long line)
112 {
113 
114 	malloclog[malloclogptr].addr = a;
115 	malloclog[malloclogptr].size = size;
116 	malloclog[malloclogptr].type = type;
117 	malloclog[malloclogptr].action = action;
118 	malloclog[malloclogptr].file = file;
119 	malloclog[malloclogptr].line = line;
120 	malloclogptr++;
121 	if (malloclogptr >= MALLOCLOGSIZE)
122 		malloclogptr = 0;
123 }
124 
125 static void
126 hitmlog(void *a)
127 {
128 	struct malloclog *lp;
129 	long l;
130 
131 #define	PRT do { \
132 	if (malloclog[l].addr == a && malloclog[l].action) { \
133 		lp = &malloclog[l]; \
134 		printf("malloc log entry %ld:\n", l); \
135 		printf("\taddr = %p\n", lp->addr); \
136 		printf("\tsize = %ld\n", lp->size); \
137 		printf("\ttype = %s\n", lp->type->ks_shortdesc); \
138 		printf("\taction = %s\n", lp->action == 1 ? "alloc" : "free"); \
139 		printf("\tfile = %s\n", lp->file); \
140 		printf("\tline = %ld\n", lp->line); \
141 	} \
142 } while (/* CONSTCOND */0)
143 
144 	for (l = malloclogptr; l < MALLOCLOGSIZE; l++)
145 		PRT;
146 
147 	for (l = 0; l < malloclogptr; l++)
148 		PRT;
149 }
150 #endif /* MALLOCLOG */
151 
152 #ifdef DIAGNOSTIC
153 /*
154  * This structure provides a set of masks to catch unaligned frees.
155  */
156 const long addrmask[] = { 0,
157 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
158 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
159 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
160 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
161 };
162 
163 /*
164  * The WEIRD_ADDR is used as known text to copy into free objects so
165  * that modifications after frees can be detected.
166  */
167 #define	WEIRD_ADDR	((uint32_t) 0xdeadbeef)
168 #ifdef DEBUG
169 #define	MAX_COPY	PAGE_SIZE
170 #else
171 #define	MAX_COPY	32
172 #endif
173 
174 /*
175  * Normally the freelist structure is used only to hold the list pointer
176  * for free objects.  However, when running with diagnostics, the first
177  * 8/16 bytes of the structure is unused except for diagnostic information,
178  * and the free list pointer is at offset 8/16 in the structure.  Since the
179  * first 8 bytes is the portion of the structure most often modified, this
180  * helps to detect memory reuse problems and avoid free list corruption.
181  */
182 struct freelist {
183 	uint32_t spare0;
184 #ifdef _LP64
185 	uint32_t spare1;		/* explicit padding */
186 #endif
187 	struct malloc_type *type;
188 	caddr_t	next;
189 };
190 #else /* !DIAGNOSTIC */
191 struct freelist {
192 	caddr_t	next;
193 };
194 #endif /* DIAGNOSTIC */
195 
196 /*
197  * The following are standard, build-in malloc types are are not
198  * specific to any one subsystem.
199  */
200 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
201 MALLOC_DEFINE(M_DMAMAP, "DMA map", "bus_dma(9) structures");
202 MALLOC_DEFINE(M_FREE, "free", "should be on free list");
203 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
204 MALLOC_DEFINE(M_SOFTINTR, "softintr", "Softinterrupt structures");
205 MALLOC_DEFINE(M_TEMP, "temp", "misc. temporary data buffers");
206 
207 /* XXX These should all be elsewhere. */
208 MALLOC_DEFINE(M_RTABLE, "routetbl", "routing tables");
209 MALLOC_DEFINE(M_FTABLE, "fragtbl", "fragment reassembly header");
210 MALLOC_DEFINE(M_UFSMNT, "UFS mount", "UFS mount structure");
211 MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
212 MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
213 MALLOC_DEFINE(M_IPMADDR, "in_multi", "internet multicast address");
214 MALLOC_DEFINE(M_MRTABLE, "mrt", "multicast routing tables");
215 MALLOC_DEFINE(M_1394DATA, "1394data", "IEEE 1394 data buffers");
216 
217 struct simplelock malloc_slock = SIMPLELOCK_INITIALIZER;
218 
219 /*
220  * Allocate a block of memory
221  */
222 #ifdef MALLOCLOG
223 void *
224 _malloc(unsigned long size, struct malloc_type *ksp, int flags,
225     const char *file, long line)
226 #else
227 void *
228 malloc(unsigned long size, struct malloc_type *ksp, int flags)
229 #endif /* MALLOCLOG */
230 {
231 	struct kmembuckets *kbp;
232 	struct kmemusage *kup;
233 	struct freelist *freep;
234 	long indx, npg, allocsize;
235 	int s;
236 	caddr_t va, cp, savedlist;
237 #ifdef DIAGNOSTIC
238 	uint32_t *end, *lp;
239 	int copysize;
240 	const char *savedtype;
241 #endif
242 
243 #ifdef LOCKDEBUG
244 	if ((flags & M_NOWAIT) == 0)
245 		simple_lock_only_held(NULL, "malloc");
246 #endif
247 #ifdef MALLOC_DEBUG
248 	if (debug_malloc(size, ksp, flags, (void **) &va))
249 		return ((void *) va);
250 #endif
251 	indx = BUCKETINDX(size);
252 	kbp = &bucket[indx];
253 	s = splvm();
254 	simple_lock(&malloc_slock);
255 #ifdef KMEMSTATS
256 	while (ksp->ks_memuse >= ksp->ks_limit) {
257 		if (flags & M_NOWAIT) {
258 			simple_unlock(&malloc_slock);
259 			splx(s);
260 			return ((void *) NULL);
261 		}
262 		if (ksp->ks_limblocks < 65535)
263 			ksp->ks_limblocks++;
264 		ltsleep((caddr_t)ksp, PSWP+2, ksp->ks_shortdesc, 0,
265 			&malloc_slock);
266 	}
267 	ksp->ks_size |= 1 << indx;
268 #endif
269 #ifdef DIAGNOSTIC
270 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
271 #endif
272 	if (kbp->kb_next == NULL) {
273 		kbp->kb_last = NULL;
274 		if (size > MAXALLOCSAVE)
275 			allocsize = round_page(size);
276 		else
277 			allocsize = 1 << indx;
278 		npg = btoc(allocsize);
279 		simple_unlock(&malloc_slock);
280 		va = (caddr_t) uvm_km_kmemalloc(kmem_map, NULL,
281 		    (vsize_t)ctob(npg),
282 		    ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) |
283 		    ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 0));
284 		if (__predict_false(va == NULL)) {
285 			/*
286 			 * Kmem_malloc() can return NULL, even if it can
287 			 * wait, if there is no map space avaiable, because
288 			 * it can't fix that problem.  Neither can we,
289 			 * right now.  (We should release pages which
290 			 * are completely free and which are in buckets
291 			 * with too many free elements.)
292 			 */
293 			if ((flags & (M_NOWAIT|M_CANFAIL)) == 0)
294 				panic("malloc: out of space in kmem_map");
295 			splx(s);
296 			return (NULL);
297 		}
298 		simple_lock(&malloc_slock);
299 #ifdef KMEMSTATS
300 		kbp->kb_total += kbp->kb_elmpercl;
301 #endif
302 		kup = btokup(va);
303 		kup->ku_indx = indx;
304 		if (allocsize > MAXALLOCSAVE) {
305 			if (npg > 65535)
306 				panic("malloc: allocation too large");
307 			kup->ku_pagecnt = npg;
308 #ifdef KMEMSTATS
309 			ksp->ks_memuse += allocsize;
310 #endif
311 			goto out;
312 		}
313 #ifdef KMEMSTATS
314 		kup->ku_freecnt = kbp->kb_elmpercl;
315 		kbp->kb_totalfree += kbp->kb_elmpercl;
316 #endif
317 		/*
318 		 * Just in case we blocked while allocating memory,
319 		 * and someone else also allocated memory for this
320 		 * bucket, don't assume the list is still empty.
321 		 */
322 		savedlist = kbp->kb_next;
323 		kbp->kb_next = cp = va + (npg << PAGE_SHIFT) - allocsize;
324 		for (;;) {
325 			freep = (struct freelist *)cp;
326 #ifdef DIAGNOSTIC
327 			/*
328 			 * Copy in known text to detect modification
329 			 * after freeing.
330 			 */
331 			end = (int32_t *)&cp[copysize];
332 			for (lp = (int32_t *)cp; lp < end; lp++)
333 				*lp = WEIRD_ADDR;
334 			freep->type = M_FREE;
335 #endif /* DIAGNOSTIC */
336 			if (cp <= va)
337 				break;
338 			cp -= allocsize;
339 			freep->next = cp;
340 		}
341 		freep->next = savedlist;
342 		if (kbp->kb_last == NULL)
343 			kbp->kb_last = (caddr_t)freep;
344 	}
345 	va = kbp->kb_next;
346 	kbp->kb_next = ((struct freelist *)va)->next;
347 #ifdef DIAGNOSTIC
348 	freep = (struct freelist *)va;
349 	/* XXX potential to get garbage pointer here. */
350 	savedtype = freep->type->ks_shortdesc;
351 	if (kbp->kb_next) {
352 		int rv;
353 		vaddr_t addr = (vaddr_t)kbp->kb_next;
354 
355 		vm_map_lock(kmem_map);
356 		rv = uvm_map_checkprot(kmem_map, addr,
357 		    addr + sizeof(struct freelist), VM_PROT_WRITE);
358 		vm_map_unlock(kmem_map);
359 
360 		if (__predict_false(rv == 0)) {
361 			printf("Data modified on freelist: "
362 			    "word %ld of object %p size %ld previous type %s "
363 			    "(invalid addr %p)\n",
364 			    (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
365 			    va, size, savedtype, kbp->kb_next);
366 #ifdef MALLOCLOG
367 			hitmlog(va);
368 #endif
369 			kbp->kb_next = NULL;
370 		}
371 	}
372 
373 	/* Fill the fields that we've used with WEIRD_ADDR */
374 #ifdef _LP64
375 	freep->type = (struct malloc_type *)
376 	    (WEIRD_ADDR | (((u_long) WEIRD_ADDR) << 32));
377 #else
378 	freep->type = (struct malloc_type *) WEIRD_ADDR;
379 #endif
380 	end = (int32_t *)&freep->next +
381 	    (sizeof(freep->next) / sizeof(int32_t));
382 	for (lp = (int32_t *)&freep->next; lp < end; lp++)
383 		*lp = WEIRD_ADDR;
384 
385 	/* and check that the data hasn't been modified. */
386 	end = (uint32_t *)&va[copysize];
387 	for (lp = (int32_t *)va; lp < end; lp++) {
388 		if (__predict_true(*lp == WEIRD_ADDR))
389 			continue;
390 		printf("Data modified on freelist: "
391 		    "word %ld of object %p size %ld previous type %s "
392 		    "(0x%x != 0x%x)\n",
393 		    (long)(lp - (uint32_t *)va), va, size,
394 		    savedtype, *lp, WEIRD_ADDR);
395 #ifdef MALLOCLOG
396 		hitmlog(va);
397 #endif
398 		break;
399 	}
400 
401 	freep->spare0 = 0;
402 #endif /* DIAGNOSTIC */
403 #ifdef KMEMSTATS
404 	kup = btokup(va);
405 	if (kup->ku_indx != indx)
406 		panic("malloc: wrong bucket");
407 	if (kup->ku_freecnt == 0)
408 		panic("malloc: lost data");
409 	kup->ku_freecnt--;
410 	kbp->kb_totalfree--;
411 	ksp->ks_memuse += 1 << indx;
412 out:
413 	kbp->kb_calls++;
414 	ksp->ks_inuse++;
415 	ksp->ks_calls++;
416 	if (ksp->ks_memuse > ksp->ks_maxused)
417 		ksp->ks_maxused = ksp->ks_memuse;
418 #else
419 out:
420 #endif
421 #ifdef MALLOCLOG
422 	domlog(va, size, type, 1, file, line);
423 #endif
424 	simple_unlock(&malloc_slock);
425 	splx(s);
426 	if ((flags & M_ZERO) != 0)
427 		memset(va, 0, size);
428 	return ((void *) va);
429 }
430 
431 /*
432  * Free a block of memory allocated by malloc.
433  */
434 #ifdef MALLOCLOG
435 void
436 _free(void *addr, struct malloc_type *type, const char *file, long line)
437 #else
438 void
439 free(void *addr, struct malloc_type *ksp)
440 #endif /* MALLOCLOG */
441 {
442 	struct kmembuckets *kbp;
443 	struct kmemusage *kup;
444 	struct freelist *freep;
445 	long size;
446 	int s;
447 #ifdef DIAGNOSTIC
448 	caddr_t cp;
449 	int32_t *end, *lp;
450 	long alloc, copysize;
451 #endif
452 
453 #ifdef MALLOC_DEBUG
454 	if (debug_free(addr, ksp))
455 		return;
456 #endif
457 
458 #ifdef DIAGNOSTIC
459 	/*
460 	 * Ensure that we're free'ing something that we could
461 	 * have allocated in the first place.  That is, check
462 	 * to see that the address is within kmem_map.
463 	 */
464 	if (__predict_false((vaddr_t)addr < kmem_map->header.start ||
465 	    (vaddr_t)addr >= kmem_map->header.end))
466 		panic("free: addr %p not within kmem_map", addr);
467 #endif
468 
469 	kup = btokup(addr);
470 	size = 1 << kup->ku_indx;
471 	kbp = &bucket[kup->ku_indx];
472 	s = splvm();
473 	simple_lock(&malloc_slock);
474 #ifdef MALLOCLOG
475 	domlog(addr, 0, type, 2, file, line);
476 #endif
477 #ifdef DIAGNOSTIC
478 	/*
479 	 * Check for returns of data that do not point to the
480 	 * beginning of the allocation.
481 	 */
482 	if (size > PAGE_SIZE)
483 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
484 	else
485 		alloc = addrmask[kup->ku_indx];
486 	if (((u_long)addr & alloc) != 0)
487 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
488 		    addr, size, ksp->ks_shortdesc, alloc);
489 #endif /* DIAGNOSTIC */
490 	if (size > MAXALLOCSAVE) {
491 		uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
492 #ifdef KMEMSTATS
493 		size = kup->ku_pagecnt << PGSHIFT;
494 		ksp->ks_memuse -= size;
495 		kup->ku_indx = 0;
496 		kup->ku_pagecnt = 0;
497 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
498 		    ksp->ks_memuse < ksp->ks_limit)
499 			wakeup((caddr_t)ksp);
500 		ksp->ks_inuse--;
501 		kbp->kb_total -= 1;
502 #endif
503 		simple_unlock(&malloc_slock);
504 		splx(s);
505 		return;
506 	}
507 	freep = (struct freelist *)addr;
508 #ifdef DIAGNOSTIC
509 	/*
510 	 * Check for multiple frees. Use a quick check to see if
511 	 * it looks free before laboriously searching the freelist.
512 	 */
513 	if (__predict_false(freep->spare0 == WEIRD_ADDR)) {
514 		for (cp = kbp->kb_next; cp;
515 		    cp = ((struct freelist *)cp)->next) {
516 			if (addr != cp)
517 				continue;
518 			printf("multiply freed item %p\n", addr);
519 #ifdef MALLOCLOG
520 			hitmlog(addr);
521 #endif
522 			panic("free: duplicated free");
523 		}
524 	}
525 #ifdef LOCKDEBUG
526 	/*
527 	 * Check if we're freeing a locked simple lock.
528 	 */
529 	simple_lock_freecheck(addr, (char *)addr + size);
530 #endif
531 	/*
532 	 * Copy in known text to detect modification after freeing
533 	 * and to make it look free. Also, save the type being freed
534 	 * so we can list likely culprit if modification is detected
535 	 * when the object is reallocated.
536 	 */
537 	copysize = size < MAX_COPY ? size : MAX_COPY;
538 	end = (int32_t *)&((caddr_t)addr)[copysize];
539 	for (lp = (int32_t *)addr; lp < end; lp++)
540 		*lp = WEIRD_ADDR;
541 	freep->type = ksp;
542 #endif /* DIAGNOSTIC */
543 #ifdef KMEMSTATS
544 	kup->ku_freecnt++;
545 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
546 		if (kup->ku_freecnt > kbp->kb_elmpercl)
547 			panic("free: multiple frees");
548 		else if (kbp->kb_totalfree > kbp->kb_highwat)
549 			kbp->kb_couldfree++;
550 	}
551 	kbp->kb_totalfree++;
552 	ksp->ks_memuse -= size;
553 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
554 	    ksp->ks_memuse < ksp->ks_limit)
555 		wakeup((caddr_t)ksp);
556 	ksp->ks_inuse--;
557 #endif
558 	if (kbp->kb_next == NULL)
559 		kbp->kb_next = addr;
560 	else
561 		((struct freelist *)kbp->kb_last)->next = addr;
562 	freep->next = NULL;
563 	kbp->kb_last = addr;
564 	simple_unlock(&malloc_slock);
565 	splx(s);
566 }
567 
568 /*
569  * Change the size of a block of memory.
570  */
571 void *
572 realloc(void *curaddr, unsigned long newsize, struct malloc_type *ksp,
573     int flags)
574 {
575 	struct kmemusage *kup;
576 	unsigned long cursize;
577 	void *newaddr;
578 #ifdef DIAGNOSTIC
579 	long alloc;
580 #endif
581 
582 	/*
583 	 * realloc() with a NULL pointer is the same as malloc().
584 	 */
585 	if (curaddr == NULL)
586 		return (malloc(newsize, ksp, flags));
587 
588 	/*
589 	 * realloc() with zero size is the same as free().
590 	 */
591 	if (newsize == 0) {
592 		free(curaddr, ksp);
593 		return (NULL);
594 	}
595 
596 #ifdef LOCKDEBUG
597 	if ((flags & M_NOWAIT) == 0)
598 		simple_lock_only_held(NULL, "realloc");
599 #endif
600 
601 	/*
602 	 * Find out how large the old allocation was (and do some
603 	 * sanity checking).
604 	 */
605 	kup = btokup(curaddr);
606 	cursize = 1 << kup->ku_indx;
607 
608 #ifdef DIAGNOSTIC
609 	/*
610 	 * Check for returns of data that do not point to the
611 	 * beginning of the allocation.
612 	 */
613 	if (cursize > PAGE_SIZE)
614 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
615 	else
616 		alloc = addrmask[kup->ku_indx];
617 	if (((u_long)curaddr & alloc) != 0)
618 		panic("realloc: "
619 		    "unaligned addr %p, size %ld, type %s, mask %ld\n",
620 		    curaddr, cursize, ksp->ks_shortdesc, alloc);
621 #endif /* DIAGNOSTIC */
622 
623 	if (cursize > MAXALLOCSAVE)
624 		cursize = ctob(kup->ku_pagecnt);
625 
626 	/*
627 	 * If we already actually have as much as they want, we're done.
628 	 */
629 	if (newsize <= cursize)
630 		return (curaddr);
631 
632 	/*
633 	 * Can't satisfy the allocation with the existing block.
634 	 * Allocate a new one and copy the data.
635 	 */
636 	newaddr = malloc(newsize, ksp, flags);
637 	if (__predict_false(newaddr == NULL)) {
638 		/*
639 		 * malloc() failed, because flags included M_NOWAIT.
640 		 * Return NULL to indicate that failure.  The old
641 		 * pointer is still valid.
642 		 */
643 		return (NULL);
644 	}
645 	memcpy(newaddr, curaddr, cursize);
646 
647 	/*
648 	 * We were successful: free the old allocation and return
649 	 * the new one.
650 	 */
651 	free(curaddr, ksp);
652 	return (newaddr);
653 }
654 
655 /*
656  * Roundup size to the actual allocation size.
657  */
658 unsigned long
659 malloc_roundup(unsigned long size)
660 {
661 
662 	if (size > MAXALLOCSAVE)
663 		return (roundup(size, PAGE_SIZE));
664 	else
665 		return (1 << BUCKETINDX(size));
666 }
667 
668 /*
669  * Add a malloc type to the system.
670  */
671 void
672 malloc_type_attach(struct malloc_type *type)
673 {
674 
675 	if (nkmempages == 0)
676 		panic("malloc_type_attach: nkmempages == 0");
677 
678 	if (type->ks_magic != M_MAGIC)
679 		panic("malloc_type_attach: bad magic");
680 
681 #ifdef DIAGNOSTIC
682 	{
683 		struct malloc_type *ksp;
684 		for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
685 			if (ksp == type)
686 				panic("malloc_type_attach: already on list");
687 		}
688 	}
689 #endif
690 
691 #ifdef KMEMSTATS
692 	if (type->ks_limit == 0)
693 		type->ks_limit = ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
694 #else
695 	type->ks_limit = 0;
696 #endif
697 
698 	type->ks_next = kmemstatistics;
699 	kmemstatistics = type;
700 }
701 
702 /*
703  * Remove a malloc type from the system..
704  */
705 void
706 malloc_type_detach(struct malloc_type *type)
707 {
708 	struct malloc_type *ksp;
709 
710 #ifdef DIAGNOSTIC
711 	if (type->ks_magic != M_MAGIC)
712 		panic("malloc_type_detach: bad magic");
713 #endif
714 
715 	if (type == kmemstatistics)
716 		kmemstatistics = type->ks_next;
717 	else {
718 		for (ksp = kmemstatistics; ksp->ks_next != NULL;
719 		     ksp = ksp->ks_next) {
720 			if (ksp->ks_next == type) {
721 				ksp->ks_next = type->ks_next;
722 				break;
723 			}
724 		}
725 #ifdef DIAGNOSTIC
726 		if (ksp->ks_next == NULL)
727 			panic("malloc_type_detach: not on list");
728 #endif
729 	}
730 	type->ks_next = NULL;
731 }
732 
733 /*
734  * Set the limit on a malloc type.
735  */
736 void
737 malloc_type_setlimit(struct malloc_type *type, u_long limit)
738 {
739 #ifdef KMEMSTATS
740 	int s;
741 
742 	s = splvm();
743 	type->ks_limit = limit;
744 	splx(s);
745 #endif
746 }
747 
748 /*
749  * Compute the number of pages that kmem_map will map, that is,
750  * the size of the kernel malloc arena.
751  */
752 void
753 kmeminit_nkmempages(void)
754 {
755 	int npages;
756 
757 	if (nkmempages != 0) {
758 		/*
759 		 * It's already been set (by us being here before, or
760 		 * by patching or kernel config options), bail out now.
761 		 */
762 		return;
763 	}
764 
765 	/*
766 	 * We use the following (simple) formula:
767 	 *
768 	 *	- Starting point is physical memory / 4.
769 	 *
770 	 *	- Clamp it down to NKMEMPAGES_MAX.
771 	 *
772 	 *	- Round it up to NKMEMPAGES_MIN.
773 	 */
774 	npages = physmem / 4;
775 
776 	if (npages > NKMEMPAGES_MAX)
777 		npages = NKMEMPAGES_MAX;
778 
779 	if (npages < NKMEMPAGES_MIN)
780 		npages = NKMEMPAGES_MIN;
781 
782 	nkmempages = npages;
783 }
784 
785 /*
786  * Initialize the kernel memory allocator
787  */
788 void
789 kmeminit(void)
790 {
791 	__link_set_decl(malloc_types, struct malloc_type);
792 	struct malloc_type * const *ksp;
793 #ifdef KMEMSTATS
794 	long indx;
795 #endif
796 
797 #if	((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
798 		ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
799 #endif
800 #if	(MAXALLOCSAVE > MINALLOCSIZE * 32768)
801 		ERROR!_kmeminit:_MAXALLOCSAVE_too_big
802 #endif
803 #if	(MAXALLOCSAVE < NBPG)
804 		ERROR!_kmeminit:_MAXALLOCSAVE_too_small
805 #endif
806 
807 	if (sizeof(struct freelist) > (1 << MINBUCKET))
808 		panic("minbucket too small/struct freelist too big");
809 
810 	/*
811 	 * Compute the number of kmem_map pages, if we have not
812 	 * done so already.
813 	 */
814 	kmeminit_nkmempages();
815 
816 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
817 	    (vsize_t)(nkmempages * sizeof(struct kmemusage)));
818 	kmem_map = uvm_km_suballoc(kernel_map, (void *)&kmembase,
819 	    (void *)&kmemlimit, (vsize_t)(nkmempages << PAGE_SHIFT),
820 	    VM_MAP_INTRSAFE, FALSE, &kmem_map_store);
821 #ifdef KMEMSTATS
822 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
823 		if (1 << indx >= PAGE_SIZE)
824 			bucket[indx].kb_elmpercl = 1;
825 		else
826 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
827 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
828 	}
829 #endif
830 
831 	/* Attach all of the statically-linked malloc types. */
832 	__link_set_foreach(ksp, malloc_types)
833 		malloc_type_attach(*ksp);
834 
835 #ifdef MALLOC_DEBUG
836 	debug_malloc_init();
837 #endif
838 }
839 
840 #ifdef DDB
841 #include <ddb/db_output.h>
842 
843 /*
844  * Dump kmem statistics from ddb.
845  *
846  * usage: call dump_kmemstats
847  */
848 void	dump_kmemstats(void);
849 
850 void
851 dump_kmemstats(void)
852 {
853 #ifdef KMEMSTATS
854 	struct malloc_type *ksp;
855 
856 	for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
857 		if (ksp->ks_memuse == 0)
858 			continue;
859 		db_printf("%s%.*s %ld\n", ksp->ks_shortdesc,
860 		    (int)(20 - strlen(ksp->ks_shortdesc)),
861 		    "                    ",
862 		    ksp->ks_memuse);
863 	}
864 #else
865 	db_printf("Kmem stats are not being collected.\n");
866 #endif /* KMEMSTATS */
867 }
868 #endif /* DDB */
869