]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_malloc.c
MFV: r329021
[FreeBSD/FreeBSD.git] / sys / kern / kern_malloc.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1987, 1991, 1993
5  *      The Regents of the University of California.
6  * Copyright (c) 2005-2009 Robert N. M. Watson
7  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> (mallocarray)
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)kern_malloc.c       8.3 (Berkeley) 1/4/94
35  */
36
37 /*
38  * Kernel malloc(9) implementation -- general purpose kernel memory allocator
39  * based on memory types.  Back end is implemented using the UMA(9) zone
40  * allocator.  A set of fixed-size buckets are used for smaller allocations,
41  * and a special UMA allocation interface is used for larger allocations.
42  * Callers declare memory types, and statistics are maintained independently
43  * for each memory type.  Statistics are maintained per-CPU for performance
44  * reasons.  See malloc(9) and comments in malloc.h for a detailed
45  * description.
46  */
47
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
50
51 #include "opt_ddb.h"
52 #include "opt_vm.h"
53
54 #include <sys/param.h>
55 #include <sys/systm.h>
56 #include <sys/kdb.h>
57 #include <sys/kernel.h>
58 #include <sys/lock.h>
59 #include <sys/malloc.h>
60 #include <sys/mutex.h>
61 #include <sys/vmmeter.h>
62 #include <sys/proc.h>
63 #include <sys/sbuf.h>
64 #include <sys/sysctl.h>
65 #include <sys/time.h>
66 #include <sys/vmem.h>
67
68 #include <vm/vm.h>
69 #include <vm/pmap.h>
70 #include <vm/vm_pageout.h>
71 #include <vm/vm_param.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_extern.h>
74 #include <vm/vm_map.h>
75 #include <vm/vm_page.h>
76 #include <vm/uma.h>
77 #include <vm/uma_int.h>
78 #include <vm/uma_dbg.h>
79
80 #ifdef DEBUG_MEMGUARD
81 #include <vm/memguard.h>
82 #endif
83 #ifdef DEBUG_REDZONE
84 #include <vm/redzone.h>
85 #endif
86
87 #if defined(INVARIANTS) && defined(__i386__)
88 #include <machine/cpu.h>
89 #endif
90
91 #include <ddb/ddb.h>
92
93 #ifdef KDTRACE_HOOKS
94 #include <sys/dtrace_bsd.h>
95
96 dtrace_malloc_probe_func_t      dtrace_malloc_probe;
97 #endif
98
99 extern void     uma_startup2(void);
100
101 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) ||             \
102     defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
103 #define MALLOC_DEBUG    1
104 #endif
105
106 /*
107  * When realloc() is called, if the new size is sufficiently smaller than
108  * the old size, realloc() will allocate a new, smaller block to avoid
109  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
110  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
111  */
112 #ifndef REALLOC_FRACTION
113 #define REALLOC_FRACTION        1       /* new block if <= half the size */
114 #endif
115
116 /*
117  * Centrally define some common malloc types.
118  */
119 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
120 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
121 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
122
123 static struct malloc_type *kmemstatistics;
124 static int kmemcount;
125
126 #define KMEM_ZSHIFT     4
127 #define KMEM_ZBASE      16
128 #define KMEM_ZMASK      (KMEM_ZBASE - 1)
129
130 #define KMEM_ZMAX       65536
131 #define KMEM_ZSIZE      (KMEM_ZMAX >> KMEM_ZSHIFT)
132 static uint8_t kmemsize[KMEM_ZSIZE + 1];
133
134 #ifndef MALLOC_DEBUG_MAXZONES
135 #define MALLOC_DEBUG_MAXZONES   1
136 #endif
137 static int numzones = MALLOC_DEBUG_MAXZONES;
138
139 /*
140  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
141  * of various sizes.
142  *
143  * XXX: The comment here used to read "These won't be powers of two for
144  * long."  It's possible that a significant amount of wasted memory could be
145  * recovered by tuning the sizes of these buckets.
146  */
147 struct {
148         int kz_size;
149         char *kz_name;
150         uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
151 } kmemzones[] = {
152         {16, "16", },
153         {32, "32", },
154         {64, "64", },
155         {128, "128", },
156         {256, "256", },
157         {512, "512", },
158         {1024, "1024", },
159         {2048, "2048", },
160         {4096, "4096", },
161         {8192, "8192", },
162         {16384, "16384", },
163         {32768, "32768", },
164         {65536, "65536", },
165         {0, NULL},
166 };
167
168 /*
169  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
170  * types are described by a data structure passed by the declaring code, but
171  * the malloc(9) implementation has its own data structure describing the
172  * type and statistics.  This permits the malloc(9)-internal data structures
173  * to be modified without breaking binary-compiled kernel modules that
174  * declare malloc types.
175  */
176 static uma_zone_t mt_zone;
177
178 u_long vm_kmem_size;
179 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
180     "Size of kernel memory");
181
182 static u_long kmem_zmax = KMEM_ZMAX;
183 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
184     "Maximum allocation size that malloc(9) would use UMA as backend");
185
186 static u_long vm_kmem_size_min;
187 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
188     "Minimum size of kernel memory");
189
190 static u_long vm_kmem_size_max;
191 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
192     "Maximum size of kernel memory");
193
194 static u_int vm_kmem_size_scale;
195 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
196     "Scale factor for kernel memory size");
197
198 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
199 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
200     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
201     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
202
203 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
204 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
205     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
206     sysctl_kmem_map_free, "LU", "Free space in kmem");
207
208 /*
209  * The malloc_mtx protects the kmemstatistics linked list.
210  */
211 struct mtx malloc_mtx;
212
213 #ifdef MALLOC_PROFILE
214 uint64_t krequests[KMEM_ZSIZE + 1];
215
216 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
217 #endif
218
219 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
220
221 /*
222  * time_uptime of the last malloc(9) failure (induced or real).
223  */
224 static time_t t_malloc_fail;
225
226 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
227 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
228     "Kernel malloc debugging options");
229 #endif
230
231 /*
232  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
233  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
234  */
235 #ifdef MALLOC_MAKE_FAILURES
236 static int malloc_failure_rate;
237 static int malloc_nowait_count;
238 static int malloc_failure_count;
239 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
240     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
241 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
242     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
243 #endif
244
245 static int
246 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
247 {
248         u_long size;
249
250         size = uma_size();
251         return (sysctl_handle_long(oidp, &size, 0, req));
252 }
253
254 static int
255 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
256 {
257         u_long size, limit;
258
259         /* The sysctl is unsigned, implement as a saturation value. */
260         size = uma_size();
261         limit = uma_limit();
262         if (size > limit)
263                 size = 0;
264         else
265                 size = limit - size;
266         return (sysctl_handle_long(oidp, &size, 0, req));
267 }
268
269 /*
270  * malloc(9) uma zone separation -- sub-page buffer overruns in one
271  * malloc type will affect only a subset of other malloc types.
272  */
273 #if MALLOC_DEBUG_MAXZONES > 1
274 static void
275 tunable_set_numzones(void)
276 {
277
278         TUNABLE_INT_FETCH("debug.malloc.numzones",
279             &numzones);
280
281         /* Sanity check the number of malloc uma zones. */
282         if (numzones <= 0)
283                 numzones = 1;
284         if (numzones > MALLOC_DEBUG_MAXZONES)
285                 numzones = MALLOC_DEBUG_MAXZONES;
286 }
287 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
288 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
289     &numzones, 0, "Number of malloc uma subzones");
290
291 /*
292  * Any number that changes regularly is an okay choice for the
293  * offset.  Build numbers are pretty good of you have them.
294  */
295 static u_int zone_offset = __FreeBSD_version;
296 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
297 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
298     &zone_offset, 0, "Separate malloc types by examining the "
299     "Nth character in the malloc type short description.");
300
301 static u_int
302 mtp_get_subzone(const char *desc)
303 {
304         size_t len;
305         u_int val;
306
307         if (desc == NULL || (len = strlen(desc)) == 0)
308                 return (0);
309         val = desc[zone_offset % len];
310         return (val % numzones);
311 }
312 #elif MALLOC_DEBUG_MAXZONES == 0
313 #error "MALLOC_DEBUG_MAXZONES must be positive."
314 #else
315 static inline u_int
316 mtp_get_subzone(const char *desc)
317 {
318
319         return (0);
320 }
321 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
322
323 int
324 malloc_last_fail(void)
325 {
326
327         return (time_uptime - t_malloc_fail);
328 }
329
330 /*
331  * An allocation has succeeded -- update malloc type statistics for the
332  * amount of bucket size.  Occurs within a critical section so that the
333  * thread isn't preempted and doesn't migrate while updating per-PCU
334  * statistics.
335  */
336 static void
337 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
338     int zindx)
339 {
340         struct malloc_type_internal *mtip;
341         struct malloc_type_stats *mtsp;
342
343         critical_enter();
344         mtip = mtp->ks_handle;
345         mtsp = &mtip->mti_stats[curcpu];
346         if (size > 0) {
347                 mtsp->mts_memalloced += size;
348                 mtsp->mts_numallocs++;
349         }
350         if (zindx != -1)
351                 mtsp->mts_size |= 1 << zindx;
352
353 #ifdef KDTRACE_HOOKS
354         if (dtrace_malloc_probe != NULL) {
355                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
356                 if (probe_id != 0)
357                         (dtrace_malloc_probe)(probe_id,
358                             (uintptr_t) mtp, (uintptr_t) mtip,
359                             (uintptr_t) mtsp, size, zindx);
360         }
361 #endif
362
363         critical_exit();
364 }
365
366 void
367 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
368 {
369
370         if (size > 0)
371                 malloc_type_zone_allocated(mtp, size, -1);
372 }
373
374 /*
375  * A free operation has occurred -- update malloc type statistics for the
376  * amount of the bucket size.  Occurs within a critical section so that the
377  * thread isn't preempted and doesn't migrate while updating per-CPU
378  * statistics.
379  */
380 void
381 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
382 {
383         struct malloc_type_internal *mtip;
384         struct malloc_type_stats *mtsp;
385
386         critical_enter();
387         mtip = mtp->ks_handle;
388         mtsp = &mtip->mti_stats[curcpu];
389         mtsp->mts_memfreed += size;
390         mtsp->mts_numfrees++;
391
392 #ifdef KDTRACE_HOOKS
393         if (dtrace_malloc_probe != NULL) {
394                 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
395                 if (probe_id != 0)
396                         (dtrace_malloc_probe)(probe_id,
397                             (uintptr_t) mtp, (uintptr_t) mtip,
398                             (uintptr_t) mtsp, size, 0);
399         }
400 #endif
401
402         critical_exit();
403 }
404
405 /*
406  *      contigmalloc:
407  *
408  *      Allocate a block of physically contiguous memory.
409  *
410  *      If M_NOWAIT is set, this routine will not block and return NULL if
411  *      the allocation fails.
412  */
413 void *
414 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
415     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
416     vm_paddr_t boundary)
417 {
418         void *ret;
419
420         ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
421             alignment, boundary, VM_MEMATTR_DEFAULT);
422         if (ret != NULL)
423                 malloc_type_allocated(type, round_page(size));
424         return (ret);
425 }
426
427 void *
428 contigmalloc_domain(unsigned long size, struct malloc_type *type,
429     int domain, int flags, vm_paddr_t low, vm_paddr_t high,
430     unsigned long alignment, vm_paddr_t boundary)
431 {
432         void *ret;
433
434         ret = (void *)kmem_alloc_contig_domain(domain, size, flags, low, high,
435             alignment, boundary, VM_MEMATTR_DEFAULT);
436         if (ret != NULL)
437                 malloc_type_allocated(type, round_page(size));
438         return (ret);
439 }
440
441 /*
442  *      contigfree:
443  *
444  *      Free a block of memory allocated by contigmalloc.
445  *
446  *      This routine may not block.
447  */
448 void
449 contigfree(void *addr, unsigned long size, struct malloc_type *type)
450 {
451
452         kmem_free(kernel_arena, (vm_offset_t)addr, size);
453         malloc_type_freed(type, round_page(size));
454 }
455
456 #ifdef MALLOC_DEBUG
457 static int
458 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
459     int flags)
460 {
461 #ifdef INVARIANTS
462         int indx;
463
464         KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
465         /*
466          * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
467          */
468         indx = flags & (M_WAITOK | M_NOWAIT);
469         if (indx != M_NOWAIT && indx != M_WAITOK) {
470                 static  struct timeval lasterr;
471                 static  int curerr, once;
472                 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
473                         printf("Bad malloc flags: %x\n", indx);
474                         kdb_backtrace();
475                         flags |= M_WAITOK;
476                         once++;
477                 }
478         }
479 #endif
480 #ifdef MALLOC_MAKE_FAILURES
481         if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
482                 atomic_add_int(&malloc_nowait_count, 1);
483                 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
484                         atomic_add_int(&malloc_failure_count, 1);
485                         t_malloc_fail = time_uptime;
486                         *vap = NULL;
487                         return (EJUSTRETURN);
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         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
495             ("malloc: called with spinlock or critical section held"));
496
497 #ifdef DEBUG_MEMGUARD
498         if (memguard_cmp_mtp(mtp, *sizep)) {
499                 *vap = memguard_alloc(*sizep, flags);
500                 if (*vap != NULL)
501                         return (EJUSTRETURN);
502                 /* This is unfortunate but should not be fatal. */
503         }
504 #endif
505
506 #ifdef DEBUG_REDZONE
507         *sizep = redzone_size_ntor(*sizep);
508 #endif
509
510         return (0);
511 }
512 #endif
513
514 /*
515  *      malloc:
516  *
517  *      Allocate a block of memory.
518  *
519  *      If M_NOWAIT is set, this routine will not block and return NULL if
520  *      the allocation fails.
521  */
522 void *
523 malloc(size_t size, struct malloc_type *mtp, int flags)
524 {
525         int indx;
526         struct malloc_type_internal *mtip;
527         caddr_t va;
528         uma_zone_t zone;
529 #if defined(DEBUG_REDZONE)
530         unsigned long osize = size;
531 #endif
532
533 #ifdef MALLOC_DEBUG
534         if (malloc_dbg(&va, &size, mtp, flags) != 0)
535                 return (va);
536 #endif
537
538         if (size <= kmem_zmax) {
539                 mtip = mtp->ks_handle;
540                 if (size & KMEM_ZMASK)
541                         size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
542                 indx = kmemsize[size >> KMEM_ZSHIFT];
543                 KASSERT(mtip->mti_zone < numzones,
544                     ("mti_zone %u out of range %d",
545                     mtip->mti_zone, numzones));
546                 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
547 #ifdef MALLOC_PROFILE
548                 krequests[size >> KMEM_ZSHIFT]++;
549 #endif
550                 va = uma_zalloc(zone, flags);
551                 if (va != NULL)
552                         size = zone->uz_size;
553                 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
554         } else {
555                 size = roundup(size, PAGE_SIZE);
556                 zone = NULL;
557                 va = uma_large_malloc(size, flags);
558                 malloc_type_allocated(mtp, va == NULL ? 0 : size);
559         }
560         if (flags & M_WAITOK)
561                 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
562         else if (va == NULL)
563                 t_malloc_fail = time_uptime;
564 #ifdef DEBUG_REDZONE
565         if (va != NULL)
566                 va = redzone_setup(va, osize);
567 #endif
568         return ((void *) va);
569 }
570
571 void *
572 malloc_domain(size_t size, struct malloc_type *mtp, int domain,
573     int flags)
574 {
575         int indx;
576         struct malloc_type_internal *mtip;
577         caddr_t va;
578         uma_zone_t zone;
579 #if defined(DEBUG_REDZONE)
580         unsigned long osize = size;
581 #endif
582
583 #ifdef MALLOC_DEBUG
584         if (malloc_dbg(&va, &size, mtp, flags) != 0)
585                 return (va);
586 #endif
587         if (size <= kmem_zmax) {
588                 mtip = mtp->ks_handle;
589                 if (size & KMEM_ZMASK)
590                         size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
591                 indx = kmemsize[size >> KMEM_ZSHIFT];
592                 KASSERT(mtip->mti_zone < numzones,
593                     ("mti_zone %u out of range %d",
594                     mtip->mti_zone, numzones));
595                 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
596 #ifdef MALLOC_PROFILE
597                 krequests[size >> KMEM_ZSHIFT]++;
598 #endif
599                 va = uma_zalloc_domain(zone, NULL, domain, flags);
600                 if (va != NULL)
601                         size = zone->uz_size;
602                 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
603         } else {
604                 size = roundup(size, PAGE_SIZE);
605                 zone = NULL;
606                 va = uma_large_malloc_domain(size, domain, flags);
607                 malloc_type_allocated(mtp, va == NULL ? 0 : size);
608         }
609         if (flags & M_WAITOK)
610                 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
611         else if (va == NULL)
612                 t_malloc_fail = time_uptime;
613 #ifdef DEBUG_REDZONE
614         if (va != NULL)
615                 va = redzone_setup(va, osize);
616 #endif
617         return ((void *) va);
618 }
619
620 void *
621 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
622 {
623
624         if (WOULD_OVERFLOW(nmemb, size))
625                 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
626
627         return (malloc(size * nmemb, type, flags));
628 }
629
630 #ifdef INVARIANTS
631 static void
632 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
633 {
634         struct malloc_type **mtpp = addr;
635
636         /*
637          * Cache a pointer to the malloc_type that most recently freed
638          * this memory here.  This way we know who is most likely to
639          * have stepped on it later.
640          *
641          * This code assumes that size is a multiple of 8 bytes for
642          * 64 bit machines
643          */
644         mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
645         mtpp += (size - sizeof(struct malloc_type *)) /
646             sizeof(struct malloc_type *);
647         *mtpp = mtp;
648 }
649 #endif
650
651 #ifdef MALLOC_DEBUG
652 static int
653 free_dbg(void **addrp, struct malloc_type *mtp)
654 {
655         void *addr;
656
657         addr = *addrp;
658         KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
659         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
660             ("free: called with spinlock or critical section held"));
661
662         /* free(NULL, ...) does nothing */
663         if (addr == NULL)
664                 return (EJUSTRETURN);
665
666 #ifdef DEBUG_MEMGUARD
667         if (is_memguard_addr(addr)) {
668                 memguard_free(addr);
669                 return (EJUSTRETURN);
670         }
671 #endif
672
673 #ifdef DEBUG_REDZONE
674         redzone_check(addr);
675         *addrp = redzone_addr_ntor(addr);
676 #endif
677
678         return (0);
679 }
680 #endif
681
682 /*
683  *      free:
684  *
685  *      Free a block of memory allocated by malloc.
686  *
687  *      This routine may not block.
688  */
689 void
690 free(void *addr, struct malloc_type *mtp)
691 {
692         uma_slab_t slab;
693         u_long size;
694
695 #ifdef MALLOC_DEBUG
696         if (free_dbg(&addr, mtp) != 0)
697                 return;
698 #endif
699         /* free(NULL, ...) does nothing */
700         if (addr == NULL)
701                 return;
702
703         slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
704         if (slab == NULL)
705                 panic("free: address %p(%p) has not been allocated.\n",
706                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
707
708         if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
709                 size = slab->us_keg->uk_size;
710 #ifdef INVARIANTS
711                 free_save_type(addr, mtp, size);
712 #endif
713                 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
714         } else {
715                 size = slab->us_size;
716                 uma_large_free(slab);
717         }
718         malloc_type_freed(mtp, size);
719 }
720
721 void
722 free_domain(void *addr, struct malloc_type *mtp)
723 {
724         uma_slab_t slab;
725         u_long size;
726
727 #ifdef MALLOC_DEBUG
728         if (free_dbg(&addr, mtp) != 0)
729                 return;
730 #endif
731
732         /* free(NULL, ...) does nothing */
733         if (addr == NULL)
734                 return;
735
736         slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
737         if (slab == NULL)
738                 panic("free_domain: address %p(%p) has not been allocated.\n",
739                     addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
740
741         if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
742                 size = slab->us_keg->uk_size;
743 #ifdef INVARIANTS
744                 free_save_type(addr, mtp, size);
745 #endif
746                 uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones),
747                     addr, slab);
748         } else {
749                 size = slab->us_size;
750                 uma_large_free(slab);
751         }
752         malloc_type_freed(mtp, size);
753 }
754
755 /*
756  *      realloc: change the size of a memory block
757  */
758 void *
759 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
760 {
761         uma_slab_t slab;
762         unsigned long alloc;
763         void *newaddr;
764
765         KASSERT(mtp->ks_magic == M_MAGIC,
766             ("realloc: bad malloc type magic"));
767         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
768             ("realloc: called with spinlock or critical section held"));
769
770         /* realloc(NULL, ...) is equivalent to malloc(...) */
771         if (addr == NULL)
772                 return (malloc(size, mtp, flags));
773
774         /*
775          * XXX: Should report free of old memory and alloc of new memory to
776          * per-CPU stats.
777          */
778
779 #ifdef DEBUG_MEMGUARD
780         if (is_memguard_addr(addr))
781                 return (memguard_realloc(addr, size, mtp, flags));
782 #endif
783
784 #ifdef DEBUG_REDZONE
785         slab = NULL;
786         alloc = redzone_get_size(addr);
787 #else
788         slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
789
790         /* Sanity check */
791         KASSERT(slab != NULL,
792             ("realloc: address %p out of range", (void *)addr));
793
794         /* Get the size of the original block */
795         if (!(slab->us_flags & UMA_SLAB_MALLOC))
796                 alloc = slab->us_keg->uk_size;
797         else
798                 alloc = slab->us_size;
799
800         /* Reuse the original block if appropriate */
801         if (size <= alloc
802             && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
803                 return (addr);
804 #endif /* !DEBUG_REDZONE */
805
806         /* Allocate a new, bigger (or smaller) block */
807         if ((newaddr = malloc(size, mtp, flags)) == NULL)
808                 return (NULL);
809
810         /* Copy over original contents */
811         bcopy(addr, newaddr, min(size, alloc));
812         free(addr, mtp);
813         return (newaddr);
814 }
815
816 /*
817  *      reallocf: same as realloc() but free memory on failure.
818  */
819 void *
820 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
821 {
822         void *mem;
823
824         if ((mem = realloc(addr, size, mtp, flags)) == NULL)
825                 free(addr, mtp);
826         return (mem);
827 }
828
829 #ifndef __sparc64__
830 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
831 #endif
832
833 /*
834  * Initialize the kernel memory (kmem) arena.
835  */
836 void
837 kmeminit(void)
838 {
839         u_long mem_size;
840         u_long tmp;
841
842 #ifdef VM_KMEM_SIZE
843         if (vm_kmem_size == 0)
844                 vm_kmem_size = VM_KMEM_SIZE;
845 #endif
846 #ifdef VM_KMEM_SIZE_MIN
847         if (vm_kmem_size_min == 0)
848                 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
849 #endif
850 #ifdef VM_KMEM_SIZE_MAX
851         if (vm_kmem_size_max == 0)
852                 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
853 #endif
854         /*
855          * Calculate the amount of kernel virtual address (KVA) space that is
856          * preallocated to the kmem arena.  In order to support a wide range
857          * of machines, it is a function of the physical memory size,
858          * specifically,
859          *
860          *      min(max(physical memory size / VM_KMEM_SIZE_SCALE,
861          *          VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
862          *
863          * Every architecture must define an integral value for
864          * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
865          * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
866          * ceiling on this preallocation, are optional.  Typically,
867          * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
868          * a given architecture.
869          */
870         mem_size = vm_cnt.v_page_count;
871         if (mem_size <= 32768) /* delphij XXX 128MB */
872                 kmem_zmax = PAGE_SIZE;
873
874         if (vm_kmem_size_scale < 1)
875                 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
876
877         /*
878          * Check if we should use defaults for the "vm_kmem_size"
879          * variable:
880          */
881         if (vm_kmem_size == 0) {
882                 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
883
884                 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
885                         vm_kmem_size = vm_kmem_size_min;
886                 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
887                         vm_kmem_size = vm_kmem_size_max;
888         }
889
890         /*
891          * The amount of KVA space that is preallocated to the
892          * kmem arena can be set statically at compile-time or manually
893          * through the kernel environment.  However, it is still limited to
894          * twice the physical memory size, which has been sufficient to handle
895          * the most severe cases of external fragmentation in the kmem arena. 
896          */
897         if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
898                 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
899
900         vm_kmem_size = round_page(vm_kmem_size);
901 #ifdef DEBUG_MEMGUARD
902         tmp = memguard_fudge(vm_kmem_size, kernel_map);
903 #else
904         tmp = vm_kmem_size;
905 #endif
906         uma_set_limit(tmp);
907
908 #ifdef DEBUG_MEMGUARD
909         /*
910          * Initialize MemGuard if support compiled in.  MemGuard is a
911          * replacement allocator used for detecting tamper-after-free
912          * scenarios as they occur.  It is only used for debugging.
913          */
914         memguard_init(kernel_arena);
915 #endif
916 }
917
918 /*
919  * Initialize the kernel memory allocator
920  */
921 /* ARGSUSED*/
922 static void
923 mallocinit(void *dummy)
924 {
925         int i;
926         uint8_t indx;
927
928         mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
929
930         kmeminit();
931
932         uma_startup2();
933
934         if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
935                 kmem_zmax = KMEM_ZMAX;
936
937         mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
938 #ifdef INVARIANTS
939             mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
940 #else
941             NULL, NULL, NULL, NULL,
942 #endif
943             UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
944         for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
945                 int size = kmemzones[indx].kz_size;
946                 char *name = kmemzones[indx].kz_name;
947                 int subzone;
948
949                 for (subzone = 0; subzone < numzones; subzone++) {
950                         kmemzones[indx].kz_zone[subzone] =
951                             uma_zcreate(name, size,
952 #ifdef INVARIANTS
953                             mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
954 #else
955                             NULL, NULL, NULL, NULL,
956 #endif
957                             UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
958                 }                   
959                 for (;i <= size; i+= KMEM_ZBASE)
960                         kmemsize[i >> KMEM_ZSHIFT] = indx;
961
962         }
963 }
964 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
965
966 void
967 malloc_init(void *data)
968 {
969         struct malloc_type_internal *mtip;
970         struct malloc_type *mtp;
971
972         KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
973
974         mtp = data;
975         if (mtp->ks_magic != M_MAGIC)
976                 panic("malloc_init: bad malloc type magic");
977
978         mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
979         mtp->ks_handle = mtip;
980         mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
981
982         mtx_lock(&malloc_mtx);
983         mtp->ks_next = kmemstatistics;
984         kmemstatistics = mtp;
985         kmemcount++;
986         mtx_unlock(&malloc_mtx);
987 }
988
989 void
990 malloc_uninit(void *data)
991 {
992         struct malloc_type_internal *mtip;
993         struct malloc_type_stats *mtsp;
994         struct malloc_type *mtp, *temp;
995         uma_slab_t slab;
996         long temp_allocs, temp_bytes;
997         int i;
998
999         mtp = data;
1000         KASSERT(mtp->ks_magic == M_MAGIC,
1001             ("malloc_uninit: bad malloc type magic"));
1002         KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1003
1004         mtx_lock(&malloc_mtx);
1005         mtip = mtp->ks_handle;
1006         mtp->ks_handle = NULL;
1007         if (mtp != kmemstatistics) {
1008                 for (temp = kmemstatistics; temp != NULL;
1009                     temp = temp->ks_next) {
1010                         if (temp->ks_next == mtp) {
1011                                 temp->ks_next = mtp->ks_next;
1012                                 break;
1013                         }
1014                 }
1015                 KASSERT(temp,
1016                     ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1017         } else
1018                 kmemstatistics = mtp->ks_next;
1019         kmemcount--;
1020         mtx_unlock(&malloc_mtx);
1021
1022         /*
1023          * Look for memory leaks.
1024          */
1025         temp_allocs = temp_bytes = 0;
1026         for (i = 0; i < MAXCPU; i++) {
1027                 mtsp = &mtip->mti_stats[i];
1028                 temp_allocs += mtsp->mts_numallocs;
1029                 temp_allocs -= mtsp->mts_numfrees;
1030                 temp_bytes += mtsp->mts_memalloced;
1031                 temp_bytes -= mtsp->mts_memfreed;
1032         }
1033         if (temp_allocs > 0 || temp_bytes > 0) {
1034                 printf("Warning: memory type %s leaked memory on destroy "
1035                     "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1036                     temp_allocs, temp_bytes);
1037         }
1038
1039         slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
1040         uma_zfree_arg(mt_zone, mtip, slab);
1041 }
1042
1043 struct malloc_type *
1044 malloc_desc2type(const char *desc)
1045 {
1046         struct malloc_type *mtp;
1047
1048         mtx_assert(&malloc_mtx, MA_OWNED);
1049         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1050                 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1051                         return (mtp);
1052         }
1053         return (NULL);
1054 }
1055
1056 static int
1057 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1058 {
1059         struct malloc_type_stream_header mtsh;
1060         struct malloc_type_internal *mtip;
1061         struct malloc_type_header mth;
1062         struct malloc_type *mtp;
1063         int error, i;
1064         struct sbuf sbuf;
1065
1066         error = sysctl_wire_old_buffer(req, 0);
1067         if (error != 0)
1068                 return (error);
1069         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1070         sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1071         mtx_lock(&malloc_mtx);
1072
1073         /*
1074          * Insert stream header.
1075          */
1076         bzero(&mtsh, sizeof(mtsh));
1077         mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1078         mtsh.mtsh_maxcpus = MAXCPU;
1079         mtsh.mtsh_count = kmemcount;
1080         (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1081
1082         /*
1083          * Insert alternating sequence of type headers and type statistics.
1084          */
1085         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1086                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1087
1088                 /*
1089                  * Insert type header.
1090                  */
1091                 bzero(&mth, sizeof(mth));
1092                 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1093                 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1094
1095                 /*
1096                  * Insert type statistics for each CPU.
1097                  */
1098                 for (i = 0; i < MAXCPU; i++) {
1099                         (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
1100                             sizeof(mtip->mti_stats[i]));
1101                 }
1102         }
1103         mtx_unlock(&malloc_mtx);
1104         error = sbuf_finish(&sbuf);
1105         sbuf_delete(&sbuf);
1106         return (error);
1107 }
1108
1109 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1110     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1111     "Return malloc types");
1112
1113 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1114     "Count of kernel malloc types");
1115
1116 void
1117 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1118 {
1119         struct malloc_type *mtp, **bufmtp;
1120         int count, i;
1121         size_t buflen;
1122
1123         mtx_lock(&malloc_mtx);
1124 restart:
1125         mtx_assert(&malloc_mtx, MA_OWNED);
1126         count = kmemcount;
1127         mtx_unlock(&malloc_mtx);
1128
1129         buflen = sizeof(struct malloc_type *) * count;
1130         bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1131
1132         mtx_lock(&malloc_mtx);
1133
1134         if (count < kmemcount) {
1135                 free(bufmtp, M_TEMP);
1136                 goto restart;
1137         }
1138
1139         for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1140                 bufmtp[i] = mtp;
1141
1142         mtx_unlock(&malloc_mtx);
1143
1144         for (i = 0; i < count; i++)
1145                 (func)(bufmtp[i], arg);
1146
1147         free(bufmtp, M_TEMP);
1148 }
1149
1150 #ifdef DDB
1151 DB_SHOW_COMMAND(malloc, db_show_malloc)
1152 {
1153         struct malloc_type_internal *mtip;
1154         struct malloc_type *mtp;
1155         uint64_t allocs, frees;
1156         uint64_t alloced, freed;
1157         int i;
1158
1159         db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
1160             "Requests");
1161         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1162                 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1163                 allocs = 0;
1164                 frees = 0;
1165                 alloced = 0;
1166                 freed = 0;
1167                 for (i = 0; i < MAXCPU; i++) {
1168                         allocs += mtip->mti_stats[i].mts_numallocs;
1169                         frees += mtip->mti_stats[i].mts_numfrees;
1170                         alloced += mtip->mti_stats[i].mts_memalloced;
1171                         freed += mtip->mti_stats[i].mts_memfreed;
1172                 }
1173                 db_printf("%18s %12ju %12juK %12ju\n",
1174                     mtp->ks_shortdesc, allocs - frees,
1175                     (alloced - freed + 1023) / 1024, allocs);
1176                 if (db_pager_quit)
1177                         break;
1178         }
1179 }
1180
1181 #if MALLOC_DEBUG_MAXZONES > 1
1182 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1183 {
1184         struct malloc_type_internal *mtip;
1185         struct malloc_type *mtp;
1186         u_int subzone;
1187
1188         if (!have_addr) {
1189                 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1190                 return;
1191         }
1192         mtp = (void *)addr;
1193         if (mtp->ks_magic != M_MAGIC) {
1194                 db_printf("Magic %lx does not match expected %x\n",
1195                     mtp->ks_magic, M_MAGIC);
1196                 return;
1197         }
1198
1199         mtip = mtp->ks_handle;
1200         subzone = mtip->mti_zone;
1201
1202         for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1203                 mtip = mtp->ks_handle;
1204                 if (mtip->mti_zone != subzone)
1205                         continue;
1206                 db_printf("%s\n", mtp->ks_shortdesc);
1207                 if (db_pager_quit)
1208                         break;
1209         }
1210 }
1211 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1212 #endif /* DDB */
1213
1214 #ifdef MALLOC_PROFILE
1215
1216 static int
1217 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1218 {
1219         struct sbuf sbuf;
1220         uint64_t count;
1221         uint64_t waste;
1222         uint64_t mem;
1223         int error;
1224         int rsize;
1225         int size;
1226         int i;
1227
1228         waste = 0;
1229         mem = 0;
1230
1231         error = sysctl_wire_old_buffer(req, 0);
1232         if (error != 0)
1233                 return (error);
1234         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1235         sbuf_printf(&sbuf, 
1236             "\n  Size                    Requests  Real Size\n");
1237         for (i = 0; i < KMEM_ZSIZE; i++) {
1238                 size = i << KMEM_ZSHIFT;
1239                 rsize = kmemzones[kmemsize[i]].kz_size;
1240                 count = (long long unsigned)krequests[i];
1241
1242                 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1243                     (unsigned long long)count, rsize);
1244
1245                 if ((rsize * count) > (size * count))
1246                         waste += (rsize * count) - (size * count);
1247                 mem += (rsize * count);
1248         }
1249         sbuf_printf(&sbuf,
1250             "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1251             (unsigned long long)mem, (unsigned long long)waste);
1252         error = sbuf_finish(&sbuf);
1253         sbuf_delete(&sbuf);
1254         return (error);
1255 }
1256
1257 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1258     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1259 #endif /* MALLOC_PROFILE */