xref: /openbsd-src/sys/kern/kern_malloc.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*	$OpenBSD: kern_malloc.c,v 1.92 2012/03/30 23:03:42 pirofti Exp $	*/
2 /*	$NetBSD: kern_malloc.c,v 1.15.4.2 1996/06/13 17:10:56 cgd Exp $	*/
3 
4 /*
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. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)kern_malloc.c	8.3 (Berkeley) 1/4/94
33  */
34 
35 #include <sys/param.h>
36 #include <sys/proc.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/systm.h>
40 #include <sys/sysctl.h>
41 #include <sys/time.h>
42 #include <sys/rwlock.h>
43 
44 #include <uvm/uvm.h>
45 
46 static __inline__ long BUCKETINDX(size_t sz)
47 {
48 #ifdef SMALL_KERNEL
49 	long b;
50 
51 	if (sz-- == 0)
52 		return MINBUCKET;
53 
54 	for (b = MINBUCKET; b < MINBUCKET + 15; b++)
55 		if ((sz >> b) == 0)
56 			break;
57 #else
58 	long b, d;
59 
60 	/* note that this relies upon MINALLOCSIZE being 1 << MINBUCKET */
61 	b = 7 + MINBUCKET; d = 4;
62 	while (d != 0) {
63 		if (sz <= (1 << b))
64 			b -= d;
65 		else
66 			b += d;
67 		d >>= 1;
68 	}
69 	if (sz <= (1 << b))
70 		b += 0;
71 	else
72 		b += 1;
73 #endif
74 
75 	return b;
76 }
77 
78 static struct vm_map kmem_map_store;
79 struct vm_map *kmem_map = NULL;
80 
81 #ifdef NKMEMCLUSTERS
82 #error NKMEMCLUSTERS is obsolete; remove it from your kernel config file and use NKMEMPAGES instead or let the kernel auto-size
83 #endif
84 
85 /*
86  * Default number of pages in kmem_map.  We attempt to calculate this
87  * at run-time, but allow it to be either patched or set in the kernel
88  * config file.
89  */
90 #ifndef NKMEMPAGES
91 #define	NKMEMPAGES	0
92 #endif
93 u_int	nkmempages = NKMEMPAGES;
94 
95 /*
96  * Defaults for lower- and upper-bounds for the kmem_map page count.
97  * Can be overridden by kernel config options.
98  */
99 #ifndef	NKMEMPAGES_MIN
100 #define	NKMEMPAGES_MIN	0
101 #endif
102 u_int	nkmempages_min = 0;
103 
104 #ifndef NKMEMPAGES_MAX
105 #define	NKMEMPAGES_MAX	NKMEMPAGES_MAX_DEFAULT
106 #endif
107 u_int	nkmempages_max = 0;
108 
109 struct kmembuckets bucket[MINBUCKET + 16];
110 #ifdef KMEMSTATS
111 struct kmemstats kmemstats[M_LAST];
112 #endif
113 struct kmemusage *kmemusage;
114 char *kmembase, *kmemlimit;
115 char buckstring[16 * sizeof("123456,")];
116 int buckstring_init = 0;
117 #if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES)
118 char *memname[] = INITKMEMNAMES;
119 char *memall = NULL;
120 struct rwlock sysctl_kmemlock = RWLOCK_INITIALIZER("sysctlklk");
121 #endif
122 
123 #ifdef DIAGNOSTIC
124 /*
125  * This structure provides a set of masks to catch unaligned frees.
126  */
127 const long addrmask[] = { 0,
128 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
129 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
130 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
131 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
132 };
133 
134 /*
135  * The WEIRD_ADDR is used as known text to copy into free objects so
136  * that modifications after frees can be detected.
137  */
138 #ifdef DEADBEEF0
139 #define WEIRD_ADDR	((unsigned) DEADBEEF0)
140 #else
141 #define WEIRD_ADDR	((unsigned) 0xdeadbeef)
142 #endif
143 #define MAX_COPY	32
144 
145 /*
146  * Normally the freelist structure is used only to hold the list pointer
147  * for free objects.  However, when running with diagnostics, the first
148  * 8 bytes of the structure is unused except for diagnostic information,
149  * and the free list pointer is at offset 8 in the structure.  Since the
150  * first 8 bytes is the portion of the structure most often modified, this
151  * helps to detect memory reuse problems and avoid free list corruption.
152  */
153 struct freelist {
154 	int32_t	spare0;
155 	int16_t	type;
156 	int16_t	spare1;
157 	caddr_t	next;
158 };
159 #else /* !DIAGNOSTIC */
160 struct freelist {
161 	caddr_t	next;
162 };
163 #endif /* DIAGNOSTIC */
164 
165 #ifndef SMALL_KERNEL
166 struct timeval malloc_errintvl = { 5, 0 };
167 struct timeval malloc_lasterr;
168 #endif
169 
170 /*
171  * Allocate a block of memory
172  */
173 void *
174 malloc(unsigned long size, int type, int flags)
175 {
176 	struct kmembuckets *kbp;
177 	struct kmemusage *kup;
178 	struct freelist *freep;
179 	long indx, npg, allocsize;
180 	int s;
181 	caddr_t va, cp, savedlist;
182 #ifdef DIAGNOSTIC
183 	int32_t *end, *lp;
184 	int copysize, freshalloc;
185 	char *savedtype;
186 #endif
187 #ifdef KMEMSTATS
188 	struct kmemstats *ksp = &kmemstats[type];
189 
190 	if (((unsigned long)type) <= 1 || ((unsigned long)type) >= M_LAST)
191 		panic("malloc - bogus type");
192 #endif
193 
194 	KASSERT(flags & (M_WAITOK | M_NOWAIT));
195 
196 	if ((flags & M_NOWAIT) == 0)
197 		assertwaitok();
198 
199 #ifdef MALLOC_DEBUG
200 	if (debug_malloc(size, type, flags, (void **)&va)) {
201 		if ((flags & M_ZERO) && va != NULL)
202 			memset(va, 0, size);
203 		return (va);
204 	}
205 #endif
206 
207 	if (size > 65535 * PAGE_SIZE) {
208 		if (flags & M_CANFAIL) {
209 #ifndef SMALL_KERNEL
210 			if (ratecheck(&malloc_lasterr, &malloc_errintvl))
211 				printf("malloc(): allocation too large, "
212 				    "type = %d, size = %lu\n", type, size);
213 #endif
214 			return (NULL);
215 		} else
216 			panic("malloc: allocation too large, "
217 			    "type = %d, size = %lu\n", type, size);
218 	}
219 
220 	indx = BUCKETINDX(size);
221 	kbp = &bucket[indx];
222 	s = splvm();
223 #ifdef KMEMSTATS
224 	while (ksp->ks_memuse >= ksp->ks_limit) {
225 		if (flags & M_NOWAIT) {
226 			splx(s);
227 			return (NULL);
228 		}
229 		if (ksp->ks_limblocks < 65535)
230 			ksp->ks_limblocks++;
231 		tsleep(ksp, PSWP+2, memname[type], 0);
232 	}
233 	ksp->ks_size |= 1 << indx;
234 #endif
235 #ifdef DIAGNOSTIC
236 	copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
237 #endif
238 	if (kbp->kb_next == NULL) {
239 		if (size > MAXALLOCSAVE)
240 			allocsize = round_page(size);
241 		else
242 			allocsize = 1 << indx;
243 		npg = atop(round_page(allocsize));
244 		va = (caddr_t)uvm_km_kmemalloc_pla(kmem_map, NULL,
245 		    (vsize_t)ptoa(npg), 0,
246 		    ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) |
247 		    ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 0),
248 		    no_constraint.ucr_low, no_constraint.ucr_high,
249 		    0, 0, 0);
250 		if (va == NULL) {
251 			/*
252 			 * Kmem_malloc() can return NULL, even if it can
253 			 * wait, if there is no map space available, because
254 			 * it can't fix that problem.  Neither can we,
255 			 * right now.  (We should release pages which
256 			 * are completely free and which are in buckets
257 			 * with too many free elements.)
258 			 */
259 			if ((flags & (M_NOWAIT|M_CANFAIL)) == 0)
260 				panic("malloc: out of space in kmem_map");
261 			splx(s);
262 			return (NULL);
263 		}
264 #ifdef KMEMSTATS
265 		kbp->kb_total += kbp->kb_elmpercl;
266 #endif
267 		kup = btokup(va);
268 		kup->ku_indx = indx;
269 #ifdef DIAGNOSTIC
270 		freshalloc = 1;
271 #endif
272 		if (allocsize > MAXALLOCSAVE) {
273 			kup->ku_pagecnt = npg;
274 #ifdef KMEMSTATS
275 			ksp->ks_memuse += allocsize;
276 #endif
277 			goto out;
278 		}
279 #ifdef KMEMSTATS
280 		kup->ku_freecnt = kbp->kb_elmpercl;
281 		kbp->kb_totalfree += kbp->kb_elmpercl;
282 #endif
283 		/*
284 		 * Just in case we blocked while allocating memory,
285 		 * and someone else also allocated memory for this
286 		 * bucket, don't assume the list is still empty.
287 		 */
288 		savedlist = kbp->kb_next;
289 		kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
290 		for (;;) {
291 			freep = (struct freelist *)cp;
292 #ifdef DIAGNOSTIC
293 			/*
294 			 * Copy in known text to detect modification
295 			 * after freeing.
296 			 */
297 			end = (int32_t *)&cp[copysize];
298 			for (lp = (int32_t *)cp; lp < end; lp++)
299 				*lp = WEIRD_ADDR;
300 			freep->type = M_FREE;
301 #endif /* DIAGNOSTIC */
302 			if (cp <= va)
303 				break;
304 			cp -= allocsize;
305 			freep->next = cp;
306 		}
307 		freep->next = savedlist;
308 		if (savedlist == NULL)
309 			kbp->kb_last = (caddr_t)freep;
310 	} else {
311 #ifdef DIAGNOSTIC
312 		freshalloc = 0;
313 #endif
314 	}
315 	va = kbp->kb_next;
316 	kbp->kb_next = ((struct freelist *)va)->next;
317 #ifdef DIAGNOSTIC
318 	freep = (struct freelist *)va;
319 	savedtype = (unsigned)freep->type < M_LAST ?
320 		memname[freep->type] : "???";
321 	if (freshalloc == 0 && kbp->kb_next) {
322 		int rv;
323 		vaddr_t addr = (vaddr_t)kbp->kb_next;
324 
325 		vm_map_lock(kmem_map);
326 		rv = uvm_map_checkprot(kmem_map, addr,
327 		    addr + sizeof(struct freelist), VM_PROT_WRITE);
328 		vm_map_unlock(kmem_map);
329 
330 		if (!rv)  {
331 			printf("%s %d of object %p size 0x%lx %s %s"
332 			    " (invalid addr %p)\n",
333 			    "Data modified on freelist: word",
334 			    (int32_t *)&kbp->kb_next - (int32_t *)kbp, va, size,
335 			    "previous type", savedtype, addr);
336 			kbp->kb_next = NULL;
337 		}
338 	}
339 
340 	/* Fill the fields that we've used with WEIRD_ADDR */
341 #if BYTE_ORDER == BIG_ENDIAN
342 	freep->type = WEIRD_ADDR >> 16;
343 #endif
344 #if BYTE_ORDER == LITTLE_ENDIAN
345 	freep->type = (short)WEIRD_ADDR;
346 #endif
347 	end = (int32_t *)&freep->next +
348 	    (sizeof(freep->next) / sizeof(int32_t));
349 	for (lp = (int32_t *)&freep->next; lp < end; lp++)
350 		*lp = WEIRD_ADDR;
351 
352 	/* and check that the data hasn't been modified. */
353 	if (freshalloc == 0) {
354 		end = (int32_t *)&va[copysize];
355 		for (lp = (int32_t *)va; lp < end; lp++) {
356 			if (*lp == WEIRD_ADDR)
357 				continue;
358 			printf("%s %d of object %p size 0x%lx %s %s"
359 			    " (0x%x != 0x%x)\n",
360 			    "Data modified on freelist: word",
361 			    lp - (int32_t *)va, va, size,
362 			    "previous type", savedtype, *lp, WEIRD_ADDR);
363 			break;
364 		}
365 	}
366 
367 	freep->spare0 = 0;
368 #endif /* DIAGNOSTIC */
369 #ifdef KMEMSTATS
370 	kup = btokup(va);
371 	if (kup->ku_indx != indx)
372 		panic("malloc: wrong bucket");
373 	if (kup->ku_freecnt == 0)
374 		panic("malloc: lost data");
375 	kup->ku_freecnt--;
376 	kbp->kb_totalfree--;
377 	ksp->ks_memuse += 1 << indx;
378 out:
379 	kbp->kb_calls++;
380 	ksp->ks_inuse++;
381 	ksp->ks_calls++;
382 	if (ksp->ks_memuse > ksp->ks_maxused)
383 		ksp->ks_maxused = ksp->ks_memuse;
384 #else
385 out:
386 #endif
387 	splx(s);
388 
389 	if ((flags & M_ZERO) && va != NULL)
390 		memset(va, 0, size);
391 	return (va);
392 }
393 
394 /*
395  * Free a block of memory allocated by malloc.
396  */
397 void
398 free(void *addr, int type)
399 {
400 	struct kmembuckets *kbp;
401 	struct kmemusage *kup;
402 	struct freelist *freep;
403 	long size;
404 	int s;
405 #ifdef DIAGNOSTIC
406 	caddr_t cp;
407 	int32_t *end, *lp;
408 	long alloc, copysize;
409 #endif
410 #ifdef KMEMSTATS
411 	struct kmemstats *ksp = &kmemstats[type];
412 #endif
413 
414 #ifdef MALLOC_DEBUG
415 	if (debug_free(addr, type))
416 		return;
417 #endif
418 
419 #ifdef DIAGNOSTIC
420 	if (addr < (void *)kmembase || addr >= (void *)kmemlimit)
421 		panic("free: non-malloced addr %p type %s", addr,
422 		    memname[type]);
423 #endif
424 
425 	kup = btokup(addr);
426 	size = 1 << kup->ku_indx;
427 	kbp = &bucket[kup->ku_indx];
428 	s = splvm();
429 #ifdef DIAGNOSTIC
430 	/*
431 	 * Check for returns of data that do not point to the
432 	 * beginning of the allocation.
433 	 */
434 	if (size > PAGE_SIZE)
435 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
436 	else
437 		alloc = addrmask[kup->ku_indx];
438 	if (((u_long)addr & alloc) != 0)
439 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
440 			addr, size, memname[type], alloc);
441 #endif /* DIAGNOSTIC */
442 	if (size > MAXALLOCSAVE) {
443 		uvm_km_free(kmem_map, (vaddr_t)addr, ptoa(kup->ku_pagecnt));
444 #ifdef KMEMSTATS
445 		size = kup->ku_pagecnt << PGSHIFT;
446 		ksp->ks_memuse -= size;
447 		kup->ku_indx = 0;
448 		kup->ku_pagecnt = 0;
449 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
450 		    ksp->ks_memuse < ksp->ks_limit)
451 			wakeup(ksp);
452 		ksp->ks_inuse--;
453 		kbp->kb_total -= 1;
454 #endif
455 		splx(s);
456 		return;
457 	}
458 	freep = (struct freelist *)addr;
459 #ifdef DIAGNOSTIC
460 	/*
461 	 * Check for multiple frees. Use a quick check to see if
462 	 * it looks free before laboriously searching the freelist.
463 	 */
464 	if (freep->spare0 == WEIRD_ADDR) {
465 		for (cp = kbp->kb_next; cp;
466 		    cp = ((struct freelist *)cp)->next) {
467 			if (addr != cp)
468 				continue;
469 			printf("multiply freed item %p\n", addr);
470 			panic("free: duplicated free");
471 		}
472 	}
473 	/*
474 	 * Copy in known text to detect modification after freeing
475 	 * and to make it look free. Also, save the type being freed
476 	 * so we can list likely culprit if modification is detected
477 	 * when the object is reallocated.
478 	 */
479 	copysize = size < MAX_COPY ? size : MAX_COPY;
480 	end = (int32_t *)&((caddr_t)addr)[copysize];
481 	for (lp = (int32_t *)addr; lp < end; lp++)
482 		*lp = WEIRD_ADDR;
483 	freep->type = type;
484 #endif /* DIAGNOSTIC */
485 #ifdef KMEMSTATS
486 	kup->ku_freecnt++;
487 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
488 		if (kup->ku_freecnt > kbp->kb_elmpercl)
489 			panic("free: multiple frees");
490 		else if (kbp->kb_totalfree > kbp->kb_highwat)
491 			kbp->kb_couldfree++;
492 	}
493 	kbp->kb_totalfree++;
494 	ksp->ks_memuse -= size;
495 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
496 	    ksp->ks_memuse < ksp->ks_limit)
497 		wakeup(ksp);
498 	ksp->ks_inuse--;
499 #endif
500 	if (kbp->kb_next == NULL)
501 		kbp->kb_next = addr;
502 	else
503 		((struct freelist *)kbp->kb_last)->next = addr;
504 	freep->next = NULL;
505 	kbp->kb_last = addr;
506 	splx(s);
507 }
508 
509 /*
510  * Compute the number of pages that kmem_map will map, that is,
511  * the size of the kernel malloc arena.
512  */
513 void
514 kmeminit_nkmempages(void)
515 {
516 	u_int npages;
517 
518 	if (nkmempages != 0) {
519 		/*
520 		 * It's already been set (by us being here before, or
521 		 * by patching or kernel config options), bail out now.
522 		 */
523 		return;
524 	}
525 
526 	/*
527 	 * We can't initialize these variables at compilation time, since
528 	 * the page size may not be known (on sparc GENERIC kernels, for
529 	 * example). But we still want the MD code to be able to provide
530 	 * better values.
531 	 */
532 	if (nkmempages_min == 0)
533 		nkmempages_min = NKMEMPAGES_MIN;
534 	if (nkmempages_max == 0)
535 		nkmempages_max = NKMEMPAGES_MAX;
536 
537 	/*
538 	 * We use the following (simple) formula:
539 	 *
540 	 *	- Starting point is physical memory / 4.
541 	 *
542 	 *	- Clamp it down to nkmempages_max.
543 	 *
544 	 *	- Round it up to nkmempages_min.
545 	 */
546 	npages = physmem / 4;
547 
548 	if (npages > nkmempages_max)
549 		npages = nkmempages_max;
550 
551 	if (npages < nkmempages_min)
552 		npages = nkmempages_min;
553 
554 	nkmempages = npages;
555 }
556 
557 /*
558  * Initialize the kernel memory allocator
559  */
560 void
561 kmeminit(void)
562 {
563 	vaddr_t base, limit;
564 #ifdef KMEMSTATS
565 	long indx;
566 #endif
567 
568 #ifdef DIAGNOSTIC
569 	if (sizeof(struct freelist) > (1 << MINBUCKET))
570 		panic("kmeminit: minbucket too small/struct freelist too big");
571 #endif
572 
573 	/*
574 	 * Compute the number of kmem_map pages, if we have not
575 	 * done so already.
576 	 */
577 	kmeminit_nkmempages();
578 	base = vm_map_min(kernel_map);
579 	kmem_map = uvm_km_suballoc(kernel_map, &base, &limit,
580 	    (vsize_t)nkmempages << PAGE_SHIFT,
581 #ifdef KVA_GUARDPAGES
582 	    VM_MAP_INTRSAFE | VM_MAP_GUARDPAGES,
583 #else
584 	    VM_MAP_INTRSAFE,
585 #endif
586 	    FALSE, &kmem_map_store);
587 	kmembase = (char *)base;
588 	kmemlimit = (char *)limit;
589 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
590 		(vsize_t)(nkmempages * sizeof(struct kmemusage)));
591 #ifdef KMEMSTATS
592 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
593 		if (1 << indx >= PAGE_SIZE)
594 			bucket[indx].kb_elmpercl = 1;
595 		else
596 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
597 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
598 	}
599 	for (indx = 0; indx < M_LAST; indx++)
600 		kmemstats[indx].ks_limit = nkmempages * PAGE_SIZE * 6 / 10;
601 #endif
602 #ifdef MALLOC_DEBUG
603 	debug_malloc_init();
604 #endif
605 }
606 
607 /*
608  * Return kernel malloc statistics information.
609  */
610 int
611 sysctl_malloc(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
612     size_t newlen, struct proc *p)
613 {
614 	struct kmembuckets kb;
615 	int i, siz;
616 
617 	if (namelen != 2 && name[0] != KERN_MALLOC_BUCKETS &&
618 	    name[0] != KERN_MALLOC_KMEMNAMES)
619 		return (ENOTDIR);		/* overloaded */
620 
621 	switch (name[0]) {
622 	case KERN_MALLOC_BUCKETS:
623 		/* Initialize the first time */
624 		if (buckstring_init == 0) {
625 			buckstring_init = 1;
626 			bzero(buckstring, sizeof(buckstring));
627 			for (siz = 0, i = MINBUCKET; i < MINBUCKET + 16; i++) {
628 				snprintf(buckstring + siz,
629 				    sizeof buckstring - siz,
630 				    "%d,", (u_int)(1<<i));
631 				siz += strlen(buckstring + siz);
632 			}
633 			/* Remove trailing comma */
634 			if (siz)
635 				buckstring[siz - 1] = '\0';
636 		}
637 		return (sysctl_rdstring(oldp, oldlenp, newp, buckstring));
638 
639 	case KERN_MALLOC_BUCKET:
640 		bcopy(&bucket[BUCKETINDX(name[1])], &kb, sizeof(kb));
641 		kb.kb_next = kb.kb_last = 0;
642 		return (sysctl_rdstruct(oldp, oldlenp, newp, &kb, sizeof(kb)));
643 	case KERN_MALLOC_KMEMSTATS:
644 #ifdef KMEMSTATS
645 		if ((name[1] < 0) || (name[1] >= M_LAST))
646 			return (EINVAL);
647 		return (sysctl_rdstruct(oldp, oldlenp, newp,
648 		    &kmemstats[name[1]], sizeof(struct kmemstats)));
649 #else
650 		return (EOPNOTSUPP);
651 #endif
652 	case KERN_MALLOC_KMEMNAMES:
653 #if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES)
654 		if (memall == NULL) {
655 			int totlen;
656 
657 			i = rw_enter(&sysctl_kmemlock, RW_WRITE|RW_INTR);
658 			if (i)
659 				return (i);
660 
661 			/* Figure out how large a buffer we need */
662 			for (totlen = 0, i = 0; i < M_LAST; i++) {
663 				if (memname[i])
664 					totlen += strlen(memname[i]);
665 				totlen++;
666 			}
667 			memall = malloc(totlen + M_LAST, M_SYSCTL,
668 			    M_WAITOK|M_ZERO);
669 			for (siz = 0, i = 0; i < M_LAST; i++) {
670 				snprintf(memall + siz,
671 				    totlen + M_LAST - siz,
672 				    "%s,", memname[i] ? memname[i] : "");
673 				siz += strlen(memall + siz);
674 			}
675 			/* Remove trailing comma */
676 			if (siz)
677 				memall[siz - 1] = '\0';
678 
679 			/* Now, convert all spaces to underscores */
680 			for (i = 0; i < totlen; i++)
681 				if (memall[i] == ' ')
682 					memall[i] = '_';
683 			rw_exit_write(&sysctl_kmemlock);
684 		}
685 		return (sysctl_rdstring(oldp, oldlenp, newp, memall));
686 #else
687 		return (EOPNOTSUPP);
688 #endif
689 	default:
690 		return (EOPNOTSUPP);
691 	}
692 	/* NOTREACHED */
693 }
694 
695 /*
696  * Round up a size to how much malloc would actually allocate.
697  */
698 size_t
699 malloc_roundup(size_t sz)
700 {
701 	if (sz > MAXALLOCSAVE)
702 		return round_page(sz);
703 
704 	return (1 << BUCKETINDX(sz));
705 }
706 
707 #if defined(DDB)
708 #include <machine/db_machdep.h>
709 #include <ddb/db_interface.h>
710 #include <ddb/db_output.h>
711 
712 void
713 malloc_printit(int (*pr)(const char *, ...))
714 {
715 #ifdef KMEMSTATS
716 	struct kmemstats *km;
717 	int i;
718 
719 	(*pr)("%15s %5s  %6s  %7s  %6s %9s %8s %8s\n",
720 	    "Type", "InUse", "MemUse", "HighUse", "Limit", "Requests",
721 	    "Type Lim", "Kern Lim");
722 	for (i = 0, km = kmemstats; i < M_LAST; i++, km++) {
723 		if (!km->ks_calls || !memname[i])
724 			continue;
725 
726 		(*pr)("%15s %5ld %6ldK %7ldK %6ldK %9ld %8d %8d\n",
727 		    memname[i], km->ks_inuse, km->ks_memuse / 1024,
728 		    km->ks_maxused / 1024, km->ks_limit / 1024,
729 		    km->ks_calls, km->ks_limblocks, km->ks_mapblocks);
730 	}
731 #else
732 	(*pr)("No KMEMSTATS compiled in\n");
733 #endif
734 }
735 #endif /* DDB */
736