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