]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_malloc.c
Merge bmake-20130904
[FreeBSD/FreeBSD.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 #include <sys/vmem.h>
66
67 #include <vm/vm.h>
68 #include <vm/pmap.h>
69 #include <vm/vm_pageout.h>
70 #include <vm/vm_param.h>
71 #include <vm/vm_kern.h>
72 #include <vm/vm_extern.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_page.h>
75 #include <vm/uma.h>
76 #include <vm/uma_int.h>
77 #include <vm/uma_dbg.h>
78
79 #ifdef DEBUG_MEMGUARD
80 #include <vm/memguard.h>
81 #endif
82 #ifdef DEBUG_REDZONE
83 #include <vm/redzone.h>
84 #endif
85
86 #if defined(INVARIANTS) && defined(__i386__)
87 #include <machine/cpu.h>
88 #endif
89
90 #include <ddb/ddb.h>
91
92 #ifdef KDTRACE_HOOKS
93 #include <sys/dtrace_bsd.h>
94
95 dtrace_malloc_probe_func_t      dtrace_malloc_probe;
96 #endif
97
98 /*
99  * When realloc() is called, if the new size is sufficiently smaller than
100  * the old size, realloc() will allocate a new, smaller block to avoid
101  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
102  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
103  */
104 #ifndef REALLOC_FRACTION
105 #define REALLOC_FRACTION        1       /* new block if <= half the size */
106 #endif
107
108 /*
109  * Centrally define some common malloc types.
110  */
111 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
112 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
113 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
114
115 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
116 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
117
118 static struct malloc_type *kmemstatistics;
119 static int kmemcount;
120
121 #define KMEM_ZSHIFT     4
122 #define KMEM_ZBASE      16
123 #define KMEM_ZMASK      (KMEM_ZBASE - 1)
124
125 #define KMEM_ZMAX       PAGE_SIZE
126 #define KMEM_ZSIZE      (KMEM_ZMAX >> KMEM_ZSHIFT)
127 static uint8_t kmemsize[KMEM_ZSIZE + 1];
128
129 #ifndef MALLOC_DEBUG_MAXZONES
130 #define MALLOC_DEBUG_MAXZONES   1
131 #endif
132 static int numzones = MALLOC_DEBUG_MAXZONES;
133
134 /*
135  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
136  * of various sizes.
137  *
138  * XXX: The comment here used to read "These won't be powers of two for
139  * long."  It's possible that a significant amount of wasted memory could be
140  * recovered by tuning the sizes of these buckets.
141  */
142 struct {
143         int kz_size;
144         char *kz_name;
145         uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
146 } kmemzones[] = {
147         {16, "16", },
148         {32, "32", },
149         {64, "64", },
150         {128, "128", },
151         {256, "256", },
152         {512, "512", },
153         {1024, "1024", },
154         {2048, "2048", },
155         {4096, "4096", },
156 #if PAGE_SIZE > 4096
157         {8192, "8192", },
158 #if PAGE_SIZE > 8192
159         {16384, "16384", },
160 #if PAGE_SIZE > 16384
161         {32768, "32768", },
162 #if PAGE_SIZE > 32768
163         {65536, "65536", },
164 #if PAGE_SIZE > 65536
165 #error  "Unsupported PAGE_SIZE"
166 #endif  /* 65536 */
167 #endif  /* 32768 */
168 #endif  /* 16384 */
169 #endif  /* 8192 */
170 #endif  /* 4096 */
171         {0, NULL},
172 };
173
174 /*
175  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
176  * types are described by a data structure passed by the declaring code, but
177  * the malloc(9) implementation has its own data structure describing the
178  * type and statistics.  This permits the malloc(9)-internal data structures
179  * to be modified without breaking binary-compiled kernel modules that
180  * declare malloc types.
181  */
182 static uma_zone_t mt_zone;
183
184 u_long vm_kmem_size;
185 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
186     "Size of kernel memory");
187
188 static u_long vm_kmem_size_min;
189 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
190     "Minimum size of kernel memory");
191
192 static u_long vm_kmem_size_max;
193 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
194     "Maximum size of kernel memory");
195
196 static u_int vm_kmem_size_scale;
197 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
198     "Scale factor for kernel memory size");
199
200 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
201 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
202     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
203     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
204
205 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
206 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
207     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
208     sysctl_kmem_map_free, "LU", "Free space in kmem");
209
210 /*
211  * The malloc_mtx protects the kmemstatistics linked list.
212  */
213 struct mtx malloc_mtx;
214
215 #ifdef MALLOC_PROFILE
216 uint64_t krequests[KMEM_ZSIZE + 1];
217
218 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
219 #endif
220
221 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
222
223 /*
224  * time_uptime of the last malloc(9) failure (induced or real).
225  */
226 static time_t t_malloc_fail;
227
228 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
229 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
230     "Kernel malloc debugging options");
231 #endif
232
233 /*
234  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
235  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
236  */
237 #ifdef MALLOC_MAKE_FAILURES
238 static int malloc_failure_rate;
239 static int malloc_nowait_count;
240 static int malloc_failure_count;
241 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW,
242     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
243 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
244 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
245     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
246 #endif
247
248 static int
249 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
250 {
251         u_long size;
252
253         size = vmem_size(kmem_arena, VMEM_ALLOC);
254         return (sysctl_handle_long(oidp, &size, 0, req));
255 }
256
257 static int
258 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
259 {
260         u_long size;
261
262         size = vmem_size(kmem_arena, VMEM_FREE);
263         return (sysctl_handle_long(oidp, &size, 0, req));
264 }
265
266 /*
267  * malloc(9) uma zone separation -- sub-page buffer overruns in one
268  * malloc type will affect only a subset of other malloc types.
269  */
270 #if MALLOC_DEBUG_MAXZONES > 1
271 static void
272 tunable_set_numzones(void)
273 {
274
275         TUNABLE_INT_FETCH("debug.malloc.numzones",
276             &numzones);
277
278         /* Sanity check the number of malloc uma zones. */
279         if (numzones <= 0)
280                 numzones = 1;
281         if (numzones > MALLOC_DEBUG_MAXZONES)
282                 numzones = MALLOC_DEBUG_MAXZONES;
283 }
284 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
285 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN,
286     &numzones, 0, "Number of malloc uma subzones");
287
288 /*
289  * Any number that changes regularly is an okay choice for the
290  * offset.  Build numbers are pretty good of you have them.
291  */
292 static u_int zone_offset = __FreeBSD_version;
293 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
294 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
295     &zone_offset, 0, "Separate malloc types by examining the "
296     "Nth character in the malloc type short description.");
297
298 static u_int
299 mtp_get_subzone(const char *desc)
300 {
301         size_t len;
302         u_int val;
303
304         if (desc == NULL || (len = strlen(desc)) == 0)
305                 return (0);
306         val = desc[zone_offset % len];
307         return (val % numzones);
308 }
309 #elif MALLOC_DEBUG_MAXZONES == 0
310 #error "MALLOC_DEBUG_MAXZONES must be positive."
311 #else
312 static inline u_int
313 mtp_get_subzone(const char *desc)
314 {
315
316         return (0);
317 }
318 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
319
320 int
321 malloc_last_fail(void)
322 {
323
324         return (time_uptime - t_malloc_fail);
325 }
326
327 /*
328  * An allocation has succeeded -- update malloc type statistics for the
329  * amount of bucket size.  Occurs within a critical section so that the
330  * thread isn't preempted and doesn't migrate while updating per-PCU
331  * statistics.
332  */
333 static void
334 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
335     int zindx)
336 {
337         struct malloc_type_internal *mtip;
338         struct malloc_type_stats *mtsp;
339
340         critical_enter();
341         mtip = mtp->ks_handle;
342         mtsp = &mtip->mti_stats[curcpu];
343         if (size > 0) {
344                 mtsp->mts_memalloced += size;
345                 mtsp->mts_numallocs++;
346         }
347         if (zindx != -1)
348                 mtsp->mts_size |= 1 << zindx;
349
350 #ifdef KDTRACE_HOOKS
351         if (dtrace_malloc_probe != NULL) {
352                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
353                 if (probe_id != 0)
354                         (dtrace_malloc_probe)(probe_id,
355                             (uintptr_t) mtp, (uintptr_t) mtip,
356                             (uintptr_t) mtsp, size, zindx);
357         }
358 #endif
359
360         critical_exit();
361 }
362
363 void
364 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
365 {
366
367         if (size > 0)
368                 malloc_type_zone_allocated(mtp, size, -1);
369 }
370
371 /*
372  * A free operation has occurred -- update malloc type statistics for the
373  * amount of the bucket size.  Occurs within a critical section so that the
374  * thread isn't preempted and doesn't migrate while updating per-CPU
375  * statistics.
376  */
377 void
378 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
379 {
380         struct malloc_type_internal *mtip;
381         struct malloc_type_stats *mtsp;
382
383         critical_enter();
384         mtip = mtp->ks_handle;
385         mtsp = &mtip->mti_stats[curcpu];
386         mtsp->mts_memfreed += size;
387         mtsp->mts_numfrees++;
388
389 #ifdef KDTRACE_HOOKS
390         if (dtrace_malloc_probe != NULL) {
391                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
392                 if (probe_id != 0)
393                         (dtrace_malloc_probe)(probe_id,
394                             (uintptr_t) mtp, (uintptr_t) mtip,
395                             (uintptr_t) mtsp, size, 0);
396         }
397 #endif
398
399         critical_exit();
400 }
401
402 /*
403  *      contigmalloc:
404  *
405  *      Allocate a block of physically contiguous memory.
406  *
407  *      If M_NOWAIT is set, this routine will not block and return NULL if
408  *      the allocation fails.
409  */
410 void *
411 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
412     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
413     vm_paddr_t boundary)
414 {
415         void *ret;
416
417         ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
418             alignment, boundary, VM_MEMATTR_DEFAULT);
419         if (ret != NULL)
420                 malloc_type_allocated(type, round_page(size));
421         return (ret);
422 }
423
424 /*
425  *      contigfree:
426  *
427  *      Free a block of memory allocated by contigmalloc.
428  *
429  *      This routine may not block.
430  */
431 void
432 contigfree(void *addr, unsigned long size, struct malloc_type *type)
433 {
434
435         kmem_free(kernel_arena, (vm_offset_t)addr, size);
436         malloc_type_freed(type, round_page(size));
437 }
438
439 /*
440  *      malloc:
441  *
442  *      Allocate a block of memory.
443  *
444  *      If M_NOWAIT is set, this routine will not block and return NULL if
445  *      the allocation fails.
446  */
447 void *
448 malloc(unsigned long size, struct malloc_type *mtp, int flags)
449 {
450         int indx;
451         struct malloc_type_internal *mtip;
452         caddr_t va;
453         uma_zone_t zone;
454 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
455         unsigned long osize = size;
456 #endif
457
458 #ifdef INVARIANTS
459         KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
460         /*
461          * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
462          */
463         indx = flags & (M_WAITOK | M_NOWAIT);
464         if (indx != M_NOWAIT && indx != M_WAITOK) {
465                 static  struct timeval lasterr;
466                 static  int curerr, once;
467                 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
468                         printf("Bad malloc flags: %x\n", indx);
469                         kdb_backtrace();
470                         flags |= M_WAITOK;
471                         once++;
472                 }
473         }
474 #endif
475 #ifdef MALLOC_MAKE_FAILURES
476         if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
477                 atomic_add_int(&malloc_nowait_count, 1);
478                 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
479                         atomic_add_int(&malloc_failure_count, 1);
480                         t_malloc_fail = time_uptime;
481                         return (NULL);
482                 }
483         }
484 #endif
485         if (flags & M_WAITOK)
486                 KASSERT(curthread->td_intr_nesting_level == 0,
487                    ("malloc(M_WAITOK) in interrupt context"));
488
489 #ifdef DEBUG_MEMGUARD
490         if (memguard_cmp_mtp(mtp, size)) {
491                 va = memguard_alloc(size, flags);
492                 if (va != NULL)
493                         return (va);
494                 /* This is unfortunate but should not be fatal. */
495         }
496 #endif
497
498 #ifdef DEBUG_REDZONE
499         size = redzone_size_ntor(size);
500 #endif
501
502         if (size <= KMEM_ZMAX) {
503                 mtip = mtp->ks_handle;
504                 if (size & KMEM_ZMASK)
505                         size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
506                 indx = kmemsize[size >> KMEM_ZSHIFT];
507                 KASSERT(mtip->mti_zone < numzones,
508                     ("mti_zone %u out of range %d",
509                     mtip->mti_zone, numzones));
510                 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
511 #ifdef MALLOC_PROFILE
512                 krequests[size >> KMEM_ZSHIFT]++;
513 #endif
514                 va = uma_zalloc(zone, flags);
515                 if (va != NULL)
516                         size = zone->uz_size;
517                 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
518         } else {
519                 size = roundup(size, PAGE_SIZE);
520                 zone = NULL;
521                 va = uma_large_malloc(size, flags);
522                 malloc_type_allocated(mtp, va == NULL ? 0 : size);
523         }
524         if (flags & M_WAITOK)
525                 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
526         else if (va == NULL)
527                 t_malloc_fail = time_uptime;
528 #ifdef DIAGNOSTIC
529         if (va != NULL && !(flags & M_ZERO)) {
530                 memset(va, 0x70, osize);
531         }
532 #endif
533 #ifdef DEBUG_REDZONE
534         if (va != NULL)
535                 va = redzone_setup(va, osize);
536 #endif
537         return ((void *) va);
538 }
539
540 /*
541  *      free:
542  *
543  *      Free a block of memory allocated by malloc.
544  *
545  *      This routine may not block.
546  */
547 void
548 free(void *addr, struct malloc_type *mtp)
549 {
550         uma_slab_t slab;
551         u_long size;
552
553         KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
554
555         /* free(NULL, ...) does nothing */
556         if (addr == NULL)
557                 return;
558
559 #ifdef DEBUG_MEMGUARD
560         if (is_memguard_addr(addr)) {
561                 memguard_free(addr);
562                 return;
563         }
564 #endif
565
566 #ifdef DEBUG_REDZONE
567         redzone_check(addr);
568         addr = redzone_addr_ntor(addr);
569 #endif
570
571         slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
572
573         if (slab == NULL)
574                 panic("free: address %p(%p) has not been allocated.\n",
575                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
576
577         if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
578 #ifdef INVARIANTS
579                 struct malloc_type **mtpp = addr;
580 #endif
581                 size = slab->us_keg->uk_size;
582 #ifdef INVARIANTS
583                 /*
584                  * Cache a pointer to the malloc_type that most recently freed
585                  * this memory here.  This way we know who is most likely to
586                  * have stepped on it later.
587                  *
588                  * This code assumes that size is a multiple of 8 bytes for
589                  * 64 bit machines
590                  */
591                 mtpp = (struct malloc_type **)
592                     ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
593                 mtpp += (size - sizeof(struct malloc_type *)) /
594                     sizeof(struct malloc_type *);
595                 *mtpp = mtp;
596 #endif
597                 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
598         } else {
599                 size = slab->us_size;
600                 uma_large_free(slab);
601         }
602         malloc_type_freed(mtp, size);
603 }
604
605 /*
606  *      realloc: change the size of a memory block
607  */
608 void *
609 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
610 {
611         uma_slab_t slab;
612         unsigned long alloc;
613         void *newaddr;
614
615         KASSERT(mtp->ks_magic == M_MAGIC,
616             ("realloc: bad malloc type magic"));
617
618         /* realloc(NULL, ...) is equivalent to malloc(...) */
619         if (addr == NULL)
620                 return (malloc(size, mtp, flags));
621
622         /*
623          * XXX: Should report free of old memory and alloc of new memory to
624          * per-CPU stats.
625          */
626
627 #ifdef DEBUG_MEMGUARD
628         if (is_memguard_addr(addr))
629                 return (memguard_realloc(addr, size, mtp, flags));
630 #endif
631
632 #ifdef DEBUG_REDZONE
633         slab = NULL;
634         alloc = redzone_get_size(addr);
635 #else
636         slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
637
638         /* Sanity check */
639         KASSERT(slab != NULL,
640             ("realloc: address %p out of range", (void *)addr));
641
642         /* Get the size of the original block */
643         if (!(slab->us_flags & UMA_SLAB_MALLOC))
644                 alloc = slab->us_keg->uk_size;
645         else
646                 alloc = slab->us_size;
647
648         /* Reuse the original block if appropriate */
649         if (size <= alloc
650             && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
651                 return (addr);
652 #endif /* !DEBUG_REDZONE */
653
654         /* Allocate a new, bigger (or smaller) block */
655         if ((newaddr = malloc(size, mtp, flags)) == NULL)
656                 return (NULL);
657
658         /* Copy over original contents */
659         bcopy(addr, newaddr, min(size, alloc));
660         free(addr, mtp);
661         return (newaddr);
662 }
663
664 /*
665  *      reallocf: same as realloc() but free memory on failure.
666  */
667 void *
668 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
669 {
670         void *mem;
671
672         if ((mem = realloc(addr, size, mtp, flags)) == NULL)
673                 free(addr, mtp);
674         return (mem);
675 }
676
677 /*
678  * Wake the page daemon when we exhaust KVA.  It will call the lowmem handler
679  * and uma_reclaim() callbacks in a context that is safe.
680  */
681 static void
682 kmem_reclaim(vmem_t *vm, int flags)
683 {
684
685         pagedaemon_wakeup();
686 }
687
688 /*
689  * Initialize the kernel memory arena.
690  */
691 void
692 kmeminit(void)
693 {
694         u_long mem_size, tmp;
695  
696         /*
697          * Try to auto-tune the kernel memory size, so that it is
698          * more applicable for a wider range of machine sizes.  The
699          * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
700          * available.
701          *
702          * Note that the kmem_map is also used by the zone allocator,
703          * so make sure that there is enough space.
704          */
705         vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
706         mem_size = cnt.v_page_count;
707
708 #if defined(VM_KMEM_SIZE_SCALE)
709         vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
710 #endif
711         TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
712         if (vm_kmem_size_scale > 0 &&
713             (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
714                 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
715
716 #if defined(VM_KMEM_SIZE_MIN)
717         vm_kmem_size_min = VM_KMEM_SIZE_MIN;
718 #endif
719         TUNABLE_ULONG_FETCH("vm.kmem_size_min", &vm_kmem_size_min);
720         if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) {
721                 vm_kmem_size = vm_kmem_size_min;
722         }
723
724 #if defined(VM_KMEM_SIZE_MAX)
725         vm_kmem_size_max = VM_KMEM_SIZE_MAX;
726 #endif
727         TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
728         if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
729                 vm_kmem_size = vm_kmem_size_max;
730
731         /* Allow final override from the kernel environment */
732         TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
733
734         /*
735          * Limit kmem virtual size to twice the physical memory.
736          * This allows for kmem map sparseness, but limits the size
737          * to something sane.  Be careful to not overflow the 32bit
738          * ints while doing the check or the adjustment.
739          */
740         if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
741                 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
742
743         vm_kmem_size = round_page(vm_kmem_size);
744 #ifdef DEBUG_MEMGUARD
745         tmp = memguard_fudge(vm_kmem_size, kernel_map);
746 #else
747         tmp = vm_kmem_size;
748 #endif
749         vmem_init(kmem_arena, "kmem arena", kva_alloc(tmp), tmp, PAGE_SIZE,
750             0, 0);
751         vmem_set_reclaim(kmem_arena, kmem_reclaim);
752
753 #ifdef DEBUG_MEMGUARD
754         /*
755          * Initialize MemGuard if support compiled in.  MemGuard is a
756          * replacement allocator used for detecting tamper-after-free
757          * scenarios as they occur.  It is only used for debugging.
758          */
759         memguard_init(kmem_arena);
760 #endif
761 }
762
763 /*
764  * Initialize the kernel memory allocator
765  */
766 /* ARGSUSED*/
767 static void
768 mallocinit(void *dummy)
769 {
770         int i;
771         uint8_t indx;
772
773         mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
774
775         kmeminit();
776
777         uma_startup2();
778
779         mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
780 #ifdef INVARIANTS
781             mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
782 #else
783             NULL, NULL, NULL, NULL,
784 #endif
785             UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
786         for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
787                 int size = kmemzones[indx].kz_size;
788                 char *name = kmemzones[indx].kz_name;
789                 int subzone;
790
791                 for (subzone = 0; subzone < numzones; subzone++) {
792                         kmemzones[indx].kz_zone[subzone] =
793                             uma_zcreate(name, size,
794 #ifdef INVARIANTS
795                             mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
796 #else
797                             NULL, NULL, NULL, NULL,
798 #endif
799                             UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
800                 }                   
801                 for (;i <= size; i+= KMEM_ZBASE)
802                         kmemsize[i >> KMEM_ZSHIFT] = indx;
803                 
804         }
805 }
806 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, mallocinit, NULL);
807
808 void
809 malloc_init(void *data)
810 {
811         struct malloc_type_internal *mtip;
812         struct malloc_type *mtp;
813
814         KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
815
816         mtp = data;
817         if (mtp->ks_magic != M_MAGIC)
818                 panic("malloc_init: bad malloc type magic");
819
820         mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
821         mtp->ks_handle = mtip;
822         mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
823
824         mtx_lock(&malloc_mtx);
825         mtp->ks_next = kmemstatistics;
826         kmemstatistics = mtp;
827         kmemcount++;
828         mtx_unlock(&malloc_mtx);
829 }
830
831 void
832 malloc_uninit(void *data)
833 {
834         struct malloc_type_internal *mtip;
835         struct malloc_type_stats *mtsp;
836         struct malloc_type *mtp, *temp;
837         uma_slab_t slab;
838         long temp_allocs, temp_bytes;
839         int i;
840
841         mtp = data;
842         KASSERT(mtp->ks_magic == M_MAGIC,
843             ("malloc_uninit: bad malloc type magic"));
844         KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
845
846         mtx_lock(&malloc_mtx);
847         mtip = mtp->ks_handle;
848         mtp->ks_handle = NULL;
849         if (mtp != kmemstatistics) {
850                 for (temp = kmemstatistics; temp != NULL;
851                     temp = temp->ks_next) {
852                         if (temp->ks_next == mtp) {
853                                 temp->ks_next = mtp->ks_next;
854                                 break;
855                         }
856                 }
857                 KASSERT(temp,
858                     ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
859         } else
860                 kmemstatistics = mtp->ks_next;
861         kmemcount--;
862         mtx_unlock(&malloc_mtx);
863
864         /*
865          * Look for memory leaks.
866          */
867         temp_allocs = temp_bytes = 0;
868         for (i = 0; i < MAXCPU; i++) {
869                 mtsp = &mtip->mti_stats[i];
870                 temp_allocs += mtsp->mts_numallocs;
871                 temp_allocs -= mtsp->mts_numfrees;
872                 temp_bytes += mtsp->mts_memalloced;
873                 temp_bytes -= mtsp->mts_memfreed;
874         }
875         if (temp_allocs > 0 || temp_bytes > 0) {
876                 printf("Warning: memory type %s leaked memory on destroy "
877                     "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
878                     temp_allocs, temp_bytes);
879         }
880
881         slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
882         uma_zfree_arg(mt_zone, mtip, slab);
883 }
884
885 struct malloc_type *
886 malloc_desc2type(const char *desc)
887 {
888         struct malloc_type *mtp;
889
890         mtx_assert(&malloc_mtx, MA_OWNED);
891         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
892                 if (strcmp(mtp->ks_shortdesc, desc) == 0)
893                         return (mtp);
894         }
895         return (NULL);
896 }
897
898 static int
899 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
900 {
901         struct malloc_type_stream_header mtsh;
902         struct malloc_type_internal *mtip;
903         struct malloc_type_header mth;
904         struct malloc_type *mtp;
905         int error, i;
906         struct sbuf sbuf;
907
908         error = sysctl_wire_old_buffer(req, 0);
909         if (error != 0)
910                 return (error);
911         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
912         mtx_lock(&malloc_mtx);
913
914         /*
915          * Insert stream header.
916          */
917         bzero(&mtsh, sizeof(mtsh));
918         mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
919         mtsh.mtsh_maxcpus = MAXCPU;
920         mtsh.mtsh_count = kmemcount;
921         (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
922
923         /*
924          * Insert alternating sequence of type headers and type statistics.
925          */
926         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
927                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
928
929                 /*
930                  * Insert type header.
931                  */
932                 bzero(&mth, sizeof(mth));
933                 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
934                 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
935
936                 /*
937                  * Insert type statistics for each CPU.
938                  */
939                 for (i = 0; i < MAXCPU; i++) {
940                         (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
941                             sizeof(mtip->mti_stats[i]));
942                 }
943         }
944         mtx_unlock(&malloc_mtx);
945         error = sbuf_finish(&sbuf);
946         sbuf_delete(&sbuf);
947         return (error);
948 }
949
950 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
951     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
952     "Return malloc types");
953
954 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
955     "Count of kernel malloc types");
956
957 void
958 malloc_type_list(malloc_type_list_func_t *func, void *arg)
959 {
960         struct malloc_type *mtp, **bufmtp;
961         int count, i;
962         size_t buflen;
963
964         mtx_lock(&malloc_mtx);
965 restart:
966         mtx_assert(&malloc_mtx, MA_OWNED);
967         count = kmemcount;
968         mtx_unlock(&malloc_mtx);
969
970         buflen = sizeof(struct malloc_type *) * count;
971         bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
972
973         mtx_lock(&malloc_mtx);
974
975         if (count < kmemcount) {
976                 free(bufmtp, M_TEMP);
977                 goto restart;
978         }
979
980         for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
981                 bufmtp[i] = mtp;
982
983         mtx_unlock(&malloc_mtx);
984
985         for (i = 0; i < count; i++)
986                 (func)(bufmtp[i], arg);
987
988         free(bufmtp, M_TEMP);
989 }
990
991 #ifdef DDB
992 DB_SHOW_COMMAND(malloc, db_show_malloc)
993 {
994         struct malloc_type_internal *mtip;
995         struct malloc_type *mtp;
996         uint64_t allocs, frees;
997         uint64_t alloced, freed;
998         int i;
999
1000         db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
1001             "Requests");
1002         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1003                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1004                 allocs = 0;
1005                 frees = 0;
1006                 alloced = 0;
1007                 freed = 0;
1008                 for (i = 0; i < MAXCPU; i++) {
1009                         allocs += mtip->mti_stats[i].mts_numallocs;
1010                         frees += mtip->mti_stats[i].mts_numfrees;
1011                         alloced += mtip->mti_stats[i].mts_memalloced;
1012                         freed += mtip->mti_stats[i].mts_memfreed;
1013                 }
1014                 db_printf("%18s %12ju %12juK %12ju\n",
1015                     mtp->ks_shortdesc, allocs - frees,
1016                     (alloced - freed + 1023) / 1024, allocs);
1017                 if (db_pager_quit)
1018                         break;
1019         }
1020 }
1021
1022 #if MALLOC_DEBUG_MAXZONES > 1
1023 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1024 {
1025         struct malloc_type_internal *mtip;
1026         struct malloc_type *mtp;
1027         u_int subzone;
1028
1029         if (!have_addr) {
1030                 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1031                 return;
1032         }
1033         mtp = (void *)addr;
1034         if (mtp->ks_magic != M_MAGIC) {
1035                 db_printf("Magic %lx does not match expected %x\n",
1036                     mtp->ks_magic, M_MAGIC);
1037                 return;
1038         }
1039
1040         mtip = mtp->ks_handle;
1041         subzone = mtip->mti_zone;
1042
1043         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1044                 mtip = mtp->ks_handle;
1045                 if (mtip->mti_zone != subzone)
1046                         continue;
1047                 db_printf("%s\n", mtp->ks_shortdesc);
1048                 if (db_pager_quit)
1049                         break;
1050         }
1051 }
1052 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1053 #endif /* DDB */
1054
1055 #ifdef MALLOC_PROFILE
1056
1057 static int
1058 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1059 {
1060         struct sbuf sbuf;
1061         uint64_t count;
1062         uint64_t waste;
1063         uint64_t mem;
1064         int error;
1065         int rsize;
1066         int size;
1067         int i;
1068
1069         waste = 0;
1070         mem = 0;
1071
1072         error = sysctl_wire_old_buffer(req, 0);
1073         if (error != 0)
1074                 return (error);
1075         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1076         sbuf_printf(&sbuf, 
1077             "\n  Size                    Requests  Real Size\n");
1078         for (i = 0; i < KMEM_ZSIZE; i++) {
1079                 size = i << KMEM_ZSHIFT;
1080                 rsize = kmemzones[kmemsize[i]].kz_size;
1081                 count = (long long unsigned)krequests[i];
1082
1083                 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1084                     (unsigned long long)count, rsize);
1085
1086                 if ((rsize * count) > (size * count))
1087                         waste += (rsize * count) - (size * count);
1088                 mem += (rsize * count);
1089         }
1090         sbuf_printf(&sbuf,
1091             "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1092             (unsigned long long)mem, (unsigned long long)waste);
1093         error = sbuf_finish(&sbuf);
1094         sbuf_delete(&sbuf);
1095         return (error);
1096 }
1097
1098 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1099     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1100 #endif /* MALLOC_PROFILE */