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
35 /*
36 * Kernel malloc(9) implementation -- general purpose kernel memory allocator
37 * based on memory types. Back end is implemented using the UMA(9) zone
38 * allocator. A set of fixed-size buckets are used for smaller allocations,
39 * and a special UMA allocation interface is used for larger allocations.
40 * Callers declare memory types, and statistics are maintained independently
41 * for each memory type. Statistics are maintained per-CPU for performance
42 * reasons. See malloc(9) and comments in malloc.h for a detailed
43 * description.
44 */
45
46 #include "opt_ddb.h"
47 #include "opt_vm.h"
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/asan.h>
52 #include <sys/ckdint.h>
53 #include <sys/kdb.h>
54 #include <sys/kernel.h>
55 #include <sys/lock.h>
56 #include <sys/malloc.h>
57 #include <sys/msan.h>
58 #include <sys/mutex.h>
59 #include <sys/vmmeter.h>
60 #include <sys/proc.h>
61 #include <sys/queue.h>
62 #include <sys/sbuf.h>
63 #include <sys/smp.h>
64 #include <sys/sysctl.h>
65 #include <sys/time.h>
66 #include <sys/vmem.h>
67 #ifdef EPOCH_TRACE
68 #include <sys/epoch.h>
69 #endif
70
71 #include <vm/vm.h>
72 #include <vm/pmap.h>
73 #include <vm/vm_domainset.h>
74 #include <vm/vm_pageout.h>
75 #include <vm/vm_param.h>
76 #include <vm/vm_kern.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_phys.h>
81 #include <vm/vm_pagequeue.h>
82 #include <vm/uma.h>
83 #include <vm/uma_int.h>
84 #include <vm/uma_dbg.h>
85
86 #ifdef DEBUG_MEMGUARD
87 #include <vm/memguard.h>
88 #endif
89 #ifdef DEBUG_REDZONE
90 #include <vm/redzone.h>
91 #endif
92
93 #if defined(INVARIANTS) && defined(__i386__)
94 #include <machine/cpu.h>
95 #endif
96
97 #include <ddb/ddb.h>
98
99 #ifdef KDTRACE_HOOKS
100 #include <sys/dtrace_bsd.h>
101
102 bool __read_frequently dtrace_malloc_enabled;
103 dtrace_malloc_probe_func_t __read_mostly dtrace_malloc_probe;
104 #endif
105
106 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) || \
107 defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
108 #define MALLOC_DEBUG 1
109 #endif
110
111 typedef enum {
112 SLAB_COOKIE_SLAB_PTR = 0x0,
113 SLAB_COOKIE_MALLOC_LARGE = 0x1,
114 SLAB_COOKIE_CONTIG_MALLOC = 0x2,
115 } slab_cookie_t;
116 #define SLAB_COOKIE_MASK 0x3
117 #define SLAB_COOKIE_SHIFT 2
118 #define GET_SLAB_COOKIE(_slab) \
119 ((slab_cookie_t)(uintptr_t)(_slab) & SLAB_COOKIE_MASK)
120
121 /*
122 * When realloc() is called, if the new size is sufficiently smaller than
123 * the old size, realloc() will allocate a new, smaller block to avoid
124 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
125 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
126 */
127 #ifndef REALLOC_FRACTION
128 #define REALLOC_FRACTION 1 /* new block if <= half the size */
129 #endif
130
131 /*
132 * Centrally define some common malloc types.
133 */
134 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
135 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
136 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
137
138 static struct malloc_type *kmemstatistics;
139 static int kmemcount;
140
141 #define KMEM_ZSHIFT 4
142 #define KMEM_ZBASE 16
143 #define KMEM_ZMASK (KMEM_ZBASE - 1)
144
145 #define KMEM_ZMAX 65536
146 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
147 static uint8_t kmemsize[KMEM_ZSIZE + 1];
148
149 #ifndef MALLOC_DEBUG_MAXZONES
150 #define MALLOC_DEBUG_MAXZONES 1
151 #endif
152 static int numzones = MALLOC_DEBUG_MAXZONES;
153
154 /*
155 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
156 * of various sizes.
157 *
158 * Warning: the layout of the struct is duplicated in libmemstat for KVM support.
159 *
160 * XXX: The comment here used to read "These won't be powers of two for
161 * long." It's possible that a significant amount of wasted memory could be
162 * recovered by tuning the sizes of these buckets.
163 */
164 struct {
165 int kz_size;
166 const char *kz_name;
167 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
168 } kmemzones[] = {
169 {16, "malloc-16", },
170 {32, "malloc-32", },
171 {64, "malloc-64", },
172 {128, "malloc-128", },
173 {256, "malloc-256", },
174 {384, "malloc-384", },
175 {512, "malloc-512", },
176 {1024, "malloc-1024", },
177 {2048, "malloc-2048", },
178 {4096, "malloc-4096", },
179 {8192, "malloc-8192", },
180 {16384, "malloc-16384", },
181 {32768, "malloc-32768", },
182 {65536, "malloc-65536", },
183 {0, NULL},
184 };
185
186 u_long vm_kmem_size;
187 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
188 "Size of kernel memory");
189
190 static u_long kmem_zmax = KMEM_ZMAX;
191 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
192 "Maximum allocation size that malloc(9) would use UMA as backend");
193
194 static u_long vm_kmem_size_min;
195 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
196 "Minimum size of kernel memory");
197
198 static u_long vm_kmem_size_max;
199 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
200 "Maximum size of kernel memory");
201
202 static u_int vm_kmem_size_scale;
203 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
204 "Scale factor for kernel memory size");
205
206 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
207 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
208 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
209 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
210
211 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
212 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
213 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
214 sysctl_kmem_map_free, "LU", "Free space in kmem");
215
216 static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
217 "Malloc information");
218
219 static u_int vm_malloc_zone_count = nitems(kmemzones);
220 SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
221 CTLFLAG_RD, &vm_malloc_zone_count, 0,
222 "Number of malloc zones");
223
224 static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
225 SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
226 CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
227 sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
228
229 /*
230 * The malloc_mtx protects the kmemstatistics linked list.
231 */
232 struct mtx malloc_mtx;
233
234 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
235
236 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
237 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
238 "Kernel malloc debugging options");
239 #endif
240
241 /*
242 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
243 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
244 */
245 #ifdef MALLOC_MAKE_FAILURES
246 static int malloc_failure_rate;
247 static int malloc_nowait_count;
248 static int malloc_failure_count;
249 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
250 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
251 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
252 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
253 #endif
254
255 static int
sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)256 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
257 {
258 u_long size;
259
260 size = uma_size();
261 return (sysctl_handle_long(oidp, &size, 0, req));
262 }
263
264 static int
sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)265 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
266 {
267 u_long size, limit;
268
269 /* The sysctl is unsigned, implement as a saturation value. */
270 size = uma_size();
271 limit = uma_limit();
272 if (size > limit)
273 size = 0;
274 else
275 size = limit - size;
276 return (sysctl_handle_long(oidp, &size, 0, req));
277 }
278
279 static int
sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)280 sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
281 {
282 int sizes[nitems(kmemzones)];
283 int i;
284
285 for (i = 0; i < nitems(kmemzones); i++) {
286 sizes[i] = kmemzones[i].kz_size;
287 }
288
289 return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
290 }
291
292 /*
293 * malloc(9) uma zone separation -- sub-page buffer overruns in one
294 * malloc type will affect only a subset of other malloc types.
295 */
296 #if MALLOC_DEBUG_MAXZONES > 1
297 static void
tunable_set_numzones(void * dummy __unused)298 tunable_set_numzones(void *dummy __unused)
299 {
300
301 TUNABLE_INT_FETCH("debug.malloc.numzones",
302 &numzones);
303
304 /* Sanity check the number of malloc uma zones. */
305 if (numzones <= 0)
306 numzones = 1;
307 if (numzones > MALLOC_DEBUG_MAXZONES)
308 numzones = MALLOC_DEBUG_MAXZONES;
309 }
310 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
311 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
312 &numzones, 0, "Number of malloc uma subzones");
313
314 /*
315 * Any number that changes regularly is an okay choice for the
316 * offset. Build numbers are pretty good of you have them.
317 */
318 static u_int zone_offset = __FreeBSD_version;
319 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
320 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
321 &zone_offset, 0, "Separate malloc types by examining the "
322 "Nth character in the malloc type short description.");
323
324 static void
mtp_set_subzone(struct malloc_type * mtp)325 mtp_set_subzone(struct malloc_type *mtp)
326 {
327 struct malloc_type_internal *mtip;
328 const char *desc;
329 size_t len;
330 u_int val;
331
332 mtip = &mtp->ks_mti;
333 desc = mtp->ks_shortdesc;
334 if (desc == NULL || (len = strlen(desc)) == 0)
335 val = 0;
336 else
337 val = desc[zone_offset % len];
338 mtip->mti_zone = (val % numzones);
339 }
340
341 static inline u_int
mtp_get_subzone(struct malloc_type * mtp)342 mtp_get_subzone(struct malloc_type *mtp)
343 {
344 struct malloc_type_internal *mtip;
345
346 mtip = &mtp->ks_mti;
347
348 KASSERT(mtip->mti_zone < numzones,
349 ("mti_zone %u out of range %d",
350 mtip->mti_zone, numzones));
351 return (mtip->mti_zone);
352 }
353 #elif MALLOC_DEBUG_MAXZONES == 0
354 #error "MALLOC_DEBUG_MAXZONES must be positive."
355 #else
356 static void
mtp_set_subzone(struct malloc_type * mtp)357 mtp_set_subzone(struct malloc_type *mtp)
358 {
359 struct malloc_type_internal *mtip;
360
361 mtip = &mtp->ks_mti;
362 mtip->mti_zone = 0;
363 }
364
365 static inline u_int
mtp_get_subzone(struct malloc_type * mtp)366 mtp_get_subzone(struct malloc_type *mtp)
367 {
368
369 return (0);
370 }
371 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
372
373 /*
374 * An allocation has succeeded -- update malloc type statistics for the
375 * amount of bucket size. Occurs within a critical section so that the
376 * thread isn't preempted and doesn't migrate while updating per-PCU
377 * statistics.
378 */
379 static void
malloc_type_zone_allocated(struct malloc_type * mtp,unsigned long size,int zindx)380 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
381 int zindx)
382 {
383 struct malloc_type_internal *mtip;
384 struct malloc_type_stats *mtsp;
385
386 critical_enter();
387 mtip = &mtp->ks_mti;
388 mtsp = zpcpu_get(mtip->mti_stats);
389 if (size > 0) {
390 mtsp->mts_memalloced += size;
391 mtsp->mts_numallocs++;
392 }
393 if (zindx != -1)
394 mtsp->mts_size |= 1 << zindx;
395
396 #ifdef KDTRACE_HOOKS
397 if (__predict_false(dtrace_malloc_enabled)) {
398 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
399 if (probe_id != 0)
400 (dtrace_malloc_probe)(probe_id,
401 (uintptr_t) mtp, (uintptr_t) mtip,
402 (uintptr_t) mtsp, size, zindx);
403 }
404 #endif
405
406 critical_exit();
407 }
408
409 void
malloc_type_allocated(struct malloc_type * mtp,unsigned long size)410 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
411 {
412
413 if (size > 0)
414 malloc_type_zone_allocated(mtp, size, -1);
415 }
416
417 /*
418 * A free operation has occurred -- update malloc type statistics for the
419 * amount of the bucket size. Occurs within a critical section so that the
420 * thread isn't preempted and doesn't migrate while updating per-CPU
421 * statistics.
422 */
423 void
malloc_type_freed(struct malloc_type * mtp,unsigned long size)424 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
425 {
426 struct malloc_type_internal *mtip;
427 struct malloc_type_stats *mtsp;
428
429 critical_enter();
430 mtip = &mtp->ks_mti;
431 mtsp = zpcpu_get(mtip->mti_stats);
432 mtsp->mts_memfreed += size;
433 mtsp->mts_numfrees++;
434
435 #ifdef KDTRACE_HOOKS
436 if (__predict_false(dtrace_malloc_enabled)) {
437 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
438 if (probe_id != 0)
439 (dtrace_malloc_probe)(probe_id,
440 (uintptr_t) mtp, (uintptr_t) mtip,
441 (uintptr_t) mtsp, size, 0);
442 }
443 #endif
444
445 critical_exit();
446 }
447
448 /*
449 * contigmalloc:
450 *
451 * Allocate a block of physically contiguous memory.
452 *
453 * If M_NOWAIT is set, this routine will not block and return NULL if
454 * the allocation fails.
455 */
456 #define IS_CONTIG_MALLOC(_slab) \
457 (GET_SLAB_COOKIE(_slab) == SLAB_COOKIE_CONTIG_MALLOC)
458 #define CONTIG_MALLOC_SLAB(_size) \
459 ((void *)(((_size) << SLAB_COOKIE_SHIFT) | SLAB_COOKIE_CONTIG_MALLOC))
460 static inline size_t
contigmalloc_size(uma_slab_t slab)461 contigmalloc_size(uma_slab_t slab)
462 {
463 uintptr_t va;
464
465 KASSERT(IS_CONTIG_MALLOC(slab),
466 ("%s: called on non-contigmalloc allocation: %p", __func__, slab));
467 va = (uintptr_t)slab;
468 return (va >> SLAB_COOKIE_SHIFT);
469 }
470
471 void *
contigmalloc(unsigned long osize,struct malloc_type * type,int flags,vm_paddr_t low,vm_paddr_t high,unsigned long alignment,vm_paddr_t boundary)472 contigmalloc(unsigned long osize, struct malloc_type *type, int flags,
473 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
474 vm_paddr_t boundary)
475 {
476 void *ret;
477 unsigned long size;
478
479 #ifdef DEBUG_REDZONE
480 size = redzone_size_ntor(osize);
481 #else
482 size = osize;
483 #endif
484
485 ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
486 boundary, VM_MEMATTR_DEFAULT);
487 if (ret != NULL) {
488 /* Use low bits unused for slab pointers. */
489 vsetzoneslab((uintptr_t)ret, NULL, CONTIG_MALLOC_SLAB(size));
490 malloc_type_allocated(type, round_page(size));
491 #ifdef DEBUG_REDZONE
492 ret = redzone_setup(ret, osize);
493 #endif
494 }
495 return (ret);
496 }
497
498 void *
contigmalloc_domainset(unsigned long osize,struct malloc_type * type,struct domainset * ds,int flags,vm_paddr_t low,vm_paddr_t high,unsigned long alignment,vm_paddr_t boundary)499 contigmalloc_domainset(unsigned long osize, struct malloc_type *type,
500 struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
501 unsigned long alignment, vm_paddr_t boundary)
502 {
503 void *ret;
504 unsigned long size;
505
506 #ifdef DEBUG_REDZONE
507 size = redzone_size_ntor(osize);
508 #else
509 size = osize;
510 #endif
511
512 ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
513 alignment, boundary, VM_MEMATTR_DEFAULT);
514 if (ret != NULL) {
515 /* Use low bits unused for slab pointers. */
516 vsetzoneslab((uintptr_t)ret, NULL, CONTIG_MALLOC_SLAB(size));
517 malloc_type_allocated(type, round_page(size));
518 #ifdef DEBUG_REDZONE
519 ret = redzone_setup(ret, osize);
520 #endif
521 }
522 return (ret);
523 }
524 #undef IS_CONTIG_MALLOC
525 #undef CONTIG_MALLOC_SLAB
526
527 /* contigfree(9) is deprecated. */
528 void
contigfree(void * addr,unsigned long size __unused,struct malloc_type * type)529 contigfree(void *addr, unsigned long size __unused, struct malloc_type *type)
530 {
531 free(addr, type);
532 }
533
534 #ifdef MALLOC_DEBUG
535 static int
malloc_dbg(void ** vap,size_t * sizep,struct malloc_type * mtp,int flags)536 malloc_dbg(void **vap, size_t *sizep, struct malloc_type *mtp,
537 int flags)
538 {
539 KASSERT(mtp->ks_version == M_VERSION, ("malloc: bad malloc type version"));
540 KASSERT((flags & (M_WAITOK | M_NOWAIT)) != 0,
541 ("malloc: flags must include either M_WAITOK or M_NOWAIT"));
542 KASSERT((flags & (M_WAITOK | M_NOWAIT)) != (M_WAITOK | M_NOWAIT),
543 ("malloc: flags may not include both M_WAITOK and M_NOWAIT"));
544 KASSERT((flags & M_NEVERFREED) == 0,
545 ("malloc: M_NEVERFREED is for internal use only"));
546 #ifdef MALLOC_MAKE_FAILURES
547 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
548 atomic_add_int(&malloc_nowait_count, 1);
549 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
550 atomic_add_int(&malloc_failure_count, 1);
551 *vap = NULL;
552 return (EJUSTRETURN);
553 }
554 }
555 #endif
556 if (flags & M_WAITOK) {
557 KASSERT(curthread->td_intr_nesting_level == 0,
558 ("malloc(M_WAITOK) in interrupt context"));
559 if (__predict_false(!THREAD_CAN_SLEEP())) {
560 #ifdef EPOCH_TRACE
561 epoch_trace_list(curthread);
562 #endif
563 KASSERT(0,
564 ("malloc(M_WAITOK) with sleeping prohibited"));
565 }
566 }
567 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
568 ("malloc: called with spinlock or critical section held"));
569
570 #ifdef DEBUG_MEMGUARD
571 if (memguard_cmp_mtp(mtp, *sizep)) {
572 *vap = memguard_alloc(*sizep, flags);
573 if (*vap != NULL)
574 return (EJUSTRETURN);
575 /* This is unfortunate but should not be fatal. */
576 }
577 #endif
578
579 #ifdef DEBUG_REDZONE
580 *sizep = redzone_size_ntor(*sizep);
581 #endif
582
583 return (0);
584 }
585 #endif
586
587 /*
588 * Handle large allocations and frees by using kmem_malloc directly.
589 */
590 #define IS_MALLOC_LARGE(_slab) \
591 (GET_SLAB_COOKIE(_slab) == SLAB_COOKIE_MALLOC_LARGE)
592 #define MALLOC_LARGE_SLAB(_size) \
593 ((void *)(((_size) << SLAB_COOKIE_SHIFT) | SLAB_COOKIE_MALLOC_LARGE))
594 static inline size_t
malloc_large_size(uma_slab_t slab)595 malloc_large_size(uma_slab_t slab)
596 {
597 uintptr_t va;
598
599 va = (uintptr_t)slab;
600 KASSERT(IS_MALLOC_LARGE(slab),
601 ("%s: called on non-malloc_large allocation: %p", __func__, slab));
602 return (va >> SLAB_COOKIE_SHIFT);
603 }
604
605 static caddr_t __noinline
malloc_large(size_t * sizep,struct malloc_type * mtp,struct domainset * policy,int flags)606 malloc_large(size_t *sizep, struct malloc_type *mtp, struct domainset *policy,
607 int flags)
608 {
609 void *va;
610 size_t size;
611
612 size = roundup(*sizep, PAGE_SIZE);
613 va = kmem_malloc_domainset(policy, size, flags);
614 if (va != NULL) {
615 /* Use low bits unused for slab pointers. */
616 vsetzoneslab((uintptr_t)va, NULL, MALLOC_LARGE_SLAB(size));
617 uma_total_inc(size);
618 }
619 malloc_type_allocated(mtp, va == NULL ? 0 : size);
620 *sizep = size;
621 return (va);
622 }
623
624 static void
free_large(void * addr,size_t size)625 free_large(void *addr, size_t size)
626 {
627
628 kmem_free(addr, size);
629 uma_total_dec(size);
630 }
631 #undef IS_MALLOC_LARGE
632 #undef MALLOC_LARGE_SLAB
633
634 /*
635 * malloc:
636 *
637 * Allocate a block of memory.
638 *
639 * If M_NOWAIT is set, this routine will not block and return NULL if
640 * the allocation fails.
641 */
642 void *
643 (malloc)(size_t size, struct malloc_type *mtp, int flags)
644 {
645 uma_zone_t zone;
646 void *va;
647 int indx;
648 #if defined(DEBUG_REDZONE) || defined(KASAN)
649 unsigned long osize = size;
650 #endif
651
652 /* We don't want to handle this rare case in a hot path. */
653 MPASS((flags & M_EXEC) == 0);
654
655 #ifdef MALLOC_DEBUG
656 va = NULL;
657 if (malloc_dbg(&va, &size, mtp, flags) != 0)
658 return (va);
659 #endif
660
661 if (__predict_false(size > kmem_zmax)) {
662 va = malloc_large(&size, mtp, DOMAINSET_RR(), flags);
663 } else {
664 if (size & KMEM_ZMASK)
665 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
666 indx = kmemsize[size >> KMEM_ZSHIFT];
667 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
668 va = uma_zalloc_arg(zone, zone, flags);
669 if (va != NULL)
670 size = zone->uz_size;
671 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
672 }
673 KASSERT(va != NULL || (flags & M_WAITOK) == 0,
674 ("malloc(M_WAITOK) returned NULL"));
675
676 #ifdef DEBUG_REDZONE
677 if (va != NULL)
678 va = redzone_setup(va, osize);
679 #endif
680 #ifdef KASAN
681 if (va != NULL)
682 kasan_mark(va, osize, size, KASAN_MALLOC_REDZONE);
683 #endif
684 #ifdef KMSAN
685 if (va != NULL && (flags & M_ZERO) == 0)
686 kmsan_orig(va, size, KMSAN_TYPE_MALLOC, KMSAN_RET_ADDR);
687 #endif
688 return (va);
689 }
690
691 static void *
malloc_domain(size_t * sizep,int * indxp,struct malloc_type * mtp,int domain,int flags)692 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
693 int flags)
694 {
695 uma_zone_t zone;
696 caddr_t va;
697 size_t size;
698 int indx;
699
700 size = *sizep;
701 KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
702 ("malloc_domain: Called with bad flag / size combination"));
703 if (size & KMEM_ZMASK)
704 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
705 indx = kmemsize[size >> KMEM_ZSHIFT];
706 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
707 va = uma_zalloc_domain(zone, zone, domain, flags);
708 if (va != NULL)
709 *sizep = zone->uz_size;
710 *indxp = indx;
711 return ((void *)va);
712 }
713
714 void *
malloc_domainset(size_t size,struct malloc_type * mtp,struct domainset * ds,int flags)715 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
716 int flags)
717 {
718 struct vm_domainset_iter di;
719 void *va;
720 int domain;
721 #if defined(KASAN) || defined(DEBUG_REDZONE)
722 unsigned long osize = size;
723 #endif
724
725 #ifdef MALLOC_DEBUG
726 va = NULL;
727 if (malloc_dbg(&va, &size, mtp, flags) != 0)
728 return (va);
729 #endif
730
731 if (__predict_false(size > kmem_zmax || (flags & M_EXEC) != 0)) {
732 va = malloc_large(&size, mtp, ds, flags);
733 } else {
734 int indx;
735
736 indx = -1;
737 va = NULL;
738 if (vm_domainset_iter_policy_init(&di, ds, &domain,
739 &flags) == 0) {
740 do {
741 va = malloc_domain(&size, &indx, mtp, domain,
742 flags);
743 } while (va == NULL &&
744 vm_domainset_iter_policy(&di, &domain) == 0);
745 }
746 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
747 }
748 KASSERT(va != NULL || (flags & M_WAITOK) == 0,
749 ("malloc(M_WAITOK) returned NULL"));
750
751 #ifdef DEBUG_REDZONE
752 if (va != NULL)
753 va = redzone_setup(va, osize);
754 #endif
755 #ifdef KASAN
756 if (va != NULL)
757 kasan_mark(va, osize, size, KASAN_MALLOC_REDZONE);
758 #endif
759 #ifdef KMSAN
760 if (va != NULL && (flags & M_ZERO) == 0)
761 kmsan_orig(va, size, KMSAN_TYPE_MALLOC, KMSAN_RET_ADDR);
762 #endif
763 return (va);
764 }
765
766 /*
767 * Allocate an executable area.
768 */
769 void *
malloc_exec(size_t size,struct malloc_type * mtp,int flags)770 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
771 {
772
773 return (malloc_domainset_exec(size, mtp, DOMAINSET_RR(), flags));
774 }
775
776 void *
malloc_domainset_exec(size_t size,struct malloc_type * mtp,struct domainset * ds,int flags)777 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
778 int flags)
779 {
780 return (malloc_domainset(size, mtp, ds, flags | M_EXEC));
781 }
782
783 void *
malloc_aligned(size_t size,size_t align,struct malloc_type * type,int flags)784 malloc_aligned(size_t size, size_t align, struct malloc_type *type, int flags)
785 {
786 return (malloc_domainset_aligned(size, align, type, DOMAINSET_RR(),
787 flags));
788 }
789
790 void *
malloc_domainset_aligned(size_t size,size_t align,struct malloc_type * mtp,struct domainset * ds,int flags)791 malloc_domainset_aligned(size_t size, size_t align,
792 struct malloc_type *mtp, struct domainset *ds, int flags)
793 {
794 void *res;
795 size_t asize;
796
797 KASSERT(powerof2(align),
798 ("malloc_domainset_aligned: wrong align %#zx size %#zx",
799 align, size));
800 KASSERT(align <= PAGE_SIZE,
801 ("malloc_domainset_aligned: align %#zx (size %#zx) too large",
802 align, size));
803
804 /*
805 * Round the allocation size up to the next power of 2,
806 * because we can only guarantee alignment for
807 * power-of-2-sized allocations. Further increase the
808 * allocation size to align if the rounded size is less than
809 * align, since malloc zones provide alignment equal to their
810 * size.
811 */
812 if (size == 0)
813 size = 1;
814 asize = size <= align ? align : 1UL << flsl(size - 1);
815
816 res = malloc_domainset(asize, mtp, ds, flags);
817 KASSERT(res == NULL || ((uintptr_t)res & (align - 1)) == 0,
818 ("malloc_domainset_aligned: result not aligned %p size %#zx "
819 "allocsize %#zx align %#zx", res, size, asize, align));
820 return (res);
821 }
822
823 void *
mallocarray(size_t nmemb,size_t size,struct malloc_type * type,int flags)824 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
825 {
826 size_t n;
827
828 if (ckd_mul(&n, nmemb, size) != 0)
829 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
830
831 return (malloc(n, type, flags));
832 }
833
834 void *
mallocarray_domainset(size_t nmemb,size_t size,struct malloc_type * type,struct domainset * ds,int flags)835 mallocarray_domainset(size_t nmemb, size_t size, struct malloc_type *type,
836 struct domainset *ds, int flags)
837 {
838 size_t n;
839
840 if (ckd_mul(&n, nmemb, size) != 0)
841 panic("mallocarray_domainset: %zu * %zu overflowed", nmemb, size);
842
843 return (malloc_domainset(n, type, ds, flags));
844 }
845
846 #if defined(INVARIANTS) && !defined(KASAN)
847 static void
free_save_type(void * addr,struct malloc_type * mtp,u_long size)848 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
849 {
850 struct malloc_type **mtpp = addr;
851
852 /*
853 * Cache a pointer to the malloc_type that most recently freed
854 * this memory here. This way we know who is most likely to
855 * have stepped on it later.
856 *
857 * This code assumes that size is a multiple of 8 bytes for
858 * 64 bit machines
859 */
860 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
861 mtpp += (size - sizeof(struct malloc_type *)) /
862 sizeof(struct malloc_type *);
863 *mtpp = mtp;
864 }
865 #endif
866
867 #ifdef MALLOC_DEBUG
868 static int
free_dbg(void ** addrp,struct malloc_type * mtp)869 free_dbg(void **addrp, struct malloc_type *mtp)
870 {
871 void *addr;
872
873 addr = *addrp;
874 KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
875 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
876 ("free: called with spinlock or critical section held"));
877
878 /* free(NULL, ...) does nothing */
879 if (addr == NULL)
880 return (EJUSTRETURN);
881
882 #ifdef DEBUG_MEMGUARD
883 if (is_memguard_addr(addr)) {
884 memguard_free(addr);
885 return (EJUSTRETURN);
886 }
887 #endif
888
889 #ifdef DEBUG_REDZONE
890 redzone_check(addr);
891 *addrp = redzone_addr_ntor(addr);
892 #endif
893
894 return (0);
895 }
896 #endif
897
898 static __always_inline void
_free(void * addr,struct malloc_type * mtp,bool dozero)899 _free(void *addr, struct malloc_type *mtp, bool dozero)
900 {
901 uma_zone_t zone;
902 uma_slab_t slab;
903 u_long size;
904
905 #ifdef MALLOC_DEBUG
906 if (free_dbg(&addr, mtp) != 0)
907 return;
908 #endif
909 /* free(NULL, ...) does nothing */
910 if (addr == NULL)
911 return;
912
913 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
914 if (slab == NULL)
915 panic("%s(%d): address %p(%p) has not been allocated", __func__,
916 dozero, addr, (void *)((uintptr_t)addr & (~UMA_SLAB_MASK)));
917
918 switch (GET_SLAB_COOKIE(slab)) {
919 case __predict_true(SLAB_COOKIE_SLAB_PTR):
920 size = zone->uz_size;
921 #if defined(INVARIANTS) && !defined(KASAN)
922 free_save_type(addr, mtp, size);
923 #endif
924 if (dozero) {
925 kasan_mark(addr, size, size, 0);
926 explicit_bzero(addr, size);
927 }
928 uma_zfree_arg(zone, addr, slab);
929 break;
930 case SLAB_COOKIE_MALLOC_LARGE:
931 size = malloc_large_size(slab);
932 if (dozero) {
933 kasan_mark(addr, size, size, 0);
934 explicit_bzero(addr, size);
935 }
936 free_large(addr, size);
937 break;
938 case SLAB_COOKIE_CONTIG_MALLOC:
939 size = round_page(contigmalloc_size(slab));
940 if (dozero)
941 explicit_bzero(addr, size);
942 kmem_free(addr, size);
943 break;
944 default:
945 panic("%s(%d): addr %p slab %p with unknown cookie %d",
946 __func__, dozero, addr, slab, GET_SLAB_COOKIE(slab));
947 /* NOTREACHED */
948 }
949 malloc_type_freed(mtp, size);
950 }
951
952 /*
953 * free:
954 * Free a block of memory allocated by malloc/contigmalloc.
955 * This routine may not block.
956 */
957 void
free(void * addr,struct malloc_type * mtp)958 free(void *addr, struct malloc_type *mtp)
959 {
960 _free(addr, mtp, false);
961 }
962
963 /*
964 * zfree:
965 * Zero then free a block of memory allocated by malloc/contigmalloc.
966 * This routine may not block.
967 */
968 void
zfree(void * addr,struct malloc_type * mtp)969 zfree(void *addr, struct malloc_type *mtp)
970 {
971 _free(addr, mtp, true);
972 }
973
974 /*
975 * realloc: change the size of a memory block
976 */
977 void *
realloc(void * addr,size_t size,struct malloc_type * mtp,int flags)978 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
979 {
980 #ifndef DEBUG_REDZONE
981 uma_zone_t zone;
982 uma_slab_t slab;
983 #endif
984 unsigned long alloc;
985 void *newaddr;
986
987 KASSERT(mtp->ks_version == M_VERSION,
988 ("realloc: bad malloc type version"));
989 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
990 ("realloc: called with spinlock or critical section held"));
991
992 /* realloc(NULL, ...) is equivalent to malloc(...) */
993 if (addr == NULL)
994 return (malloc(size, mtp, flags));
995
996 /*
997 * XXX: Should report free of old memory and alloc of new memory to
998 * per-CPU stats.
999 */
1000
1001 #ifdef DEBUG_MEMGUARD
1002 if (is_memguard_addr(addr))
1003 return (memguard_realloc(addr, size, mtp, flags));
1004 #endif
1005
1006 #ifdef DEBUG_REDZONE
1007 alloc = redzone_get_size(addr);
1008 #else
1009 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1010
1011 /* Sanity check */
1012 KASSERT(slab != NULL,
1013 ("realloc: address %p out of range", (void *)addr));
1014
1015 /* Get the size of the original block */
1016 switch (GET_SLAB_COOKIE(slab)) {
1017 case __predict_true(SLAB_COOKIE_SLAB_PTR):
1018 alloc = zone->uz_size;
1019 break;
1020 case SLAB_COOKIE_MALLOC_LARGE:
1021 alloc = malloc_large_size(slab);
1022 break;
1023 default:
1024 #ifdef INVARIANTS
1025 panic("%s: called for addr %p of unsupported allocation type; "
1026 "slab %p cookie %d", __func__, addr, slab, GET_SLAB_COOKIE(slab));
1027 #endif
1028 return (NULL);
1029 }
1030
1031 /* Reuse the original block if appropriate */
1032 if (size <= alloc &&
1033 (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE)) {
1034 kasan_mark((void *)addr, size, alloc, KASAN_MALLOC_REDZONE);
1035 return (addr);
1036 }
1037 #endif /* !DEBUG_REDZONE */
1038
1039 /* Allocate a new, bigger (or smaller) block */
1040 if ((newaddr = malloc(size, mtp, flags)) == NULL)
1041 return (NULL);
1042
1043 /*
1044 * Copy over original contents. For KASAN, the redzone must be marked
1045 * valid before performing the copy.
1046 */
1047 kasan_mark(addr, alloc, alloc, 0);
1048 bcopy(addr, newaddr, min(size, alloc));
1049 free(addr, mtp);
1050 return (newaddr);
1051 }
1052
1053 /*
1054 * reallocf: same as realloc() but free memory on failure.
1055 */
1056 void *
reallocf(void * addr,size_t size,struct malloc_type * mtp,int flags)1057 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
1058 {
1059 void *mem;
1060
1061 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1062 free(addr, mtp);
1063 return (mem);
1064 }
1065
1066 /*
1067 * malloc_size: returns the number of bytes allocated for a request of the
1068 * specified size
1069 */
1070 size_t
malloc_size(size_t size)1071 malloc_size(size_t size)
1072 {
1073 int indx;
1074
1075 if (size > kmem_zmax)
1076 return (round_page(size));
1077 if (size & KMEM_ZMASK)
1078 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
1079 indx = kmemsize[size >> KMEM_ZSHIFT];
1080 return (kmemzones[indx].kz_size);
1081 }
1082
1083 /*
1084 * malloc_usable_size: returns the usable size of the allocation.
1085 */
1086 size_t
malloc_usable_size(const void * addr)1087 malloc_usable_size(const void *addr)
1088 {
1089 #ifndef DEBUG_REDZONE
1090 uma_zone_t zone;
1091 uma_slab_t slab;
1092 #endif
1093 u_long size;
1094
1095 if (addr == NULL)
1096 return (0);
1097
1098 #ifdef DEBUG_MEMGUARD
1099 if (is_memguard_addr(__DECONST(void *, addr)))
1100 return (memguard_get_req_size(addr));
1101 #endif
1102
1103 #ifdef DEBUG_REDZONE
1104 size = redzone_get_size(__DECONST(void *, addr));
1105 #else
1106 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1107 if (slab == NULL)
1108 panic("malloc_usable_size: address %p(%p) is not allocated",
1109 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1110
1111 switch (GET_SLAB_COOKIE(slab)) {
1112 case __predict_true(SLAB_COOKIE_SLAB_PTR):
1113 size = zone->uz_size;
1114 break;
1115 case SLAB_COOKIE_MALLOC_LARGE:
1116 size = malloc_large_size(slab);
1117 break;
1118 case SLAB_COOKIE_CONTIG_MALLOC:
1119 size = round_page(contigmalloc_size(slab));
1120 break;
1121 default:
1122 __assert_unreachable();
1123 size = 0;
1124 break;
1125 }
1126 #endif
1127
1128 /*
1129 * Unmark the redzone to avoid reports from consumers who are
1130 * (presumably) about to use the full allocation size.
1131 */
1132 kasan_mark(addr, size, size, 0);
1133
1134 return (size);
1135 }
1136
1137 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1138
1139 /*
1140 * Initialize the kernel memory (kmem) arena.
1141 */
1142 void
kmeminit(void)1143 kmeminit(void)
1144 {
1145 u_long mem_size;
1146 u_long tmp;
1147
1148 #ifdef VM_KMEM_SIZE
1149 if (vm_kmem_size == 0)
1150 vm_kmem_size = VM_KMEM_SIZE;
1151 #endif
1152 #ifdef VM_KMEM_SIZE_MIN
1153 if (vm_kmem_size_min == 0)
1154 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1155 #endif
1156 #ifdef VM_KMEM_SIZE_MAX
1157 if (vm_kmem_size_max == 0)
1158 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1159 #endif
1160 /*
1161 * Calculate the amount of kernel virtual address (KVA) space that is
1162 * preallocated to the kmem arena. In order to support a wide range
1163 * of machines, it is a function of the physical memory size,
1164 * specifically,
1165 *
1166 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1167 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1168 *
1169 * Every architecture must define an integral value for
1170 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
1171 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1172 * ceiling on this preallocation, are optional. Typically,
1173 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1174 * a given architecture.
1175 */
1176 mem_size = vm_cnt.v_page_count;
1177 if (mem_size <= 32768) /* delphij XXX 128MB */
1178 kmem_zmax = PAGE_SIZE;
1179
1180 if (vm_kmem_size_scale < 1)
1181 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1182
1183 /*
1184 * Check if we should use defaults for the "vm_kmem_size"
1185 * variable:
1186 */
1187 if (vm_kmem_size == 0) {
1188 vm_kmem_size = mem_size / vm_kmem_size_scale;
1189 vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1190 vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1191 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1192 vm_kmem_size = vm_kmem_size_min;
1193 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1194 vm_kmem_size = vm_kmem_size_max;
1195 }
1196 if (vm_kmem_size == 0)
1197 panic("Tune VM_KMEM_SIZE_* for the platform");
1198
1199 /*
1200 * The amount of KVA space that is preallocated to the
1201 * kmem arena can be set statically at compile-time or manually
1202 * through the kernel environment. However, it is still limited to
1203 * twice the physical memory size, which has been sufficient to handle
1204 * the most severe cases of external fragmentation in the kmem arena.
1205 */
1206 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1207 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1208
1209 vm_kmem_size = round_page(vm_kmem_size);
1210
1211 /*
1212 * With KASAN or KMSAN enabled, dynamically allocated kernel memory is
1213 * shadowed. Account for this when setting the UMA limit.
1214 */
1215 #if defined(KASAN)
1216 vm_kmem_size = (vm_kmem_size * KASAN_SHADOW_SCALE) /
1217 (KASAN_SHADOW_SCALE + 1);
1218 #elif defined(KMSAN)
1219 vm_kmem_size /= 3;
1220 #endif
1221
1222 #ifdef DEBUG_MEMGUARD
1223 tmp = memguard_fudge(vm_kmem_size, kernel_map);
1224 #else
1225 tmp = vm_kmem_size;
1226 #endif
1227 uma_set_limit(tmp);
1228
1229 #ifdef DEBUG_MEMGUARD
1230 /*
1231 * Initialize MemGuard if support compiled in. MemGuard is a
1232 * replacement allocator used for detecting tamper-after-free
1233 * scenarios as they occur. It is only used for debugging.
1234 */
1235 memguard_init(kernel_arena);
1236 #endif
1237 }
1238
1239 /*
1240 * Initialize the kernel memory allocator
1241 */
1242 /* ARGSUSED*/
1243 static void
mallocinit(void * dummy)1244 mallocinit(void *dummy)
1245 {
1246 int i;
1247 uint8_t indx;
1248
1249 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1250
1251 kmeminit();
1252
1253 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1254 kmem_zmax = KMEM_ZMAX;
1255
1256 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1257 int size = kmemzones[indx].kz_size;
1258 const char *name = kmemzones[indx].kz_name;
1259 size_t align;
1260 int subzone;
1261
1262 align = UMA_ALIGN_PTR;
1263 if (powerof2(size) && size > sizeof(void *))
1264 align = MIN(size, PAGE_SIZE) - 1;
1265 for (subzone = 0; subzone < numzones; subzone++) {
1266 kmemzones[indx].kz_zone[subzone] =
1267 uma_zcreate(name, size,
1268 #if defined(INVARIANTS) && !defined(KASAN) && !defined(KMSAN)
1269 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1270 #else
1271 NULL, NULL, NULL, NULL,
1272 #endif
1273 align, UMA_ZONE_MALLOC);
1274 }
1275 for (; i <= size; i+= KMEM_ZBASE)
1276 kmemsize[i >> KMEM_ZSHIFT] = indx;
1277 }
1278 }
1279 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1280
1281 void
malloc_init(void * data)1282 malloc_init(void *data)
1283 {
1284 struct malloc_type_internal *mtip;
1285 struct malloc_type *mtp;
1286
1287 KASSERT(vm_cnt.v_page_count != 0,
1288 ("malloc_init() called before vm_mem_init()"));
1289
1290 mtp = data;
1291 if (mtp->ks_version != M_VERSION)
1292 panic("malloc_init: type %s with unsupported version %lu",
1293 mtp->ks_shortdesc, mtp->ks_version);
1294
1295 mtip = &mtp->ks_mti;
1296 mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1297 mtp_set_subzone(mtp);
1298
1299 mtx_lock(&malloc_mtx);
1300 mtp->ks_next = kmemstatistics;
1301 kmemstatistics = mtp;
1302 kmemcount++;
1303 mtx_unlock(&malloc_mtx);
1304 }
1305
1306 void
malloc_uninit(void * data)1307 malloc_uninit(void *data)
1308 {
1309 struct malloc_type_internal *mtip;
1310 struct malloc_type_stats *mtsp;
1311 struct malloc_type *mtp, *temp;
1312 long temp_allocs, temp_bytes;
1313 int i;
1314
1315 mtp = data;
1316 KASSERT(mtp->ks_version == M_VERSION,
1317 ("malloc_uninit: bad malloc type version"));
1318
1319 mtx_lock(&malloc_mtx);
1320 mtip = &mtp->ks_mti;
1321 if (mtp != kmemstatistics) {
1322 for (temp = kmemstatistics; temp != NULL;
1323 temp = temp->ks_next) {
1324 if (temp->ks_next == mtp) {
1325 temp->ks_next = mtp->ks_next;
1326 break;
1327 }
1328 }
1329 KASSERT(temp,
1330 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1331 } else
1332 kmemstatistics = mtp->ks_next;
1333 kmemcount--;
1334 mtx_unlock(&malloc_mtx);
1335
1336 /*
1337 * Look for memory leaks.
1338 */
1339 temp_allocs = temp_bytes = 0;
1340 for (i = 0; i <= mp_maxid; i++) {
1341 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1342 temp_allocs += mtsp->mts_numallocs;
1343 temp_allocs -= mtsp->mts_numfrees;
1344 temp_bytes += mtsp->mts_memalloced;
1345 temp_bytes -= mtsp->mts_memfreed;
1346 }
1347 if (temp_allocs > 0 || temp_bytes > 0) {
1348 printf("Warning: memory type %s leaked memory on destroy "
1349 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1350 temp_allocs, temp_bytes);
1351 }
1352
1353 uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1354 }
1355
1356 struct malloc_type *
malloc_desc2type(const char * desc)1357 malloc_desc2type(const char *desc)
1358 {
1359 struct malloc_type *mtp;
1360
1361 mtx_assert(&malloc_mtx, MA_OWNED);
1362 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1363 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1364 return (mtp);
1365 }
1366 return (NULL);
1367 }
1368
1369 static int
sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)1370 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1371 {
1372 struct malloc_type_stream_header mtsh;
1373 struct malloc_type_internal *mtip;
1374 struct malloc_type_stats *mtsp, zeromts;
1375 struct malloc_type_header mth;
1376 struct malloc_type *mtp;
1377 int error, i;
1378 struct sbuf sbuf;
1379
1380 error = sysctl_wire_old_buffer(req, 0);
1381 if (error != 0)
1382 return (error);
1383 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1384 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1385 mtx_lock(&malloc_mtx);
1386
1387 bzero(&zeromts, sizeof(zeromts));
1388
1389 /*
1390 * Insert stream header.
1391 */
1392 bzero(&mtsh, sizeof(mtsh));
1393 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1394 mtsh.mtsh_maxcpus = MAXCPU;
1395 mtsh.mtsh_count = kmemcount;
1396 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1397
1398 /*
1399 * Insert alternating sequence of type headers and type statistics.
1400 */
1401 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1402 mtip = &mtp->ks_mti;
1403
1404 /*
1405 * Insert type header.
1406 */
1407 bzero(&mth, sizeof(mth));
1408 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1409 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1410
1411 /*
1412 * Insert type statistics for each CPU.
1413 */
1414 for (i = 0; i <= mp_maxid; i++) {
1415 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1416 (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1417 }
1418 /*
1419 * Fill in the missing CPUs.
1420 */
1421 for (; i < MAXCPU; i++) {
1422 (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1423 }
1424 }
1425 mtx_unlock(&malloc_mtx);
1426 error = sbuf_finish(&sbuf);
1427 sbuf_delete(&sbuf);
1428 return (error);
1429 }
1430
1431 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1432 CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1433 sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1434 "Return malloc types");
1435
1436 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1437 "Count of kernel malloc types");
1438
1439 void
malloc_type_list(malloc_type_list_func_t * func,void * arg)1440 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1441 {
1442 struct malloc_type *mtp, **bufmtp;
1443 int count, i;
1444 size_t buflen;
1445
1446 mtx_lock(&malloc_mtx);
1447 restart:
1448 mtx_assert(&malloc_mtx, MA_OWNED);
1449 count = kmemcount;
1450 mtx_unlock(&malloc_mtx);
1451
1452 buflen = sizeof(struct malloc_type *) * count;
1453 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1454
1455 mtx_lock(&malloc_mtx);
1456
1457 if (count < kmemcount) {
1458 free(bufmtp, M_TEMP);
1459 goto restart;
1460 }
1461
1462 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1463 bufmtp[i] = mtp;
1464
1465 mtx_unlock(&malloc_mtx);
1466
1467 for (i = 0; i < count; i++)
1468 (func)(bufmtp[i], arg);
1469
1470 free(bufmtp, M_TEMP);
1471 }
1472
1473 #ifdef DDB
1474 static int64_t
get_malloc_stats(const struct malloc_type_internal * mtip,uint64_t * allocs,uint64_t * inuse)1475 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1476 uint64_t *inuse)
1477 {
1478 const struct malloc_type_stats *mtsp;
1479 uint64_t frees, alloced, freed;
1480 int i;
1481
1482 *allocs = 0;
1483 frees = 0;
1484 alloced = 0;
1485 freed = 0;
1486 for (i = 0; i <= mp_maxid; i++) {
1487 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1488
1489 *allocs += mtsp->mts_numallocs;
1490 frees += mtsp->mts_numfrees;
1491 alloced += mtsp->mts_memalloced;
1492 freed += mtsp->mts_memfreed;
1493 }
1494 *inuse = *allocs - frees;
1495 return (alloced - freed);
1496 }
1497
DB_SHOW_COMMAND_FLAGS(malloc,db_show_malloc,DB_CMD_MEMSAFE)1498 DB_SHOW_COMMAND_FLAGS(malloc, db_show_malloc, DB_CMD_MEMSAFE)
1499 {
1500 const char *fmt_hdr, *fmt_entry;
1501 struct malloc_type *mtp;
1502 uint64_t allocs, inuse;
1503 int64_t size;
1504 /* variables for sorting */
1505 struct malloc_type *last_mtype, *cur_mtype;
1506 int64_t cur_size, last_size;
1507 int ties;
1508
1509 if (modif[0] == 'i') {
1510 fmt_hdr = "%s,%s,%s,%s\n";
1511 fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1512 } else {
1513 fmt_hdr = "%18s %12s %12s %12s\n";
1514 fmt_entry = "%18s %12ju %12jdK %12ju\n";
1515 }
1516
1517 db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1518
1519 /* Select sort, largest size first. */
1520 last_mtype = NULL;
1521 last_size = INT64_MAX;
1522 for (;;) {
1523 cur_mtype = NULL;
1524 cur_size = -1;
1525 ties = 0;
1526
1527 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1528 /*
1529 * In the case of size ties, print out mtypes
1530 * in the order they are encountered. That is,
1531 * when we encounter the most recently output
1532 * mtype, we have already printed all preceding
1533 * ties, and we must print all following ties.
1534 */
1535 if (mtp == last_mtype) {
1536 ties = 1;
1537 continue;
1538 }
1539 size = get_malloc_stats(&mtp->ks_mti, &allocs,
1540 &inuse);
1541 if (size > cur_size && size < last_size + ties) {
1542 cur_size = size;
1543 cur_mtype = mtp;
1544 }
1545 }
1546 if (cur_mtype == NULL)
1547 break;
1548
1549 size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
1550 db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1551 howmany(size, 1024), allocs);
1552
1553 if (db_pager_quit)
1554 break;
1555
1556 last_mtype = cur_mtype;
1557 last_size = cur_size;
1558 }
1559 }
1560
1561 #if MALLOC_DEBUG_MAXZONES > 1
DB_SHOW_COMMAND(multizone_matches,db_show_multizone_matches)1562 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1563 {
1564 struct malloc_type_internal *mtip;
1565 struct malloc_type *mtp;
1566 u_int subzone;
1567
1568 if (!have_addr) {
1569 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1570 return;
1571 }
1572 mtp = (void *)addr;
1573 if (mtp->ks_version != M_VERSION) {
1574 db_printf("Version %lx does not match expected %x\n",
1575 mtp->ks_version, M_VERSION);
1576 return;
1577 }
1578
1579 mtip = &mtp->ks_mti;
1580 subzone = mtip->mti_zone;
1581
1582 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1583 mtip = &mtp->ks_mti;
1584 if (mtip->mti_zone != subzone)
1585 continue;
1586 db_printf("%s\n", mtp->ks_shortdesc);
1587 if (db_pager_quit)
1588 break;
1589 }
1590 }
1591 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1592 #endif /* DDB */
1593