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