xref: /openbsd-src/sys/kern/kern_malloc.c (revision e416345e5598864b399f31284e3fe41c0557f18d)
1 /*	$OpenBSD: kern_malloc.c,v 1.138 2019/05/09 14:09:01 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 	static int zerowarnings;
379 #endif
380 #ifdef KMEMSTATS
381 	struct kmemstats *ksp = &kmemstats[type];
382 	int wake;
383 #endif
384 
385 	if (addr == NULL)
386 		return;
387 
388 #ifdef DIAGNOSTIC
389 	if (addr < (void *)kmembase || addr >= (void *)kmemlimit)
390 		panic("free: non-malloced addr %p type %s", addr,
391 		    memname[type]);
392 #endif
393 
394 	mtx_enter(&malloc_mtx);
395 	kup = btokup(addr);
396 	size = 1 << kup->ku_indx;
397 	kbp = &bucket[kup->ku_indx];
398 	if (size > MAXALLOCSAVE)
399 		size = kup->ku_pagecnt << PAGE_SHIFT;
400 #ifdef DIAGNOSTIC
401 	if (freedsize == 0 && zerowarnings < 5) {
402 		zerowarnings++;
403 		printf("free with zero size: (%d)\n", type);
404 #ifdef DDB
405 #if 0
406 		db_stack_dump();
407 #endif
408 #endif
409 	}
410 	if (freedsize != 0 && freedsize > size)
411 		panic("free: size too large %zu > %ld (%p) type %s",
412 		    freedsize, size, addr, memname[type]);
413 	if (freedsize != 0 && size > MINALLOCSIZE && freedsize <= size / 2)
414 		panic("free: size too small %zu <= %ld / 2 (%p) type %s",
415 		    freedsize, size, addr, memname[type]);
416 	/*
417 	 * Check for returns of data that do not point to the
418 	 * beginning of the allocation.
419 	 */
420 	if (size > PAGE_SIZE)
421 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
422 	else
423 		alloc = addrmask[kup->ku_indx];
424 	if (((u_long)addr & alloc) != 0)
425 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
426 			addr, size, memname[type], alloc);
427 #endif /* DIAGNOSTIC */
428 	if (size > MAXALLOCSAVE) {
429 		u_short pagecnt = kup->ku_pagecnt;
430 
431 		kup->ku_indx = 0;
432 		kup->ku_pagecnt = 0;
433 		mtx_leave(&malloc_mtx);
434 		s = splvm();
435 		uvm_km_free(kmem_map, (vaddr_t)addr, ptoa(pagecnt));
436 		splx(s);
437 #ifdef KMEMSTATS
438 		mtx_enter(&malloc_mtx);
439 		ksp->ks_memuse -= size;
440 		wake = ksp->ks_memuse + size >= ksp->ks_limit &&
441 		    ksp->ks_memuse < ksp->ks_limit;
442 		ksp->ks_inuse--;
443 		kbp->kb_total -= 1;
444 		mtx_leave(&malloc_mtx);
445 		if (wake)
446 			wakeup(ksp);
447 #endif
448 		return;
449 	}
450 	freep = (struct kmem_freelist *)addr;
451 #ifdef DIAGNOSTIC
452 	/*
453 	 * Check for multiple frees. Use a quick check to see if
454 	 * it looks free before laboriously searching the freelist.
455 	 */
456 	if (freep->kf_spare0 == poison_value(freep)) {
457 		struct kmem_freelist *fp;
458 		XSIMPLEQ_FOREACH(fp, &kbp->kb_freelist, kf_flist) {
459 			if (addr != fp)
460 				continue;
461 			printf("multiply freed item %p\n", addr);
462 			panic("free: duplicated free");
463 		}
464 	}
465 	/*
466 	 * Copy in known text to detect modification after freeing
467 	 * and to make it look free. Also, save the type being freed
468 	 * so we can list likely culprit if modification is detected
469 	 * when the object is reallocated.
470 	 */
471 	poison_mem(addr, size);
472 	freep->kf_spare0 = poison_value(freep);
473 
474 	freep->kf_type = type;
475 #endif /* DIAGNOSTIC */
476 #ifdef KMEMSTATS
477 	kup->ku_freecnt++;
478 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
479 		if (kup->ku_freecnt > kbp->kb_elmpercl)
480 			panic("free: multiple frees");
481 		else if (kbp->kb_totalfree > kbp->kb_highwat)
482 			kbp->kb_couldfree++;
483 	}
484 	kbp->kb_totalfree++;
485 	ksp->ks_memuse -= size;
486 	wake = ksp->ks_memuse + size >= ksp->ks_limit &&
487 	    ksp->ks_memuse < ksp->ks_limit;
488 	ksp->ks_inuse--;
489 #endif
490 	XSIMPLEQ_INSERT_TAIL(&kbp->kb_freelist, freep, kf_flist);
491 	mtx_leave(&malloc_mtx);
492 #ifdef KMEMSTATS
493 	if (wake)
494 		wakeup(ksp);
495 #endif
496 }
497 
498 /*
499  * Compute the number of pages that kmem_map will map, that is,
500  * the size of the kernel malloc arena.
501  */
502 void
503 kmeminit_nkmempages(void)
504 {
505 	u_int npages;
506 
507 	if (nkmempages != 0) {
508 		/*
509 		 * It's already been set (by us being here before, or
510 		 * by patching or kernel config options), bail out now.
511 		 */
512 		return;
513 	}
514 
515 	/*
516 	 * We can't initialize these variables at compilation time, since
517 	 * the page size may not be known (on sparc GENERIC kernels, for
518 	 * example). But we still want the MD code to be able to provide
519 	 * better values.
520 	 */
521 	if (nkmempages_min == 0)
522 		nkmempages_min = NKMEMPAGES_MIN;
523 	if (nkmempages_max == 0)
524 		nkmempages_max = NKMEMPAGES_MAX;
525 
526 	/*
527 	 * We use the following (simple) formula:
528 	 *
529 	 *	- Starting point is physical memory / 4.
530 	 *
531 	 *	- Clamp it down to nkmempages_max.
532 	 *
533 	 *	- Round it up to nkmempages_min.
534 	 */
535 	npages = physmem / 4;
536 
537 	if (npages > nkmempages_max)
538 		npages = nkmempages_max;
539 
540 	if (npages < nkmempages_min)
541 		npages = nkmempages_min;
542 
543 	nkmempages = npages;
544 }
545 
546 /*
547  * Initialize the kernel memory allocator
548  */
549 void
550 kmeminit(void)
551 {
552 	vaddr_t base, limit;
553 	long indx;
554 
555 #ifdef DIAGNOSTIC
556 	if (sizeof(struct kmem_freelist) > (1 << MINBUCKET))
557 		panic("kmeminit: minbucket too small/struct freelist too big");
558 #endif
559 
560 	/*
561 	 * Compute the number of kmem_map pages, if we have not
562 	 * done so already.
563 	 */
564 	kmeminit_nkmempages();
565 	base = vm_map_min(kernel_map);
566 	kmem_map = uvm_km_suballoc(kernel_map, &base, &limit,
567 	    (vsize_t)nkmempages << PAGE_SHIFT,
568 #ifdef KVA_GUARDPAGES
569 	    VM_MAP_INTRSAFE | VM_MAP_GUARDPAGES,
570 #else
571 	    VM_MAP_INTRSAFE,
572 #endif
573 	    FALSE, &kmem_map_store);
574 	kmembase = (char *)base;
575 	kmemlimit = (char *)limit;
576 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
577 		(vsize_t)(nkmempages * sizeof(struct kmemusage)));
578 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
579 		XSIMPLEQ_INIT(&bucket[indx].kb_freelist);
580 	}
581 #ifdef KMEMSTATS
582 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
583 		if (1 << indx >= PAGE_SIZE)
584 			bucket[indx].kb_elmpercl = 1;
585 		else
586 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
587 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
588 	}
589 	for (indx = 0; indx < M_LAST; indx++)
590 		kmemstats[indx].ks_limit = nkmempages * PAGE_SIZE * 6 / 10;
591 #endif
592 }
593 
594 /*
595  * Return kernel malloc statistics information.
596  */
597 int
598 sysctl_malloc(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
599     size_t newlen, struct proc *p)
600 {
601 	struct kmembuckets kb;
602 #ifdef KMEMSTATS
603 	struct kmemstats km;
604 #endif
605 #if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES)
606 	int error;
607 #endif
608 	int i, siz;
609 
610 	if (namelen != 2 && name[0] != KERN_MALLOC_BUCKETS &&
611 	    name[0] != KERN_MALLOC_KMEMNAMES)
612 		return (ENOTDIR);		/* overloaded */
613 
614 	switch (name[0]) {
615 	case KERN_MALLOC_BUCKETS:
616 		/* Initialize the first time */
617 		if (buckstring_init == 0) {
618 			buckstring_init = 1;
619 			memset(buckstring, 0, sizeof(buckstring));
620 			for (siz = 0, i = MINBUCKET; i < MINBUCKET + 16; i++) {
621 				snprintf(buckstring + siz,
622 				    sizeof buckstring - siz,
623 				    "%d,", (u_int)(1<<i));
624 				siz += strlen(buckstring + siz);
625 			}
626 			/* Remove trailing comma */
627 			if (siz)
628 				buckstring[siz - 1] = '\0';
629 		}
630 		return (sysctl_rdstring(oldp, oldlenp, newp, buckstring));
631 
632 	case KERN_MALLOC_BUCKET:
633 		mtx_enter(&malloc_mtx);
634 		memcpy(&kb, &bucket[BUCKETINDX(name[1])], sizeof(kb));
635 		mtx_leave(&malloc_mtx);
636 		memset(&kb.kb_freelist, 0, sizeof(kb.kb_freelist));
637 		return (sysctl_rdstruct(oldp, oldlenp, newp, &kb, sizeof(kb)));
638 	case KERN_MALLOC_KMEMSTATS:
639 #ifdef KMEMSTATS
640 		if ((name[1] < 0) || (name[1] >= M_LAST))
641 			return (EINVAL);
642 		mtx_enter(&malloc_mtx);
643 		memcpy(&km, &kmemstats[name[1]], sizeof(km));
644 		mtx_leave(&malloc_mtx);
645 		return (sysctl_rdstruct(oldp, oldlenp, newp, &km, sizeof(km)));
646 #else
647 		return (EOPNOTSUPP);
648 #endif
649 	case KERN_MALLOC_KMEMNAMES:
650 #if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES)
651 		error = rw_enter(&sysctl_kmemlock, RW_WRITE|RW_INTR);
652 		if (error)
653 			return (error);
654 		if (memall == NULL) {
655 			int totlen;
656 
657 			/* Figure out how large a buffer we need */
658 			for (totlen = 0, i = 0; i < M_LAST; i++) {
659 				if (memname[i])
660 					totlen += strlen(memname[i]);
661 				totlen++;
662 			}
663 			memall = malloc(totlen + M_LAST, M_SYSCTL,
664 			    M_WAITOK|M_ZERO);
665 			for (siz = 0, i = 0; i < M_LAST; i++) {
666 				snprintf(memall + siz,
667 				    totlen + M_LAST - siz,
668 				    "%s,", memname[i] ? memname[i] : "");
669 				siz += strlen(memall + siz);
670 			}
671 			/* Remove trailing comma */
672 			if (siz)
673 				memall[siz - 1] = '\0';
674 
675 			/* Now, convert all spaces to underscores */
676 			for (i = 0; i < totlen; i++)
677 				if (memall[i] == ' ')
678 					memall[i] = '_';
679 		}
680 		rw_exit_write(&sysctl_kmemlock);
681 		return (sysctl_rdstring(oldp, oldlenp, newp, memall));
682 #else
683 		return (EOPNOTSUPP);
684 #endif
685 	default:
686 		return (EOPNOTSUPP);
687 	}
688 	/* NOTREACHED */
689 }
690 
691 /*
692  * Round up a size to how much malloc would actually allocate.
693  */
694 size_t
695 malloc_roundup(size_t sz)
696 {
697 	if (sz > MAXALLOCSAVE)
698 		return round_page(sz);
699 
700 	return (1 << BUCKETINDX(sz));
701 }
702 
703 #if defined(DDB)
704 
705 void
706 malloc_printit(
707     int (*pr)(const char *, ...) __attribute__((__format__(__kprintf__,1,2))))
708 {
709 #ifdef KMEMSTATS
710 	struct kmemstats *km;
711 	int i;
712 
713 	(*pr)("%15s %5s  %6s  %7s  %6s %9s %8s %8s\n",
714 	    "Type", "InUse", "MemUse", "HighUse", "Limit", "Requests",
715 	    "Type Lim", "Kern Lim");
716 	for (i = 0, km = kmemstats; i < M_LAST; i++, km++) {
717 		if (!km->ks_calls || !memname[i])
718 			continue;
719 
720 		(*pr)("%15s %5ld %6ldK %7ldK %6ldK %9ld %8d %8d\n",
721 		    memname[i], km->ks_inuse, km->ks_memuse / 1024,
722 		    km->ks_maxused / 1024, km->ks_limit / 1024,
723 		    km->ks_calls, km->ks_limblocks, km->ks_mapblocks);
724 	}
725 #else
726 	(*pr)("No KMEMSTATS compiled in\n");
727 #endif
728 }
729 #endif /* DDB */
730 
731 /*
732  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
733  *
734  * Permission to use, copy, modify, and distribute this software for any
735  * purpose with or without fee is hereby granted, provided that the above
736  * copyright notice and this permission notice appear in all copies.
737  *
738  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
739  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
740  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
741  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
742  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
743  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
744  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
745  */
746 
747 /*
748  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
749  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
750  */
751 #define MUL_NO_OVERFLOW	(1UL << (sizeof(size_t) * 4))
752 
753 void *
754 mallocarray(size_t nmemb, size_t size, int type, int flags)
755 {
756 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
757 	    nmemb > 0 && SIZE_MAX / nmemb < size) {
758 		if (flags & M_CANFAIL)
759 			return (NULL);
760 		panic("mallocarray: overflow %zu * %zu", nmemb, size);
761 	}
762 	return (malloc(size * nmemb, type, flags));
763 }
764