]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/kern_malloc.c
MFC 298950: Fix an off by one error when remapping MSI-X vectors.
[FreeBSD/stable/8.git] / sys / kern / kern_malloc.c
1 /*-
2  * Copyright (c) 1987, 1991, 1993
3  *      The Regents of the University of California.
4  * Copyright (c) 2005-2009 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      @(#)kern_malloc.c       8.3 (Berkeley) 1/4/94
32  */
33
34 /*
35  * Kernel malloc(9) implementation -- general purpose kernel memory allocator
36  * based on memory types.  Back end is implemented using the UMA(9) zone
37  * allocator.  A set of fixed-size buckets are used for smaller allocations,
38  * and a special UMA allocation interface is used for larger allocations.
39  * Callers declare memory types, and statistics are maintained independently
40  * for each memory type.  Statistics are maintained per-CPU for performance
41  * reasons.  See malloc(9) and comments in malloc.h for a detailed
42  * description.
43  */
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include "opt_ddb.h"
49 #include "opt_kdtrace.h"
50 #include "opt_vm.h"
51
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/kdb.h>
55 #include <sys/kernel.h>
56 #include <sys/lock.h>
57 #include <sys/malloc.h>
58 #include <sys/mbuf.h>
59 #include <sys/mutex.h>
60 #include <sys/vmmeter.h>
61 #include <sys/proc.h>
62 #include <sys/sbuf.h>
63 #include <sys/sysctl.h>
64 #include <sys/time.h>
65
66 #include <vm/vm.h>
67 #include <vm/pmap.h>
68 #include <vm/vm_param.h>
69 #include <vm/vm_kern.h>
70 #include <vm/vm_extern.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_page.h>
73 #include <vm/uma.h>
74 #include <vm/uma_int.h>
75 #include <vm/uma_dbg.h>
76
77 #ifdef DEBUG_MEMGUARD
78 #include <vm/memguard.h>
79 #endif
80 #ifdef DEBUG_REDZONE
81 #include <vm/redzone.h>
82 #endif
83
84 #if defined(INVARIANTS) && defined(__i386__)
85 #include <machine/cpu.h>
86 #endif
87
88 #include <ddb/ddb.h>
89
90 #ifdef KDTRACE_HOOKS
91 #include <sys/dtrace_bsd.h>
92
93 dtrace_malloc_probe_func_t      dtrace_malloc_probe;
94 #endif
95
96 /*
97  * When realloc() is called, if the new size is sufficiently smaller than
98  * the old size, realloc() will allocate a new, smaller block to avoid
99  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
100  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
101  */
102 #ifndef REALLOC_FRACTION
103 #define REALLOC_FRACTION        1       /* new block if <= half the size */
104 #endif
105
106 /*
107  * Centrally define some common malloc types.
108  */
109 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
110 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
111 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
112
113 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
114 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
115
116 static void kmeminit(void *);
117 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL);
118
119 static struct malloc_type *kmemstatistics;
120 static vm_offset_t kmembase;
121 static vm_offset_t kmemlimit;
122 static int kmemcount;
123
124 #define KMEM_ZSHIFT     4
125 #define KMEM_ZBASE      16
126 #define KMEM_ZMASK      (KMEM_ZBASE - 1)
127
128 #define KMEM_ZMAX       PAGE_SIZE
129 #define KMEM_ZSIZE      (KMEM_ZMAX >> KMEM_ZSHIFT)
130 static u_int8_t kmemsize[KMEM_ZSIZE + 1];
131
132 /*
133  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
134  * of various sizes.
135  *
136  * XXX: The comment here used to read "These won't be powers of two for
137  * long."  It's possible that a significant amount of wasted memory could be
138  * recovered by tuning the sizes of these buckets.
139  */
140 struct {
141         int kz_size;
142         char *kz_name;
143         uma_zone_t kz_zone;
144 } kmemzones[] = {
145         {16, "16", NULL},
146         {32, "32", NULL},
147         {64, "64", NULL},
148         {128, "128", NULL},
149         {256, "256", NULL},
150         {512, "512", NULL},
151         {1024, "1024", NULL},
152         {2048, "2048", NULL},
153         {4096, "4096", NULL},
154 #if PAGE_SIZE > 4096
155         {8192, "8192", NULL},
156 #if PAGE_SIZE > 8192
157         {16384, "16384", NULL},
158 #if PAGE_SIZE > 16384
159         {32768, "32768", NULL},
160 #if PAGE_SIZE > 32768
161         {65536, "65536", NULL},
162 #if PAGE_SIZE > 65536
163 #error  "Unsupported PAGE_SIZE"
164 #endif  /* 65536 */
165 #endif  /* 32768 */
166 #endif  /* 16384 */
167 #endif  /* 8192 */
168 #endif  /* 4096 */
169         {0, NULL},
170 };
171
172 /*
173  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
174  * types are described by a data structure passed by the declaring code, but
175  * the malloc(9) implementation has its own data structure describing the
176  * type and statistics.  This permits the malloc(9)-internal data structures
177  * to be modified without breaking binary-compiled kernel modules that
178  * declare malloc types.
179  */
180 static uma_zone_t mt_zone;
181
182 u_long vm_kmem_size;
183 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
184     "Size of kernel memory");
185
186 static u_long vm_kmem_size_min;
187 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
188     "Minimum size of kernel memory");
189
190 static u_long vm_kmem_size_max;
191 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
192     "Maximum size of kernel memory");
193
194 static u_int vm_kmem_size_scale;
195 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
196     "Scale factor for kernel memory size");
197
198 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
199 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
200     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
201     sysctl_kmem_map_size, "LU", "Current kmem_map allocation size");
202
203 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
204 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
205     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
206     sysctl_kmem_map_free, "LU", "Largest contiguous free range in kmem_map");
207
208 /*
209  * The malloc_mtx protects the kmemstatistics linked list.
210  */
211 struct mtx malloc_mtx;
212
213 #ifdef MALLOC_PROFILE
214 uint64_t krequests[KMEM_ZSIZE + 1];
215
216 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
217 #endif
218
219 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
220
221 /*
222  * time_uptime of the last malloc(9) failure (induced or real).
223  */
224 static time_t t_malloc_fail;
225
226 /*
227  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
228  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
229  */
230 #ifdef MALLOC_MAKE_FAILURES
231 SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
232     "Kernel malloc debugging options");
233
234 static int malloc_failure_rate;
235 static int malloc_nowait_count;
236 static int malloc_failure_count;
237 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW,
238     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
239 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
240 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
241     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
242 #endif
243
244 static int
245 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
246 {
247         u_long size;
248
249         size = kmem_map->size;
250         return (sysctl_handle_long(oidp, &size, 0, req));
251 }
252
253 static int
254 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
255 {
256         u_long size;
257
258         vm_map_lock_read(kmem_map);
259         size = kmem_map->root != NULL ? kmem_map->root->max_free :
260             kmem_map->max_offset - kmem_map->min_offset;
261         vm_map_unlock_read(kmem_map);
262         return (sysctl_handle_long(oidp, &size, 0, req));
263 }
264
265 int
266 malloc_last_fail(void)
267 {
268
269         return (time_uptime - t_malloc_fail);
270 }
271
272 /*
273  * An allocation has succeeded -- update malloc type statistics for the
274  * amount of bucket size.  Occurs within a critical section so that the
275  * thread isn't preempted and doesn't migrate while updating per-PCU
276  * statistics.
277  */
278 static void
279 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
280     int zindx)
281 {
282         struct malloc_type_internal *mtip;
283         struct malloc_type_stats *mtsp;
284
285         critical_enter();
286         mtip = mtp->ks_handle;
287         mtsp = &mtip->mti_stats[curcpu];
288         if (size > 0) {
289                 mtsp->mts_memalloced += size;
290                 mtsp->mts_numallocs++;
291         }
292         if (zindx != -1)
293                 mtsp->mts_size |= 1 << zindx;
294
295 #ifdef KDTRACE_HOOKS
296         if (dtrace_malloc_probe != NULL) {
297                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
298                 if (probe_id != 0)
299                         (dtrace_malloc_probe)(probe_id,
300                             (uintptr_t) mtp, (uintptr_t) mtip,
301                             (uintptr_t) mtsp, size, zindx);
302         }
303 #endif
304
305         critical_exit();
306 }
307
308 void
309 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
310 {
311
312         if (size > 0)
313                 malloc_type_zone_allocated(mtp, size, -1);
314 }
315
316 /*
317  * A free operation has occurred -- update malloc type statistics for the
318  * amount of the bucket size.  Occurs within a critical section so that the
319  * thread isn't preempted and doesn't migrate while updating per-CPU
320  * statistics.
321  */
322 void
323 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
324 {
325         struct malloc_type_internal *mtip;
326         struct malloc_type_stats *mtsp;
327
328         critical_enter();
329         mtip = mtp->ks_handle;
330         mtsp = &mtip->mti_stats[curcpu];
331         mtsp->mts_memfreed += size;
332         mtsp->mts_numfrees++;
333
334 #ifdef KDTRACE_HOOKS
335         if (dtrace_malloc_probe != NULL) {
336                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
337                 if (probe_id != 0)
338                         (dtrace_malloc_probe)(probe_id,
339                             (uintptr_t) mtp, (uintptr_t) mtip,
340                             (uintptr_t) mtsp, size, 0);
341         }
342 #endif
343
344         critical_exit();
345 }
346
347 /*
348  *      malloc:
349  *
350  *      Allocate a block of memory.
351  *
352  *      If M_NOWAIT is set, this routine will not block and return NULL if
353  *      the allocation fails.
354  */
355 void *
356 malloc(unsigned long size, struct malloc_type *mtp, int flags)
357 {
358         int indx;
359         caddr_t va;
360         uma_zone_t zone;
361 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
362         unsigned long osize = size;
363 #endif
364
365 #ifdef INVARIANTS
366         KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
367         /*
368          * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
369          */
370         indx = flags & (M_WAITOK | M_NOWAIT);
371         if (indx != M_NOWAIT && indx != M_WAITOK) {
372                 static  struct timeval lasterr;
373                 static  int curerr, once;
374                 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
375                         printf("Bad malloc flags: %x\n", indx);
376                         kdb_backtrace();
377                         flags |= M_WAITOK;
378                         once++;
379                 }
380         }
381 #endif
382 #ifdef MALLOC_MAKE_FAILURES
383         if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
384                 atomic_add_int(&malloc_nowait_count, 1);
385                 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
386                         atomic_add_int(&malloc_failure_count, 1);
387                         t_malloc_fail = time_uptime;
388                         return (NULL);
389                 }
390         }
391 #endif
392         if (flags & M_WAITOK)
393                 KASSERT(curthread->td_intr_nesting_level == 0,
394                    ("malloc(M_WAITOK) in interrupt context"));
395
396 #ifdef DEBUG_MEMGUARD
397         if (memguard_cmp(mtp, size)) {
398                 va = memguard_alloc(size, flags);
399                 if (va != NULL)
400                         return (va);
401                 /* This is unfortunate but should not be fatal. */
402         }
403 #endif
404
405 #ifdef DEBUG_REDZONE
406         size = redzone_size_ntor(size);
407 #endif
408
409         if (size <= KMEM_ZMAX) {
410                 if (size & KMEM_ZMASK)
411                         size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
412                 indx = kmemsize[size >> KMEM_ZSHIFT];
413                 zone = kmemzones[indx].kz_zone;
414 #ifdef MALLOC_PROFILE
415                 krequests[size >> KMEM_ZSHIFT]++;
416 #endif
417                 va = uma_zalloc(zone, flags);
418                 if (va != NULL)
419                         size = zone->uz_size;
420                 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
421         } else {
422                 size = roundup(size, PAGE_SIZE);
423                 zone = NULL;
424                 va = uma_large_malloc(size, flags);
425                 malloc_type_allocated(mtp, va == NULL ? 0 : size);
426         }
427         if (flags & M_WAITOK)
428                 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
429         else if (va == NULL)
430                 t_malloc_fail = time_uptime;
431 #ifdef DIAGNOSTIC
432         if (va != NULL && !(flags & M_ZERO)) {
433                 memset(va, 0x70, osize);
434         }
435 #endif
436 #ifdef DEBUG_REDZONE
437         if (va != NULL)
438                 va = redzone_setup(va, osize);
439 #endif
440         return ((void *) va);
441 }
442
443 /*
444  *      free:
445  *
446  *      Free a block of memory allocated by malloc.
447  *
448  *      This routine may not block.
449  */
450 void
451 free(void *addr, struct malloc_type *mtp)
452 {
453         uma_slab_t slab;
454         u_long size;
455
456         KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
457
458         /* free(NULL, ...) does nothing */
459         if (addr == NULL)
460                 return;
461
462 #ifdef DEBUG_MEMGUARD
463         if (is_memguard_addr(addr)) {
464                 memguard_free(addr);
465                 return;
466         }
467 #endif
468
469 #ifdef DEBUG_REDZONE
470         redzone_check(addr);
471         addr = redzone_addr_ntor(addr);
472 #endif
473
474         slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
475
476         if (slab == NULL)
477                 panic("free: address %p(%p) has not been allocated.\n",
478                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
479
480
481         if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
482 #ifdef INVARIANTS
483                 struct malloc_type **mtpp = addr;
484 #endif
485                 size = slab->us_keg->uk_size;
486 #ifdef INVARIANTS
487                 /*
488                  * Cache a pointer to the malloc_type that most recently freed
489                  * this memory here.  This way we know who is most likely to
490                  * have stepped on it later.
491                  *
492                  * This code assumes that size is a multiple of 8 bytes for
493                  * 64 bit machines
494                  */
495                 mtpp = (struct malloc_type **)
496                     ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
497                 mtpp += (size - sizeof(struct malloc_type *)) /
498                     sizeof(struct malloc_type *);
499                 *mtpp = mtp;
500 #endif
501                 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
502         } else {
503                 size = slab->us_size;
504                 uma_large_free(slab);
505         }
506         malloc_type_freed(mtp, size);
507 }
508
509 /*
510  *      realloc: change the size of a memory block
511  */
512 void *
513 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
514 {
515         uma_slab_t slab;
516         unsigned long alloc;
517         void *newaddr;
518
519         KASSERT(mtp->ks_magic == M_MAGIC,
520             ("realloc: bad malloc type magic"));
521
522         /* realloc(NULL, ...) is equivalent to malloc(...) */
523         if (addr == NULL)
524                 return (malloc(size, mtp, flags));
525
526         /*
527          * XXX: Should report free of old memory and alloc of new memory to
528          * per-CPU stats.
529          */
530
531 #ifdef DEBUG_MEMGUARD
532         if (is_memguard_addr(addr))
533                 return (memguard_realloc(addr, size, mtp, flags));
534 #endif
535
536 #ifdef DEBUG_REDZONE
537         slab = NULL;
538         alloc = redzone_get_size(addr);
539 #else
540         slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
541
542         /* Sanity check */
543         KASSERT(slab != NULL,
544             ("realloc: address %p out of range", (void *)addr));
545
546         /* Get the size of the original block */
547         if (!(slab->us_flags & UMA_SLAB_MALLOC))
548                 alloc = slab->us_keg->uk_size;
549         else
550                 alloc = slab->us_size;
551
552         /* Reuse the original block if appropriate */
553         if (size <= alloc
554             && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
555                 return (addr);
556 #endif /* !DEBUG_REDZONE */
557
558         /* Allocate a new, bigger (or smaller) block */
559         if ((newaddr = malloc(size, mtp, flags)) == NULL)
560                 return (NULL);
561
562         /* Copy over original contents */
563         bcopy(addr, newaddr, min(size, alloc));
564         free(addr, mtp);
565         return (newaddr);
566 }
567
568 /*
569  *      reallocf: same as realloc() but free memory on failure.
570  */
571 void *
572 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
573 {
574         void *mem;
575
576         if ((mem = realloc(addr, size, mtp, flags)) == NULL)
577                 free(addr, mtp);
578         return (mem);
579 }
580
581 /*
582  * Initialize the kernel memory allocator
583  */
584 /* ARGSUSED*/
585 static void
586 kmeminit(void *dummy)
587 {
588         u_int8_t indx;
589         u_long mem_size, tmp;
590         int i;
591  
592         mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
593
594         /*
595          * Try to auto-tune the kernel memory size, so that it is
596          * more applicable for a wider range of machine sizes.  The
597          * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
598          * available.
599          *
600          * Note that the kmem_map is also used by the zone allocator,
601          * so make sure that there is enough space.
602          */
603         vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
604         mem_size = cnt.v_page_count;
605
606 #if defined(VM_KMEM_SIZE_SCALE)
607         vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
608 #endif
609         TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
610         if (vm_kmem_size_scale > 0 &&
611             (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
612                 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
613
614 #if defined(VM_KMEM_SIZE_MIN)
615         vm_kmem_size_min = VM_KMEM_SIZE_MIN;
616 #endif
617         TUNABLE_ULONG_FETCH("vm.kmem_size_min", &vm_kmem_size_min);
618         if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) {
619                 vm_kmem_size = vm_kmem_size_min;
620         }
621
622 #if defined(VM_KMEM_SIZE_MAX)
623         vm_kmem_size_max = VM_KMEM_SIZE_MAX;
624 #endif
625         TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
626         if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
627                 vm_kmem_size = vm_kmem_size_max;
628
629         /* Allow final override from the kernel environment */
630         TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
631
632         /*
633          * Limit kmem virtual size to twice the physical memory.
634          * This allows for kmem map sparseness, but limits the size
635          * to something sane.  Be careful to not overflow the 32bit
636          * ints while doing the check or the adjustment.
637          */
638         if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
639                 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
640
641         /*
642          * Tune settings based on the kmem map's size at this time.
643          */
644         init_param3(vm_kmem_size / PAGE_SIZE);
645
646 #ifdef DEBUG_MEMGUARD
647         tmp = memguard_fudge(vm_kmem_size, kernel_map);
648 #else
649         tmp = vm_kmem_size;
650 #endif
651         kmem_map = kmem_suballoc(kernel_map, &kmembase, &kmemlimit,
652             tmp, TRUE);
653         kmem_map->system_map = 1;
654
655 #ifdef DEBUG_MEMGUARD
656         /*
657          * Initialize MemGuard if support compiled in.  MemGuard is a
658          * replacement allocator used for detecting tamper-after-free
659          * scenarios as they occur.  It is only used for debugging.
660          */
661         memguard_init(kmem_map);
662 #endif
663
664         uma_startup2();
665
666         mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
667 #ifdef INVARIANTS
668             mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
669 #else
670             NULL, NULL, NULL, NULL,
671 #endif
672             UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
673         for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
674                 int size = kmemzones[indx].kz_size;
675                 char *name = kmemzones[indx].kz_name;
676
677                 kmemzones[indx].kz_zone = uma_zcreate(name, size,
678 #ifdef INVARIANTS
679                     mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
680 #else
681                     NULL, NULL, NULL, NULL,
682 #endif
683                     UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
684                     
685                 for (;i <= size; i+= KMEM_ZBASE)
686                         kmemsize[i >> KMEM_ZSHIFT] = indx;
687                 
688         }
689 }
690
691 void
692 malloc_init(void *data)
693 {
694         struct malloc_type_internal *mtip;
695         struct malloc_type *mtp;
696
697         KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
698
699         mtp = data;
700         if (mtp->ks_magic != M_MAGIC)
701                 panic("malloc_init: bad malloc type magic");
702
703         mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
704         mtp->ks_handle = mtip;
705
706         mtx_lock(&malloc_mtx);
707         mtp->ks_next = kmemstatistics;
708         kmemstatistics = mtp;
709         kmemcount++;
710         mtx_unlock(&malloc_mtx);
711 }
712
713 void
714 malloc_uninit(void *data)
715 {
716         struct malloc_type_internal *mtip;
717         struct malloc_type_stats *mtsp;
718         struct malloc_type *mtp, *temp;
719         uma_slab_t slab;
720         long temp_allocs, temp_bytes;
721         int i;
722
723         mtp = data;
724         KASSERT(mtp->ks_magic == M_MAGIC,
725             ("malloc_uninit: bad malloc type magic"));
726         KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
727
728         mtx_lock(&malloc_mtx);
729         mtip = mtp->ks_handle;
730         mtp->ks_handle = NULL;
731         if (mtp != kmemstatistics) {
732                 for (temp = kmemstatistics; temp != NULL;
733                     temp = temp->ks_next) {
734                         if (temp->ks_next == mtp) {
735                                 temp->ks_next = mtp->ks_next;
736                                 break;
737                         }
738                 }
739                 KASSERT(temp,
740                     ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
741         } else
742                 kmemstatistics = mtp->ks_next;
743         kmemcount--;
744         mtx_unlock(&malloc_mtx);
745
746         /*
747          * Look for memory leaks.
748          */
749         temp_allocs = temp_bytes = 0;
750         for (i = 0; i < MAXCPU; i++) {
751                 mtsp = &mtip->mti_stats[i];
752                 temp_allocs += mtsp->mts_numallocs;
753                 temp_allocs -= mtsp->mts_numfrees;
754                 temp_bytes += mtsp->mts_memalloced;
755                 temp_bytes -= mtsp->mts_memfreed;
756         }
757         if (temp_allocs > 0 || temp_bytes > 0) {
758                 printf("Warning: memory type %s leaked memory on destroy "
759                     "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
760                     temp_allocs, temp_bytes);
761         }
762
763         slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
764         uma_zfree_arg(mt_zone, mtip, slab);
765 }
766
767 struct malloc_type *
768 malloc_desc2type(const char *desc)
769 {
770         struct malloc_type *mtp;
771
772         mtx_assert(&malloc_mtx, MA_OWNED);
773         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
774                 if (strcmp(mtp->ks_shortdesc, desc) == 0)
775                         return (mtp);
776         }
777         return (NULL);
778 }
779
780 static int
781 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
782 {
783         struct malloc_type_stream_header mtsh;
784         struct malloc_type_internal *mtip;
785         struct malloc_type_header mth;
786         struct malloc_type *mtp;
787         int buflen, count, error, i;
788         struct sbuf sbuf;
789         char *buffer;
790
791         mtx_lock(&malloc_mtx);
792 restart:
793         mtx_assert(&malloc_mtx, MA_OWNED);
794         count = kmemcount;
795         mtx_unlock(&malloc_mtx);
796         buflen = sizeof(mtsh) + count * (sizeof(mth) +
797             sizeof(struct malloc_type_stats) * MAXCPU) + 1;
798         buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
799         mtx_lock(&malloc_mtx);
800         if (count < kmemcount) {
801                 free(buffer, M_TEMP);
802                 goto restart;
803         }
804
805         sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
806
807         /*
808          * Insert stream header.
809          */
810         bzero(&mtsh, sizeof(mtsh));
811         mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
812         mtsh.mtsh_maxcpus = MAXCPU;
813         mtsh.mtsh_count = kmemcount;
814         if (sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)) < 0) {
815                 mtx_unlock(&malloc_mtx);
816                 error = ENOMEM;
817                 goto out;
818         }
819
820         /*
821          * Insert alternating sequence of type headers and type statistics.
822          */
823         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
824                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
825
826                 /*
827                  * Insert type header.
828                  */
829                 bzero(&mth, sizeof(mth));
830                 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
831                 if (sbuf_bcat(&sbuf, &mth, sizeof(mth)) < 0) {
832                         mtx_unlock(&malloc_mtx);
833                         error = ENOMEM;
834                         goto out;
835                 }
836
837                 /*
838                  * Insert type statistics for each CPU.
839                  */
840                 for (i = 0; i < MAXCPU; i++) {
841                         if (sbuf_bcat(&sbuf, &mtip->mti_stats[i],
842                             sizeof(mtip->mti_stats[i])) < 0) {
843                                 mtx_unlock(&malloc_mtx);
844                                 error = ENOMEM;
845                                 goto out;
846                         }
847                 }
848         }
849         mtx_unlock(&malloc_mtx);
850         sbuf_finish(&sbuf);
851         error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
852 out:
853         sbuf_delete(&sbuf);
854         free(buffer, M_TEMP);
855         return (error);
856 }
857
858 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
859     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
860     "Return malloc types");
861
862 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
863     "Count of kernel malloc types");
864
865 void
866 malloc_type_list(malloc_type_list_func_t *func, void *arg)
867 {
868         struct malloc_type *mtp, **bufmtp;
869         int count, i;
870         size_t buflen;
871
872         mtx_lock(&malloc_mtx);
873 restart:
874         mtx_assert(&malloc_mtx, MA_OWNED);
875         count = kmemcount;
876         mtx_unlock(&malloc_mtx);
877
878         buflen = sizeof(struct malloc_type *) * count;
879         bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
880
881         mtx_lock(&malloc_mtx);
882
883         if (count < kmemcount) {
884                 free(bufmtp, M_TEMP);
885                 goto restart;
886         }
887
888         for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
889                 bufmtp[i] = mtp;
890
891         mtx_unlock(&malloc_mtx);
892
893         for (i = 0; i < count; i++)
894                 (func)(bufmtp[i], arg);
895
896         free(bufmtp, M_TEMP);
897 }
898
899 #ifdef DDB
900 DB_SHOW_COMMAND(malloc, db_show_malloc)
901 {
902         struct malloc_type_internal *mtip;
903         struct malloc_type *mtp;
904         u_int64_t allocs, frees;
905         u_int64_t alloced, freed;
906         int i;
907
908         db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
909             "Requests");
910         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
911                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
912                 allocs = 0;
913                 frees = 0;
914                 alloced = 0;
915                 freed = 0;
916                 for (i = 0; i < MAXCPU; i++) {
917                         allocs += mtip->mti_stats[i].mts_numallocs;
918                         frees += mtip->mti_stats[i].mts_numfrees;
919                         alloced += mtip->mti_stats[i].mts_memalloced;
920                         freed += mtip->mti_stats[i].mts_memfreed;
921                 }
922                 db_printf("%18s %12ju %12juK %12ju\n",
923                     mtp->ks_shortdesc, allocs - frees,
924                     (alloced - freed + 1023) / 1024, allocs);
925                 if (db_pager_quit)
926                         break;
927         }
928 }
929 #endif
930
931 #ifdef MALLOC_PROFILE
932
933 static int
934 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
935 {
936         int linesize = 64;
937         struct sbuf sbuf;
938         uint64_t count;
939         uint64_t waste;
940         uint64_t mem;
941         int bufsize;
942         int error;
943         char *buf;
944         int rsize;
945         int size;
946         int i;
947
948         bufsize = linesize * (KMEM_ZSIZE + 1);
949         bufsize += 128;         /* For the stats line */
950         bufsize += 128;         /* For the banner line */
951         waste = 0;
952         mem = 0;
953
954         buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
955         sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
956         sbuf_printf(&sbuf, 
957             "\n  Size                    Requests  Real Size\n");
958         for (i = 0; i < KMEM_ZSIZE; i++) {
959                 size = i << KMEM_ZSHIFT;
960                 rsize = kmemzones[kmemsize[i]].kz_size;
961                 count = (long long unsigned)krequests[i];
962
963                 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
964                     (unsigned long long)count, rsize);
965
966                 if ((rsize * count) > (size * count))
967                         waste += (rsize * count) - (size * count);
968                 mem += (rsize * count);
969         }
970         sbuf_printf(&sbuf,
971             "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
972             (unsigned long long)mem, (unsigned long long)waste);
973         sbuf_finish(&sbuf);
974
975         error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
976
977         sbuf_delete(&sbuf);
978         free(buf, M_TEMP);
979         return (error);
980 }
981
982 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
983     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
984 #endif /* MALLOC_PROFILE */