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