xref: /openbsd-src/sys/kern/kern_malloc.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /*	$OpenBSD: kern_malloc.c,v 1.114 2014/07/13 14:59:28 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/proc.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/systm.h>
40 #include <sys/sysctl.h>
41 #include <sys/time.h>
42 #include <sys/rwlock.h>
43 
44 #include <dev/rndvar.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 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 	int s;
157 	caddr_t va, cp;
158 #ifdef DIAGNOSTIC
159 	int freshalloc;
160 	char *savedtype;
161 #endif
162 #ifdef KMEMSTATS
163 	struct kmemstats *ksp = &kmemstats[type];
164 
165 	if (((unsigned long)type) <= 1 || ((unsigned long)type) >= M_LAST)
166 		panic("malloc - bogus type");
167 #endif
168 
169 	KASSERT(flags & (M_WAITOK | M_NOWAIT));
170 
171 	if ((flags & M_NOWAIT) == 0) {
172 		extern int pool_debug;
173 #ifdef DIAGNOSTIC
174 		assertwaitok();
175 		if (pool_debug == 2)
176 			yield();
177 #endif
178 		if (!cold && pool_debug) {
179 			KERNEL_UNLOCK();
180 			KERNEL_LOCK();
181 		}
182 	}
183 
184 #ifdef MALLOC_DEBUG
185 	if (debug_malloc(size, type, flags, (void **)&va)) {
186 		if ((flags & M_ZERO) && va != NULL)
187 			memset(va, 0, size);
188 		return (va);
189 	}
190 #endif
191 
192 	if (size > 65535 * PAGE_SIZE) {
193 		if (flags & M_CANFAIL) {
194 #ifndef SMALL_KERNEL
195 			if (ratecheck(&malloc_lasterr, &malloc_errintvl))
196 				printf("malloc(): allocation too large, "
197 				    "type = %d, size = %lu\n", type, size);
198 #endif
199 			return (NULL);
200 		} else
201 			panic("malloc: allocation too large, "
202 			    "type = %d, size = %lu\n", type, size);
203 	}
204 
205 	indx = BUCKETINDX(size);
206 	kbp = &bucket[indx];
207 	s = splvm();
208 #ifdef KMEMSTATS
209 	while (ksp->ks_memuse >= ksp->ks_limit) {
210 		if (flags & M_NOWAIT) {
211 			splx(s);
212 			return (NULL);
213 		}
214 		if (ksp->ks_limblocks < 65535)
215 			ksp->ks_limblocks++;
216 		tsleep(ksp, PSWP+2, memname[type], 0);
217 	}
218 	ksp->ks_size |= 1 << indx;
219 #endif
220 	if (size > MAXALLOCSAVE)
221 		allocsize = round_page(size);
222 	else
223 		allocsize = 1 << indx;
224 	if (XSIMPLEQ_FIRST(&kbp->kb_freelist) == NULL) {
225 		npg = atop(round_page(allocsize));
226 		va = (caddr_t)uvm_km_kmemalloc_pla(kmem_map, NULL,
227 		    (vsize_t)ptoa(npg), 0,
228 		    ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) |
229 		    ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 0),
230 		    no_constraint.ucr_low, no_constraint.ucr_high,
231 		    0, 0, 0);
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 			splx(s);
244 			return (NULL);
245 		}
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 #ifdef KMEMSTATS
257 			ksp->ks_memuse += allocsize;
258 #endif
259 			goto out;
260 		}
261 #ifdef KMEMSTATS
262 		kup->ku_freecnt = kbp->kb_elmpercl;
263 		kbp->kb_totalfree += kbp->kb_elmpercl;
264 #endif
265 		cp = va + (npg * PAGE_SIZE) - allocsize;
266 		for (;;) {
267 			freep = (struct kmem_freelist *)cp;
268 #ifdef DIAGNOSTIC
269 			/*
270 			 * Copy in known text to detect modification
271 			 * after freeing.
272 			 */
273 			poison_mem(cp, allocsize);
274 			freep->kf_type = M_FREE;
275 #endif /* DIAGNOSTIC */
276 			XSIMPLEQ_INSERT_HEAD(&kbp->kb_freelist, freep, kf_flist);
277 			if (cp <= va)
278 				break;
279 			cp -= allocsize;
280 		}
281 	} else {
282 #ifdef DIAGNOSTIC
283 		freshalloc = 0;
284 #endif
285 	}
286 	freep = XSIMPLEQ_FIRST(&kbp->kb_freelist);
287 	XSIMPLEQ_REMOVE_HEAD(&kbp->kb_freelist, kf_flist);
288 	va = (caddr_t)freep;
289 #ifdef DIAGNOSTIC
290 	savedtype = (unsigned)freep->kf_type < M_LAST ?
291 		memname[freep->kf_type] : "???";
292 	if (freshalloc == 0 && XSIMPLEQ_FIRST(&kbp->kb_freelist)) {
293 		int rv;
294 		vaddr_t addr = (vaddr_t)XSIMPLEQ_FIRST(&kbp->kb_freelist);
295 
296 		vm_map_lock(kmem_map);
297 		rv = uvm_map_checkprot(kmem_map, addr,
298 		    addr + sizeof(struct kmem_freelist), VM_PROT_WRITE);
299 		vm_map_unlock(kmem_map);
300 
301 		if (!rv)  {
302 			printf("%s %zd of object %p size 0x%lx %s %s"
303 			    " (invalid addr %p)\n",
304 			    "Data modified on freelist: word",
305 			    (int32_t *)&addr - (int32_t *)kbp, va, size,
306 			    "previous type", savedtype, (void *)addr);
307 		}
308 	}
309 
310 	/* Fill the fields that we've used with poison */
311 	poison_mem(freep, sizeof(*freep));
312 
313 	/* and check that the data hasn't been modified. */
314 	if (freshalloc == 0) {
315 		size_t pidx;
316 		uint32_t pval;
317 		if (poison_check(va, allocsize, &pidx, &pval)) {
318 			panic("%s %zd of object %p size 0x%lx %s %s"
319 			    " (0x%x != 0x%x)\n",
320 			    "Data modified on freelist: word",
321 			    pidx, va, size, "previous type",
322 			    savedtype, ((int32_t*)va)[pidx], pval);
323 		}
324 	}
325 
326 	freep->kf_spare0 = 0;
327 #endif /* DIAGNOSTIC */
328 #ifdef KMEMSTATS
329 	kup = btokup(va);
330 	if (kup->ku_indx != indx)
331 		panic("malloc: wrong bucket");
332 	if (kup->ku_freecnt == 0)
333 		panic("malloc: lost data");
334 	kup->ku_freecnt--;
335 	kbp->kb_totalfree--;
336 	ksp->ks_memuse += 1 << indx;
337 out:
338 	kbp->kb_calls++;
339 	ksp->ks_inuse++;
340 	ksp->ks_calls++;
341 	if (ksp->ks_memuse > ksp->ks_maxused)
342 		ksp->ks_maxused = ksp->ks_memuse;
343 #else
344 out:
345 #endif
346 	splx(s);
347 
348 	if ((flags & M_ZERO) && va != NULL)
349 		memset(va, 0, size);
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 #endif
370 
371 	if (addr == NULL)
372 		return;
373 
374 #ifdef MALLOC_DEBUG
375 	if (debug_free(addr, type))
376 		return;
377 #endif
378 
379 #ifdef DIAGNOSTIC
380 	if (addr < (void *)kmembase || addr >= (void *)kmemlimit)
381 		panic("free: non-malloced addr %p type %s", addr,
382 		    memname[type]);
383 #endif
384 
385 	kup = btokup(addr);
386 	size = 1 << kup->ku_indx;
387 	kbp = &bucket[kup->ku_indx];
388 	s = splvm();
389 #ifdef DIAGNOSTIC
390 	if (freedsize != 0 && freedsize > size)
391 		panic("freed too much: %zu > %ld (%p)", freedsize, size, addr);
392 	if (freedsize != 0 && size > MINALLOCSIZE && freedsize < size / 2)
393 		panic("freed too little: %zu < %ld / 2 (%p)",
394 		    freedsize, size, addr);
395 	/*
396 	 * Check for returns of data that do not point to the
397 	 * beginning of the allocation.
398 	 */
399 	if (size > PAGE_SIZE)
400 		alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
401 	else
402 		alloc = addrmask[kup->ku_indx];
403 	if (((u_long)addr & alloc) != 0)
404 		panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
405 			addr, size, memname[type], alloc);
406 #endif /* DIAGNOSTIC */
407 	if (size > MAXALLOCSAVE) {
408 		uvm_km_free(kmem_map, (vaddr_t)addr, ptoa(kup->ku_pagecnt));
409 #ifdef KMEMSTATS
410 		size = kup->ku_pagecnt << PAGE_SHIFT;
411 		ksp->ks_memuse -= size;
412 		kup->ku_indx = 0;
413 		kup->ku_pagecnt = 0;
414 		if (ksp->ks_memuse + size >= ksp->ks_limit &&
415 		    ksp->ks_memuse < ksp->ks_limit)
416 			wakeup(ksp);
417 		ksp->ks_inuse--;
418 		kbp->kb_total -= 1;
419 #endif
420 		splx(s);
421 		return;
422 	}
423 	freep = (struct kmem_freelist *)addr;
424 #ifdef DIAGNOSTIC
425 	/*
426 	 * Check for multiple frees. Use a quick check to see if
427 	 * it looks free before laboriously searching the freelist.
428 	 */
429 	if (freep->kf_spare0 == poison_value(freep)) {
430 		struct kmem_freelist *fp;
431 		XSIMPLEQ_FOREACH(fp, &kbp->kb_freelist, kf_flist) {
432 			if (addr != fp)
433 				continue;
434 			printf("multiply freed item %p\n", addr);
435 			panic("free: duplicated free");
436 		}
437 	}
438 	/*
439 	 * Copy in known text to detect modification after freeing
440 	 * and to make it look free. Also, save the type being freed
441 	 * so we can list likely culprit if modification is detected
442 	 * when the object is reallocated.
443 	 */
444 	poison_mem(addr, size);
445 	freep->kf_spare0 = poison_value(freep);
446 
447 	freep->kf_type = type;
448 #endif /* DIAGNOSTIC */
449 #ifdef KMEMSTATS
450 	kup->ku_freecnt++;
451 	if (kup->ku_freecnt >= kbp->kb_elmpercl) {
452 		if (kup->ku_freecnt > kbp->kb_elmpercl)
453 			panic("free: multiple frees");
454 		else if (kbp->kb_totalfree > kbp->kb_highwat)
455 			kbp->kb_couldfree++;
456 	}
457 	kbp->kb_totalfree++;
458 	ksp->ks_memuse -= size;
459 	if (ksp->ks_memuse + size >= ksp->ks_limit &&
460 	    ksp->ks_memuse < ksp->ks_limit)
461 		wakeup(ksp);
462 	ksp->ks_inuse--;
463 #endif
464 	XSIMPLEQ_INSERT_TAIL(&kbp->kb_freelist, freep, kf_flist);
465 	splx(s);
466 }
467 
468 /*
469  * Compute the number of pages that kmem_map will map, that is,
470  * the size of the kernel malloc arena.
471  */
472 void
473 kmeminit_nkmempages(void)
474 {
475 	u_int npages;
476 
477 	if (nkmempages != 0) {
478 		/*
479 		 * It's already been set (by us being here before, or
480 		 * by patching or kernel config options), bail out now.
481 		 */
482 		return;
483 	}
484 
485 	/*
486 	 * We can't initialize these variables at compilation time, since
487 	 * the page size may not be known (on sparc GENERIC kernels, for
488 	 * example). But we still want the MD code to be able to provide
489 	 * better values.
490 	 */
491 	if (nkmempages_min == 0)
492 		nkmempages_min = NKMEMPAGES_MIN;
493 	if (nkmempages_max == 0)
494 		nkmempages_max = NKMEMPAGES_MAX;
495 
496 	/*
497 	 * We use the following (simple) formula:
498 	 *
499 	 *	- Starting point is physical memory / 4.
500 	 *
501 	 *	- Clamp it down to nkmempages_max.
502 	 *
503 	 *	- Round it up to nkmempages_min.
504 	 */
505 	npages = physmem / 4;
506 
507 	if (npages > nkmempages_max)
508 		npages = nkmempages_max;
509 
510 	if (npages < nkmempages_min)
511 		npages = nkmempages_min;
512 
513 	nkmempages = npages;
514 }
515 
516 /*
517  * Initialize the kernel memory allocator
518  */
519 void
520 kmeminit(void)
521 {
522 	vaddr_t base, limit;
523 	long indx;
524 
525 #ifdef DIAGNOSTIC
526 	if (sizeof(struct kmem_freelist) > (1 << MINBUCKET))
527 		panic("kmeminit: minbucket too small/struct freelist too big");
528 #endif
529 
530 	/*
531 	 * Compute the number of kmem_map pages, if we have not
532 	 * done so already.
533 	 */
534 	kmeminit_nkmempages();
535 	base = vm_map_min(kernel_map);
536 	kmem_map = uvm_km_suballoc(kernel_map, &base, &limit,
537 	    (vsize_t)nkmempages << PAGE_SHIFT,
538 #ifdef KVA_GUARDPAGES
539 	    VM_MAP_INTRSAFE | VM_MAP_GUARDPAGES,
540 #else
541 	    VM_MAP_INTRSAFE,
542 #endif
543 	    FALSE, &kmem_map_store);
544 	kmembase = (char *)base;
545 	kmemlimit = (char *)limit;
546 	kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
547 		(vsize_t)(nkmempages * sizeof(struct kmemusage)));
548 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
549 		XSIMPLEQ_INIT(&bucket[indx].kb_freelist);
550 	}
551 #ifdef KMEMSTATS
552 	for (indx = 0; indx < MINBUCKET + 16; indx++) {
553 		if (1 << indx >= PAGE_SIZE)
554 			bucket[indx].kb_elmpercl = 1;
555 		else
556 			bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
557 		bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
558 	}
559 	for (indx = 0; indx < M_LAST; indx++)
560 		kmemstats[indx].ks_limit = nkmempages * PAGE_SIZE * 6 / 10;
561 #endif
562 #ifdef MALLOC_DEBUG
563 	debug_malloc_init();
564 #endif
565 }
566 
567 /*
568  * Return kernel malloc statistics information.
569  */
570 int
571 sysctl_malloc(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
572     size_t newlen, struct proc *p)
573 {
574 	struct kmembuckets kb;
575 	int i, siz;
576 
577 	if (namelen != 2 && name[0] != KERN_MALLOC_BUCKETS &&
578 	    name[0] != KERN_MALLOC_KMEMNAMES)
579 		return (ENOTDIR);		/* overloaded */
580 
581 	switch (name[0]) {
582 	case KERN_MALLOC_BUCKETS:
583 		/* Initialize the first time */
584 		if (buckstring_init == 0) {
585 			buckstring_init = 1;
586 			memset(buckstring, 0, sizeof(buckstring));
587 			for (siz = 0, i = MINBUCKET; i < MINBUCKET + 16; i++) {
588 				snprintf(buckstring + siz,
589 				    sizeof buckstring - siz,
590 				    "%d,", (u_int)(1<<i));
591 				siz += strlen(buckstring + siz);
592 			}
593 			/* Remove trailing comma */
594 			if (siz)
595 				buckstring[siz - 1] = '\0';
596 		}
597 		return (sysctl_rdstring(oldp, oldlenp, newp, buckstring));
598 
599 	case KERN_MALLOC_BUCKET:
600 		bcopy(&bucket[BUCKETINDX(name[1])], &kb, sizeof(kb));
601 		memset(&kb.kb_freelist, 0, sizeof(kb.kb_freelist));
602 		return (sysctl_rdstruct(oldp, oldlenp, newp, &kb, sizeof(kb)));
603 	case KERN_MALLOC_KMEMSTATS:
604 #ifdef KMEMSTATS
605 		if ((name[1] < 0) || (name[1] >= M_LAST))
606 			return (EINVAL);
607 		return (sysctl_rdstruct(oldp, oldlenp, newp,
608 		    &kmemstats[name[1]], sizeof(struct kmemstats)));
609 #else
610 		return (EOPNOTSUPP);
611 #endif
612 	case KERN_MALLOC_KMEMNAMES:
613 #if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES)
614 		if (memall == NULL) {
615 			int totlen;
616 
617 			i = rw_enter(&sysctl_kmemlock, RW_WRITE|RW_INTR);
618 			if (i)
619 				return (i);
620 
621 			/* Figure out how large a buffer we need */
622 			for (totlen = 0, i = 0; i < M_LAST; i++) {
623 				if (memname[i])
624 					totlen += strlen(memname[i]);
625 				totlen++;
626 			}
627 			memall = malloc(totlen + M_LAST, M_SYSCTL,
628 			    M_WAITOK|M_ZERO);
629 			for (siz = 0, i = 0; i < M_LAST; i++) {
630 				snprintf(memall + siz,
631 				    totlen + M_LAST - siz,
632 				    "%s,", memname[i] ? memname[i] : "");
633 				siz += strlen(memall + siz);
634 			}
635 			/* Remove trailing comma */
636 			if (siz)
637 				memall[siz - 1] = '\0';
638 
639 			/* Now, convert all spaces to underscores */
640 			for (i = 0; i < totlen; i++)
641 				if (memall[i] == ' ')
642 					memall[i] = '_';
643 			rw_exit_write(&sysctl_kmemlock);
644 		}
645 		return (sysctl_rdstring(oldp, oldlenp, newp, memall));
646 #else
647 		return (EOPNOTSUPP);
648 #endif
649 	default:
650 		return (EOPNOTSUPP);
651 	}
652 	/* NOTREACHED */
653 }
654 
655 /*
656  * Round up a size to how much malloc would actually allocate.
657  */
658 size_t
659 malloc_roundup(size_t sz)
660 {
661 	if (sz > MAXALLOCSAVE)
662 		return round_page(sz);
663 
664 	return (1 << BUCKETINDX(sz));
665 }
666 
667 #if defined(DDB)
668 #include <machine/db_machdep.h>
669 #include <ddb/db_interface.h>
670 #include <ddb/db_output.h>
671 
672 void
673 malloc_printit(
674     int (*pr)(const char *, ...) __attribute__((__format__(__kprintf__,1,2))))
675 {
676 #ifdef KMEMSTATS
677 	struct kmemstats *km;
678 	int i;
679 
680 	(*pr)("%15s %5s  %6s  %7s  %6s %9s %8s %8s\n",
681 	    "Type", "InUse", "MemUse", "HighUse", "Limit", "Requests",
682 	    "Type Lim", "Kern Lim");
683 	for (i = 0, km = kmemstats; i < M_LAST; i++, km++) {
684 		if (!km->ks_calls || !memname[i])
685 			continue;
686 
687 		(*pr)("%15s %5ld %6ldK %7ldK %6ldK %9ld %8d %8d\n",
688 		    memname[i], km->ks_inuse, km->ks_memuse / 1024,
689 		    km->ks_maxused / 1024, km->ks_limit / 1024,
690 		    km->ks_calls, km->ks_limblocks, km->ks_mapblocks);
691 	}
692 #else
693 	(*pr)("No KMEMSTATS compiled in\n");
694 #endif
695 }
696 #endif /* DDB */
697 
698 /*
699  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
700  *
701  * Permission to use, copy, modify, and distribute this software for any
702  * purpose with or without fee is hereby granted, provided that the above
703  * copyright notice and this permission notice appear in all copies.
704  *
705  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
706  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
707  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
708  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
709  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
710  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
711  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
712  */
713 
714 /*
715  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
716  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
717  */
718 #define MUL_NO_OVERFLOW	(1UL << (sizeof(size_t) * 4))
719 
720 void *
721 mallocarray(size_t nmemb, size_t size, int type, int flags)
722 {
723 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
724 	    nmemb > 0 && SIZE_MAX / nmemb < size) {
725 		if (flags & M_CANFAIL)
726 			return (NULL);
727 		panic("mallocarray overflow: %zu * %zu", nmemb, size);
728 	}
729 	return (malloc(size * nmemb, type, flags));
730 }
731