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