xref: /openbsd-src/sys/kern/kern_malloc.c (revision 42ac1f71ddfc8f2b1ea1555399aa1e1ffc2faced)
1 /*	$OpenBSD: kern_malloc.c,v 1.147 2022/05/04 21:24:33 bluhm 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 #include <sys/tracepoint.h>
46 
47 #include <uvm/uvm_extern.h>
48 
49 #if defined(DDB)
50 #include <machine/db_machdep.h>
51 #include <ddb/db_output.h>
52 #endif
53 
54 static
55 #ifndef SMALL_KERNEL
56 __inline__
57 #endif
58 long BUCKETINDX(size_t sz)
59 {
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 	return b;
76 }
77 
78 static struct vm_map kmem_map_store;
79 struct vm_map *kmem_map = NULL;
80 
81 /*
82  * Default number of pages in kmem_map.  We attempt to calculate this
83  * at run-time, but allow it to be either patched or set in the kernel
84  * config file.
85  */
86 #ifndef NKMEMPAGES
87 #define	NKMEMPAGES	0
88 #endif
89 u_int	nkmempages = NKMEMPAGES;
90 
91 /*
92  * Defaults for lower- and upper-bounds for the kmem_map page count.
93  * Can be overridden by kernel config options.
94  */
95 #ifndef	NKMEMPAGES_MIN
96 #define	NKMEMPAGES_MIN	0
97 #endif
98 u_int	nkmempages_min = 0;
99 
100 #ifndef NKMEMPAGES_MAX
101 #define	NKMEMPAGES_MAX	NKMEMPAGES_MAX_DEFAULT
102 #endif
103 u_int	nkmempages_max = 0;
104 
105 struct mutex malloc_mtx = MUTEX_INITIALIZER(IPL_VM);
106 struct kmembuckets bucket[MINBUCKET + 16];
107 #ifdef KMEMSTATS
108 struct kmemstats kmemstats[M_LAST];
109 #endif
110 struct kmemusage *kmemusage;
111 char *kmembase, *kmemlimit;
112 char buckstring[16 * sizeof("123456,")];
113 int buckstring_init = 0;
114 #if defined(KMEMSTATS) || defined(DIAGNOSTIC)
115 char *memname[] = INITKMEMNAMES;
116 char *memall = NULL;
117 struct rwlock sysctl_kmemlock = RWLOCK_INITIALIZER("sysctlklk");
118 #endif
119 
120 /*
121  * Normally the freelist structure is used only to hold the list pointer
122  * for free objects.  However, when running with diagnostics, the first
123  * 8 bytes of the structure is unused except for diagnostic information,
124  * and the free list pointer is at offset 8 in the structure.  Since the
125  * first 8 bytes is the portion of the structure most often modified, this
126  * helps to detect memory reuse problems and avoid free list corruption.
127  */
128 struct kmem_freelist {
129 	int32_t	kf_spare0;
130 	int16_t	kf_type;
131 	int16_t	kf_spare1;
132 	XSIMPLEQ_ENTRY(kmem_freelist) kf_flist;
133 };
134 
135 #ifdef DIAGNOSTIC
136 /*
137  * This structure provides a set of masks to catch unaligned frees.
138  */
139 const long addrmask[] = { 0,
140 	0x00000001, 0x00000003, 0x00000007, 0x0000000f,
141 	0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
142 	0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
143 	0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
144 };
145 
146 #endif /* DIAGNOSTIC */
147 
148 #ifndef SMALL_KERNEL
149 struct timeval malloc_errintvl = { 5, 0 };
150 struct timeval malloc_lasterr;
151 #endif
152 
153 /*
154  * Allocate a block of memory
155  */
156 void *
157 malloc(size_t size, int type, int flags)
158 {
159 	struct kmembuckets *kbp;
160 	struct kmemusage *kup;
161 	struct kmem_freelist *freep;
162 	long indx, npg, allocsize;
163 	caddr_t va, cp;
164 	int s;
165 #ifdef DIAGNOSTIC
166 	int freshalloc;
167 	char *savedtype;
168 #endif
169 #ifdef KMEMSTATS
170 	struct kmemstats *ksp = &kmemstats[type];
171 	int wake;
172 
173 	if (((unsigned long)type) <= 1 || ((unsigned long)type) >= M_LAST)
174 		panic("malloc: bogus type %d", type);
175 #endif
176 
177 	KASSERT(flags & (M_WAITOK | M_NOWAIT));
178 
179 #ifdef DIAGNOSTIC
180 	if ((flags & M_NOWAIT) == 0) {
181 		extern int pool_debug;
182 		assertwaitok();
183 		if (pool_debug == 2)
184 			yield();
185 	}
186 #endif
187 
188 	if (size > 65535 * PAGE_SIZE) {
189 		if (flags & M_CANFAIL) {
190 #ifndef SMALL_KERNEL
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", 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_nsec(ksp, &malloc_mtx, PSWP+2, memname[type], INFSLP);
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 
363 	TRACEPOINT(uvm, malloc, type, va, size, flags);
364 
365 	return (va);
366 }
367 
368 /*
369  * Free a block of memory allocated by malloc.
370  */
371 void
372 free(void *addr, int type, size_t freedsize)
373 {
374 	struct kmembuckets *kbp;
375 	struct kmemusage *kup;
376 	struct kmem_freelist *freep;
377 	long size;
378 	int s;
379 #ifdef DIAGNOSTIC
380 	long alloc;
381 #endif
382 #ifdef KMEMSTATS
383 	struct kmemstats *ksp = &kmemstats[type];
384 	int wake;
385 #endif
386 
387 	if (addr == NULL)
388 		return;
389 
390 #ifdef DIAGNOSTIC
391 	if (addr < (void *)kmembase || addr >= (void *)kmemlimit)
392 		panic("free: non-malloced addr %p type %s", addr,
393 		    memname[type]);
394 #endif
395 
396 	TRACEPOINT(uvm, free, type, addr, freedsize);
397 
398 	mtx_enter(&malloc_mtx);
399 	kup = btokup(addr);
400 	size = 1 << kup->ku_indx;
401 	kbp = &bucket[kup->ku_indx];
402 	if (size > MAXALLOCSAVE)
403 		size = kup->ku_pagecnt << PAGE_SHIFT;
404 #ifdef DIAGNOSTIC
405 #if 0
406 	if (freedsize == 0) {
407 		static int zerowarnings;
408 		if (zerowarnings < 5) {
409 			zerowarnings++;
410 			printf("free with zero size: (%d)\n", type);
411 #ifdef DDB
412 			db_stack_dump();
413 #endif
414 	}
415 #endif
416 	if (freedsize != 0 && freedsize > size)
417 		panic("free: size too large %zu > %ld (%p) type %s",
418 		    freedsize, size, addr, memname[type]);
419 	if (freedsize != 0 && size > MINALLOCSIZE && freedsize <= size / 2)
420 		panic("free: size too small %zu <= %ld / 2 (%p) type %s",
421 		    freedsize, size, addr, memname[type]);
422 	/*
423 	 * Check for returns of data that do not point to the
424 	 * beginning of the allocation.
425 	 */
426 	if (size > PAGE_SIZE)
427 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
428 	else
429 		alloc = addrmask[kup->ku_indx];
430 	if (((u_long)addr & alloc) != 0)
431 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
432 			addr, size, memname[type], alloc);
433 #endif /* DIAGNOSTIC */
434 	if (size > MAXALLOCSAVE) {
435 		u_short pagecnt = kup->ku_pagecnt;
436 
437 		kup->ku_indx = 0;
438 		kup->ku_pagecnt = 0;
439 		mtx_leave(&malloc_mtx);
440 		s = splvm();
441 		uvm_km_free(kmem_map, (vaddr_t)addr, ptoa(pagecnt));
442 		splx(s);
443 #ifdef KMEMSTATS
444 		mtx_enter(&malloc_mtx);
445 		ksp->ks_memuse -= size;
446 		wake = ksp->ks_memuse + size >= ksp->ks_limit &&
447 		    ksp->ks_memuse < ksp->ks_limit;
448 		ksp->ks_inuse--;
449 		kbp->kb_total -= 1;
450 		mtx_leave(&malloc_mtx);
451 		if (wake)
452 			wakeup(ksp);
453 #endif
454 		return;
455 	}
456 	freep = (struct kmem_freelist *)addr;
457 #ifdef DIAGNOSTIC
458 	/*
459 	 * Check for multiple frees. Use a quick check to see if
460 	 * it looks free before laboriously searching the freelist.
461 	 */
462 	if (freep->kf_spare0 == poison_value(freep)) {
463 		struct kmem_freelist *fp;
464 		XSIMPLEQ_FOREACH(fp, &kbp->kb_freelist, kf_flist) {
465 			if (addr != fp)
466 				continue;
467 			printf("multiply freed item %p\n", addr);
468 			panic("free: duplicated free");
469 		}
470 	}
471 	/*
472 	 * Copy in known text to detect modification after freeing
473 	 * and to make it look free. Also, save the type being freed
474 	 * so we can list likely culprit if modification is detected
475 	 * when the object is reallocated.
476 	 */
477 	poison_mem(addr, size);
478 	freep->kf_spare0 = poison_value(freep);
479 
480 	freep->kf_type = type;
481 #endif /* DIAGNOSTIC */
482 #ifdef KMEMSTATS
483 	kup->ku_freecnt++;
484 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
485 		if (kup->ku_freecnt > kbp->kb_elmpercl)
486 			panic("free: multiple frees");
487 		else if (kbp->kb_totalfree > kbp->kb_highwat)
488 			kbp->kb_couldfree++;
489 	}
490 	kbp->kb_totalfree++;
491 	ksp->ks_memuse -= size;
492 	wake = ksp->ks_memuse + size >= ksp->ks_limit &&
493 	    ksp->ks_memuse < ksp->ks_limit;
494 	ksp->ks_inuse--;
495 #endif
496 	XSIMPLEQ_INSERT_TAIL(&kbp->kb_freelist, freep, kf_flist);
497 	mtx_leave(&malloc_mtx);
498 #ifdef KMEMSTATS
499 	if (wake)
500 		wakeup(ksp);
501 #endif
502 }
503 
504 /*
505  * Compute the number of pages that kmem_map will map, that is,
506  * the size of the kernel malloc arena.
507  */
508 void
509 kmeminit_nkmempages(void)
510 {
511 	u_int npages;
512 
513 	if (nkmempages != 0) {
514 		/*
515 		 * It's already been set (by us being here before, or
516 		 * by patching or kernel config options), bail out now.
517 		 */
518 		return;
519 	}
520 
521 	/*
522 	 * We can't initialize these variables at compilation time, since
523 	 * the page size may not be known (on sparc GENERIC kernels, for
524 	 * example). But we still want the MD code to be able to provide
525 	 * better values.
526 	 */
527 	if (nkmempages_min == 0)
528 		nkmempages_min = NKMEMPAGES_MIN;
529 	if (nkmempages_max == 0)
530 		nkmempages_max = NKMEMPAGES_MAX;
531 
532 	/*
533 	 * We use the following (simple) formula:
534 	 *
535 	 *	- Starting point is physical memory / 4.
536 	 *
537 	 *	- Clamp it down to nkmempages_max.
538 	 *
539 	 *	- Round it up to nkmempages_min.
540 	 */
541 	npages = physmem / 4;
542 
543 	if (npages > nkmempages_max)
544 		npages = nkmempages_max;
545 
546 	if (npages < nkmempages_min)
547 		npages = nkmempages_min;
548 
549 	nkmempages = npages;
550 }
551 
552 /*
553  * Initialize the kernel memory allocator
554  */
555 void
556 kmeminit(void)
557 {
558 	vaddr_t base, limit;
559 	long indx;
560 
561 #ifdef DIAGNOSTIC
562 	if (sizeof(struct kmem_freelist) > (1 << MINBUCKET))
563 		panic("kmeminit: minbucket too small/struct freelist too big");
564 #endif
565 
566 	/*
567 	 * Compute the number of kmem_map pages, if we have not
568 	 * done so already.
569 	 */
570 	kmeminit_nkmempages();
571 	base = vm_map_min(kernel_map);
572 	kmem_map = uvm_km_suballoc(kernel_map, &base, &limit,
573 	    (vsize_t)nkmempages << PAGE_SHIFT,
574 #ifdef KVA_GUARDPAGES
575 	    VM_MAP_INTRSAFE | VM_MAP_GUARDPAGES,
576 #else
577 	    VM_MAP_INTRSAFE,
578 #endif
579 	    FALSE, &kmem_map_store);
580 	kmembase = (char *)base;
581 	kmemlimit = (char *)limit;
582 	kmemusage = km_alloc(round_page(nkmempages * sizeof(struct kmemusage)),
583 	    &kv_any, &kp_zero, &kd_waitok);
584 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
585 		XSIMPLEQ_INIT(&bucket[indx].kb_freelist);
586 	}
587 #ifdef KMEMSTATS
588 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
589 		if (1 << indx >= PAGE_SIZE)
590 			bucket[indx].kb_elmpercl = 1;
591 		else
592 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
593 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
594 	}
595 	for (indx = 0; indx < M_LAST; indx++)
596 		kmemstats[indx].ks_limit = nkmempages * PAGE_SIZE * 6 / 10;
597 #endif
598 }
599 
600 /*
601  * Return kernel malloc statistics information.
602  */
603 int
604 sysctl_malloc(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
605     size_t newlen, struct proc *p)
606 {
607 	struct kmembuckets kb;
608 #ifdef KMEMSTATS
609 	struct kmemstats km;
610 #endif
611 #if defined(KMEMSTATS) || defined(DIAGNOSTIC)
612 	int error;
613 #endif
614 	int i, siz;
615 
616 	if (namelen != 2 && name[0] != KERN_MALLOC_BUCKETS &&
617 	    name[0] != KERN_MALLOC_KMEMNAMES)
618 		return (ENOTDIR);		/* overloaded */
619 
620 	switch (name[0]) {
621 	case KERN_MALLOC_BUCKETS:
622 		/* Initialize the first time */
623 		if (buckstring_init == 0) {
624 			buckstring_init = 1;
625 			memset(buckstring, 0, sizeof(buckstring));
626 			for (siz = 0, i = MINBUCKET; i < MINBUCKET + 16; i++) {
627 				snprintf(buckstring + siz,
628 				    sizeof buckstring - siz,
629 				    "%d,", (u_int)(1<<i));
630 				siz += strlen(buckstring + siz);
631 			}
632 			/* Remove trailing comma */
633 			if (siz)
634 				buckstring[siz - 1] = '\0';
635 		}
636 		return (sysctl_rdstring(oldp, oldlenp, newp, buckstring));
637 
638 	case KERN_MALLOC_BUCKET:
639 		mtx_enter(&malloc_mtx);
640 		memcpy(&kb, &bucket[BUCKETINDX(name[1])], sizeof(kb));
641 		mtx_leave(&malloc_mtx);
642 		memset(&kb.kb_freelist, 0, sizeof(kb.kb_freelist));
643 		return (sysctl_rdstruct(oldp, oldlenp, newp, &kb, sizeof(kb)));
644 	case KERN_MALLOC_KMEMSTATS:
645 #ifdef KMEMSTATS
646 		if ((name[1] < 0) || (name[1] >= M_LAST))
647 			return (EINVAL);
648 		mtx_enter(&malloc_mtx);
649 		memcpy(&km, &kmemstats[name[1]], sizeof(km));
650 		mtx_leave(&malloc_mtx);
651 		return (sysctl_rdstruct(oldp, oldlenp, newp, &km, sizeof(km)));
652 #else
653 		return (EOPNOTSUPP);
654 #endif
655 	case KERN_MALLOC_KMEMNAMES:
656 #if defined(KMEMSTATS) || defined(DIAGNOSTIC)
657 		error = rw_enter(&sysctl_kmemlock, RW_WRITE|RW_INTR);
658 		if (error)
659 			return (error);
660 		if (memall == NULL) {
661 			int totlen;
662 
663 			/* Figure out how large a buffer we need */
664 			for (totlen = 0, i = 0; i < M_LAST; i++) {
665 				if (memname[i])
666 					totlen += strlen(memname[i]);
667 				totlen++;
668 			}
669 			memall = malloc(totlen + M_LAST, M_SYSCTL,
670 			    M_WAITOK|M_ZERO);
671 			for (siz = 0, i = 0; i < M_LAST; i++) {
672 				snprintf(memall + siz,
673 				    totlen + M_LAST - siz,
674 				    "%s,", memname[i] ? memname[i] : "");
675 				siz += strlen(memall + siz);
676 			}
677 			/* Remove trailing comma */
678 			if (siz)
679 				memall[siz - 1] = '\0';
680 
681 			/* Now, convert all spaces to underscores */
682 			for (i = 0; i < totlen; i++)
683 				if (memall[i] == ' ')
684 					memall[i] = '_';
685 		}
686 		rw_exit_write(&sysctl_kmemlock);
687 		return (sysctl_rdstring(oldp, oldlenp, newp, memall));
688 #else
689 		return (EOPNOTSUPP);
690 #endif
691 	default:
692 		return (EOPNOTSUPP);
693 	}
694 	/* NOTREACHED */
695 }
696 
697 #if defined(DDB)
698 
699 void
700 malloc_printit(
701     int (*pr)(const char *, ...) __attribute__((__format__(__kprintf__,1,2))))
702 {
703 #ifdef KMEMSTATS
704 	struct kmemstats *km;
705 	int i;
706 
707 	(*pr)("%15s %5s  %6s  %7s  %6s %9s %8s\n",
708 	    "Type", "InUse", "MemUse", "HighUse", "Limit", "Requests",
709 	    "Type Lim");
710 	for (i = 0, km = kmemstats; i < M_LAST; i++, km++) {
711 		if (!km->ks_calls || !memname[i])
712 			continue;
713 
714 		(*pr)("%15s %5ld %6ldK %7ldK %6ldK %9ld %8d\n",
715 		    memname[i], km->ks_inuse, km->ks_memuse / 1024,
716 		    km->ks_maxused / 1024, km->ks_limit / 1024,
717 		    km->ks_calls, km->ks_limblocks);
718 	}
719 #else
720 	(*pr)("No KMEMSTATS compiled in\n");
721 #endif
722 }
723 #endif /* DDB */
724 
725 /*
726  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
727  *
728  * Permission to use, copy, modify, and distribute this software for any
729  * purpose with or without fee is hereby granted, provided that the above
730  * copyright notice and this permission notice appear in all copies.
731  *
732  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
733  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
734  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
735  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
736  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
737  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
738  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
739  */
740 
741 /*
742  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
743  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
744  */
745 #define MUL_NO_OVERFLOW	(1UL << (sizeof(size_t) * 4))
746 
747 void *
748 mallocarray(size_t nmemb, size_t size, int type, int flags)
749 {
750 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
751 	    nmemb > 0 && SIZE_MAX / nmemb < size) {
752 		if (flags & M_CANFAIL)
753 			return (NULL);
754 		panic("mallocarray: overflow %zu * %zu", nmemb, size);
755 	}
756 	return (malloc(size * nmemb, type, flags));
757 }
758