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