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