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