kern_malloc.c revision 95931
1/*
2 * Copyright (c) 1987, 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *	@(#)kern_malloc.c	8.3 (Berkeley) 1/4/94
34 * $FreeBSD: head/sys/kern/kern_malloc.c 95931 2002-05-02 09:07:04Z jeff $
35 */
36
37#include "opt_vm.h"
38
39#include <sys/param.h>
40#include <sys/systm.h>
41#include <sys/kernel.h>
42#include <sys/lock.h>
43#include <sys/malloc.h>
44#include <sys/mbuf.h>
45#include <sys/mutex.h>
46#include <sys/vmmeter.h>
47#include <sys/proc.h>
48#include <sys/sysctl.h>
49
50#include <vm/vm.h>
51#include <vm/vm_param.h>
52#include <vm/vm_kern.h>
53#include <vm/vm_extern.h>
54#include <vm/pmap.h>
55#include <vm/vm_map.h>
56#include <vm/uma.h>
57#include <vm/uma_int.h>
58#include <vm/uma_dbg.h>
59
60#if defined(INVARIANTS) && defined(__i386__)
61#include <machine/cpu.h>
62#endif
63
64/*
65 * When realloc() is called, if the new size is sufficiently smaller than
66 * the old size, realloc() will allocate a new, smaller block to avoid
67 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
68 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
69 */
70#ifndef REALLOC_FRACTION
71#define	REALLOC_FRACTION	1	/* new block if <= half the size */
72#endif
73
74MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
75MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
76MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
77
78MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
79MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
80
81static void kmeminit(void *);
82SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
83
84static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
85
86static struct malloc_type *kmemstatistics;
87static char *kmembase;
88static char *kmemlimit;
89
90#define KMEM_ZSHIFT	4
91#define KMEM_ZBASE	16
92#define KMEM_ZMASK	(KMEM_ZBASE - 1)
93
94#define KMEM_ZMAX	65536
95#define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
96static u_int8_t kmemsize[KMEM_ZSIZE + 1];
97
98/* These won't be powers of two for long */
99struct {
100	int kz_size;
101	char *kz_name;
102	uma_zone_t kz_zone;
103} kmemzones[] = {
104	{16, "16", NULL},
105	{32, "32", NULL},
106	{64, "64", NULL},
107	{128, "128", NULL},
108	{256, "256", NULL},
109	{512, "512", NULL},
110	{1024, "1024", NULL},
111	{2048, "2048", NULL},
112	{4096, "4096", NULL},
113	{8192, "8192", NULL},
114	{16384, "16384", NULL},
115	{32768, "32768", NULL},
116	{65536, "65536", NULL},
117	{0, NULL},
118};
119
120u_int vm_kmem_size;
121
122/*
123 * The malloc_mtx protects the kmemstatistics linked list as well as the
124 * mallochash.
125 */
126
127struct mtx malloc_mtx;
128
129#ifdef MALLOC_PROFILE
130uint64_t krequests[KMEM_ZSIZE + 1];
131
132static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
133#endif
134
135static int sysctl_kern_malloc(SYSCTL_HANDLER_ARGS);
136
137/*
138 *	malloc:
139 *
140 *	Allocate a block of memory.
141 *
142 *	If M_NOWAIT is set, this routine will not block and return NULL if
143 *	the allocation fails.
144 */
145void *
146malloc(size, type, flags)
147	unsigned long size;
148	struct malloc_type *type;
149	int flags;
150{
151	int indx;
152	caddr_t va;
153	uma_zone_t zone;
154	register struct malloc_type *ksp = type;
155
156#if 0
157	if (size == 0)
158		Debugger("zero size malloc");
159#endif
160#if defined(INVARIANTS)
161	if (flags == M_WAITOK)
162		KASSERT(curthread->td_intr_nesting_level == 0,
163		   ("malloc(M_WAITOK) in interrupt context"));
164#endif
165	if (size <= KMEM_ZMAX) {
166		if (size & KMEM_ZMASK)
167			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
168		indx = kmemsize[size >> KMEM_ZSHIFT];
169		zone = kmemzones[indx].kz_zone;
170#ifdef MALLOC_PROFILE
171		krequests[size >> KMEM_ZSHIFT]++;
172#endif
173		va = uma_zalloc(zone, flags);
174		mtx_lock(&ksp->ks_mtx);
175		if (va == NULL)
176			goto out;
177
178		ksp->ks_size |= 1 << indx;
179		size = zone->uz_size;
180	} else {
181		size = roundup(size, PAGE_SIZE);
182		zone = NULL;
183		va = uma_large_malloc(size, flags);
184		mtx_lock(&ksp->ks_mtx);
185		if (va == NULL)
186			goto out;
187	}
188	ksp->ks_memuse += size;
189	ksp->ks_inuse++;
190out:
191	ksp->ks_calls++;
192	if (ksp->ks_memuse > ksp->ks_maxused)
193		ksp->ks_maxused = ksp->ks_memuse;
194
195	mtx_unlock(&ksp->ks_mtx);
196	return ((void *) va);
197}
198
199/*
200 *	free:
201 *
202 *	Free a block of memory allocated by malloc.
203 *
204 *	This routine may not block.
205 */
206void
207free(addr, type)
208	void *addr;
209	struct malloc_type *type;
210{
211	uma_slab_t slab;
212	void *mem;
213	u_long size;
214	register struct malloc_type *ksp = type;
215
216	/* free(NULL, ...) does nothing */
217	if (addr == NULL)
218		return;
219
220	size = 0;
221
222	mem = (void *)((u_long)addr & (~UMA_SLAB_MASK));
223	mtx_lock(&malloc_mtx);
224	slab = hash_sfind(mallochash, mem);
225	mtx_unlock(&malloc_mtx);
226
227	if (slab == NULL)
228		panic("free: address %p(%p) has not been allocated.\n",
229		    addr, mem);
230
231	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
232#ifdef INVARIANTS
233		struct malloc_type **mtp = addr;
234#endif
235		size = slab->us_zone->uz_size;
236#ifdef INVARIANTS
237		/*
238		 * Cache a pointer to the malloc_type that most recently freed
239		 * this memory here.  This way we know who is most likely to
240		 * have stepped on it later.
241		 *
242		 * This code assumes that size is a multiple of 8 bytes for
243		 * 64 bit machines
244		 */
245		mtp = (struct malloc_type **)
246		    ((unsigned long)mtp & ~UMA_ALIGN_PTR);
247		mtp += (size - sizeof(struct malloc_type *)) /
248		    sizeof(struct malloc_type *);
249		*mtp = type;
250#endif
251		uma_zfree_arg(slab->us_zone, addr, slab);
252	} else {
253		size = slab->us_size;
254		uma_large_free(slab);
255	}
256	mtx_lock(&ksp->ks_mtx);
257	ksp->ks_memuse -= size;
258	ksp->ks_inuse--;
259	mtx_unlock(&ksp->ks_mtx);
260}
261
262/*
263 *	realloc: change the size of a memory block
264 */
265void *
266realloc(addr, size, type, flags)
267	void *addr;
268	unsigned long size;
269	struct malloc_type *type;
270	int flags;
271{
272	uma_slab_t slab;
273	unsigned long alloc;
274	void *newaddr;
275
276	/* realloc(NULL, ...) is equivalent to malloc(...) */
277	if (addr == NULL)
278		return (malloc(size, type, flags));
279
280	mtx_lock(&malloc_mtx);
281	slab = hash_sfind(mallochash,
282	    (void *)((u_long)addr & ~(UMA_SLAB_MASK)));
283	mtx_unlock(&malloc_mtx);
284
285	/* Sanity check */
286	KASSERT(slab != NULL,
287	    ("realloc: address %p out of range", (void *)addr));
288
289	/* Get the size of the original block */
290	if (slab->us_zone)
291		alloc = slab->us_zone->uz_size;
292	else
293		alloc = slab->us_size;
294
295	/* Reuse the original block if appropriate */
296	if (size <= alloc
297	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
298		return (addr);
299
300	/* Allocate a new, bigger (or smaller) block */
301	if ((newaddr = malloc(size, type, flags)) == NULL)
302		return (NULL);
303
304	/* Copy over original contents */
305	bcopy(addr, newaddr, min(size, alloc));
306	free(addr, type);
307	return (newaddr);
308}
309
310/*
311 *	reallocf: same as realloc() but free memory on failure.
312 */
313void *
314reallocf(addr, size, type, flags)
315	void *addr;
316	unsigned long size;
317	struct malloc_type *type;
318	int flags;
319{
320	void *mem;
321
322	if ((mem = realloc(addr, size, type, flags)) == NULL)
323		free(addr, type);
324	return (mem);
325}
326
327/*
328 * Initialize the kernel memory allocator
329 */
330/* ARGSUSED*/
331static void
332kmeminit(dummy)
333	void *dummy;
334{
335	u_int8_t indx;
336	u_long npg;
337	u_long mem_size;
338	void *hashmem;
339	u_long hashsize;
340	int highbit;
341	int bits;
342	int i;
343
344	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
345
346	/*
347	 * Try to auto-tune the kernel memory size, so that it is
348	 * more applicable for a wider range of machine sizes.
349	 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
350	 * a VM_KMEM_SIZE of 12MB is a fair compromise.  The
351	 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
352	 * available, and on an X86 with a total KVA space of 256MB,
353	 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
354	 *
355	 * Note that the kmem_map is also used by the zone allocator,
356	 * so make sure that there is enough space.
357	 */
358	vm_kmem_size = VM_KMEM_SIZE;
359	mem_size = cnt.v_page_count * PAGE_SIZE;
360
361#if defined(VM_KMEM_SIZE_SCALE)
362	if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
363		vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
364#endif
365
366#if defined(VM_KMEM_SIZE_MAX)
367	if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
368		vm_kmem_size = VM_KMEM_SIZE_MAX;
369#endif
370
371	/* Allow final override from the kernel environment */
372	TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
373
374	/*
375	 * Limit kmem virtual size to twice the physical memory.
376	 * This allows for kmem map sparseness, but limits the size
377	 * to something sane. Be careful to not overflow the 32bit
378	 * ints while doing the check.
379	 */
380	if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE))
381		vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
382
383	/*
384	 * In mbuf_init(), we set up submaps for mbufs and clusters, in which
385	 * case we rounddown() (nmbufs * MSIZE) and (nmbclusters * MCLBYTES),
386	 * respectively. Mathematically, this means that what we do here may
387	 * amount to slightly more address space than we need for the submaps,
388	 * but it never hurts to have an extra page in kmem_map.
389	 */
390	npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + nmbcnt *
391	    sizeof(u_int) + vm_kmem_size) / PAGE_SIZE;
392
393	kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
394		(vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
395	kmem_map->system_map = 1;
396
397	hashsize = npg * sizeof(void *);
398
399	highbit = 0;
400	bits = 0;
401	/* The hash size must be a power of two */
402	for (i = 0; i < 8 * sizeof(hashsize); i++)
403		if (hashsize & (1 << i)) {
404			highbit = i;
405			bits++;
406		}
407	if (bits > 1)
408		hashsize = 1 << (highbit);
409
410	hashmem = (void *)kmem_alloc(kernel_map, (vm_size_t)hashsize);
411	uma_startup2(hashmem, hashsize / sizeof(void *));
412
413	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
414		int size = kmemzones[indx].kz_size;
415		char *name = kmemzones[indx].kz_name;
416
417		kmemzones[indx].kz_zone = uma_zcreate(name, size,
418#ifdef INVARIANTS
419		    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
420#else
421		    NULL, NULL, NULL, NULL,
422#endif
423		    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
424
425		for (;i <= size; i+= KMEM_ZBASE)
426			kmemsize[i >> KMEM_ZSHIFT] = indx;
427
428	}
429}
430
431void
432malloc_init(data)
433	void *data;
434{
435	struct malloc_type *type = (struct malloc_type *)data;
436
437	mtx_lock(&malloc_mtx);
438	if (type->ks_magic != M_MAGIC)
439		panic("malloc type lacks magic");
440
441	if (cnt.v_page_count == 0)
442		panic("malloc_init not allowed before vm init");
443
444	if (type->ks_next != NULL)
445		return;
446
447	type->ks_next = kmemstatistics;
448	kmemstatistics = type;
449	mtx_init(&type->ks_mtx, type->ks_shortdesc, "Malloc Stats", MTX_DEF);
450	mtx_unlock(&malloc_mtx);
451}
452
453void
454malloc_uninit(data)
455	void *data;
456{
457	struct malloc_type *type = (struct malloc_type *)data;
458	struct malloc_type *t;
459
460	mtx_lock(&malloc_mtx);
461	mtx_lock(&type->ks_mtx);
462	if (type->ks_magic != M_MAGIC)
463		panic("malloc type lacks magic");
464
465	if (cnt.v_page_count == 0)
466		panic("malloc_uninit not allowed before vm init");
467
468	if (type == kmemstatistics)
469		kmemstatistics = type->ks_next;
470	else {
471		for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
472			if (t->ks_next == type) {
473				t->ks_next = type->ks_next;
474				break;
475			}
476		}
477	}
478	type->ks_next = NULL;
479	mtx_destroy(&type->ks_mtx);
480	mtx_unlock(&malloc_mtx);
481}
482
483static int
484sysctl_kern_malloc(SYSCTL_HANDLER_ARGS)
485{
486	struct malloc_type *type;
487	int linesize = 128;
488	int curline;
489	int bufsize;
490	int first;
491	int error;
492	char *buf;
493	char *p;
494	int cnt;
495	int len;
496	int i;
497
498	cnt = 0;
499
500	mtx_lock(&malloc_mtx);
501	for (type = kmemstatistics; type != NULL; type = type->ks_next)
502		cnt++;
503
504	mtx_unlock(&malloc_mtx);
505	bufsize = linesize * (cnt + 1);
506	p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
507	mtx_lock(&malloc_mtx);
508
509	len = snprintf(p, linesize,
510	    "\n        Type  InUse MemUse HighUse Requests  Size(s)\n");
511	p += len;
512
513	for (type = kmemstatistics; cnt != 0 && type != NULL;
514	    type = type->ks_next, cnt--) {
515		if (type->ks_calls == 0)
516			continue;
517
518		curline = linesize - 2;	/* Leave room for the \n */
519		len = snprintf(p, curline, "%13s%6lu%6luK%7luK%9llu",
520			type->ks_shortdesc,
521			type->ks_inuse,
522			(type->ks_memuse + 1023) / 1024,
523			(type->ks_maxused + 1023) / 1024,
524			(long long unsigned)type->ks_calls);
525		curline -= len;
526		p += len;
527
528		first = 1;
529		for (i = 0; i < 8 * sizeof(type->ks_size); i++)
530			if (type->ks_size & (1 << i)) {
531				if (first)
532					len = snprintf(p, curline, "  ");
533				else
534					len = snprintf(p, curline, ",");
535				curline -= len;
536				p += len;
537
538				len = snprintf(p, curline,
539				    "%s", kmemzones[i].kz_name);
540				curline -= len;
541				p += len;
542
543				first = 0;
544			}
545
546		len = snprintf(p, 2, "\n");
547		p += len;
548	}
549
550	mtx_unlock(&malloc_mtx);
551	error = SYSCTL_OUT(req, buf, p - buf);
552
553	free(buf, M_TEMP);
554	return (error);
555}
556
557SYSCTL_OID(_kern, OID_AUTO, malloc, CTLTYPE_STRING|CTLFLAG_RD,
558    NULL, 0, sysctl_kern_malloc, "A", "Malloc Stats");
559
560#ifdef MALLOC_PROFILE
561
562static int
563sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
564{
565	int linesize = 64;
566	uint64_t count;
567	uint64_t waste;
568	uint64_t mem;
569	int bufsize;
570	int error;
571	char *buf;
572	int rsize;
573	int size;
574	char *p;
575	int len;
576	int i;
577
578	bufsize = linesize * (KMEM_ZSIZE + 1);
579	bufsize += 128; 	/* For the stats line */
580	bufsize += 128; 	/* For the banner line */
581	waste = 0;
582	mem = 0;
583
584	p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
585	len = snprintf(p, bufsize,
586	    "\n  Size                    Requests  Real Size\n");
587	bufsize -= len;
588	p += len;
589
590	for (i = 0; i < KMEM_ZSIZE; i++) {
591		size = i << KMEM_ZSHIFT;
592		rsize = kmemzones[kmemsize[i]].kz_size;
593		count = (long long unsigned)krequests[i];
594
595		len = snprintf(p, bufsize, "%6d%28llu%11d\n",
596		    size, (unsigned long long)count, rsize);
597		bufsize -= len;
598		p += len;
599
600		if ((rsize * count) > (size * count))
601			waste += (rsize * count) - (size * count);
602		mem += (rsize * count);
603	}
604
605	len = snprintf(p, bufsize,
606	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
607	    (unsigned long long)mem, (unsigned long long)waste);
608	p += len;
609
610	error = SYSCTL_OUT(req, buf, p - buf);
611
612	free(buf, M_TEMP);
613	return (error);
614}
615
616SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
617    NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
618#endif /* MALLOC_PROFILE */
619