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