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