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