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