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