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(size, flags, low, high, alignment, 447 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((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_epochnest == 0, 521 ("malloc(M_WAITOK) in epoch context")); 522 } 523 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(), 524 ("malloc: called with spinlock or critical section held")); 525 526 #ifdef DEBUG_MEMGUARD 527 if (memguard_cmp_mtp(mtp, *sizep)) { 528 *vap = memguard_alloc(*sizep, flags); 529 if (*vap != NULL) 530 return (EJUSTRETURN); 531 /* This is unfortunate but should not be fatal. */ 532 } 533 #endif 534 535 #ifdef DEBUG_REDZONE 536 *sizep = redzone_size_ntor(*sizep); 537 #endif 538 539 return (0); 540 } 541 #endif 542 543 /* 544 * malloc: 545 * 546 * Allocate a block of memory. 547 * 548 * If M_NOWAIT is set, this routine will not block and return NULL if 549 * the allocation fails. 550 */ 551 void * 552 (malloc)(size_t size, struct malloc_type *mtp, int flags) 553 { 554 int indx; 555 caddr_t va; 556 uma_zone_t zone; 557 #if defined(DEBUG_REDZONE) 558 unsigned long osize = size; 559 #endif 560 561 #ifdef MALLOC_DEBUG 562 va = NULL; 563 if (malloc_dbg(&va, &size, mtp, flags) != 0) 564 return (va); 565 #endif 566 567 if (size <= kmem_zmax && (flags & M_EXEC) == 0) { 568 if (size & KMEM_ZMASK) 569 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE; 570 indx = kmemsize[size >> KMEM_ZSHIFT]; 571 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)]; 572 #ifdef MALLOC_PROFILE 573 krequests[size >> KMEM_ZSHIFT]++; 574 #endif 575 va = uma_zalloc(zone, flags); 576 if (va != NULL) 577 size = zone->uz_size; 578 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx); 579 } else { 580 size = roundup(size, PAGE_SIZE); 581 zone = NULL; 582 va = uma_large_malloc(size, flags); 583 malloc_type_allocated(mtp, va == NULL ? 0 : size); 584 } 585 if (flags & M_WAITOK) 586 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL")); 587 else if (va == NULL) 588 t_malloc_fail = time_uptime; 589 #ifdef DEBUG_REDZONE 590 if (va != NULL) 591 va = redzone_setup(va, osize); 592 #endif 593 return ((void *) va); 594 } 595 596 void * 597 malloc_domain(size_t size, struct malloc_type *mtp, int domain, 598 int flags) 599 { 600 int indx; 601 caddr_t va; 602 uma_zone_t zone; 603 #if defined(DEBUG_REDZONE) 604 unsigned long osize = size; 605 #endif 606 607 #ifdef MALLOC_DEBUG 608 va = NULL; 609 if (malloc_dbg(&va, &size, mtp, flags) != 0) 610 return (va); 611 #endif 612 if (size <= kmem_zmax && (flags & M_EXEC) == 0) { 613 if (size & KMEM_ZMASK) 614 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE; 615 indx = kmemsize[size >> KMEM_ZSHIFT]; 616 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)]; 617 #ifdef MALLOC_PROFILE 618 krequests[size >> KMEM_ZSHIFT]++; 619 #endif 620 va = uma_zalloc_domain(zone, NULL, domain, flags); 621 if (va != NULL) 622 size = zone->uz_size; 623 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx); 624 } else { 625 size = roundup(size, PAGE_SIZE); 626 zone = NULL; 627 va = uma_large_malloc_domain(size, domain, flags); 628 malloc_type_allocated(mtp, va == NULL ? 0 : size); 629 } 630 if (flags & M_WAITOK) 631 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL")); 632 else if (va == NULL) 633 t_malloc_fail = time_uptime; 634 #ifdef DEBUG_REDZONE 635 if (va != NULL) 636 va = redzone_setup(va, osize); 637 #endif 638 return ((void *) va); 639 } 640 641 void * 642 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags) 643 { 644 645 if (WOULD_OVERFLOW(nmemb, size)) 646 panic("mallocarray: %zu * %zu overflowed", nmemb, size); 647 648 return (malloc(size * nmemb, type, flags)); 649 } 650 651 #ifdef INVARIANTS 652 static void 653 free_save_type(void *addr, struct malloc_type *mtp, u_long size) 654 { 655 struct malloc_type **mtpp = addr; 656 657 /* 658 * Cache a pointer to the malloc_type that most recently freed 659 * this memory here. This way we know who is most likely to 660 * have stepped on it later. 661 * 662 * This code assumes that size is a multiple of 8 bytes for 663 * 64 bit machines 664 */ 665 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR); 666 mtpp += (size - sizeof(struct malloc_type *)) / 667 sizeof(struct malloc_type *); 668 *mtpp = mtp; 669 } 670 #endif 671 672 #ifdef MALLOC_DEBUG 673 static int 674 free_dbg(void **addrp, struct malloc_type *mtp) 675 { 676 void *addr; 677 678 addr = *addrp; 679 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic")); 680 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(), 681 ("free: called with spinlock or critical section held")); 682 683 /* free(NULL, ...) does nothing */ 684 if (addr == NULL) 685 return (EJUSTRETURN); 686 687 #ifdef DEBUG_MEMGUARD 688 if (is_memguard_addr(addr)) { 689 memguard_free(addr); 690 return (EJUSTRETURN); 691 } 692 #endif 693 694 #ifdef DEBUG_REDZONE 695 redzone_check(addr); 696 *addrp = redzone_addr_ntor(addr); 697 #endif 698 699 return (0); 700 } 701 #endif 702 703 /* 704 * free: 705 * 706 * Free a block of memory allocated by malloc. 707 * 708 * This routine may not block. 709 */ 710 void 711 free(void *addr, struct malloc_type *mtp) 712 { 713 uma_slab_t slab; 714 u_long size; 715 716 #ifdef MALLOC_DEBUG 717 if (free_dbg(&addr, mtp) != 0) 718 return; 719 #endif 720 /* free(NULL, ...) does nothing */ 721 if (addr == NULL) 722 return; 723 724 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK)); 725 if (slab == NULL) 726 panic("free: address %p(%p) has not been allocated.\n", 727 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK))); 728 729 if (!(slab->us_flags & UMA_SLAB_MALLOC)) { 730 size = slab->us_keg->uk_size; 731 #ifdef INVARIANTS 732 free_save_type(addr, mtp, size); 733 #endif 734 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab); 735 } else { 736 size = slab->us_size; 737 uma_large_free(slab); 738 } 739 malloc_type_freed(mtp, size); 740 } 741 742 void 743 free_domain(void *addr, struct malloc_type *mtp) 744 { 745 uma_slab_t slab; 746 u_long size; 747 748 #ifdef MALLOC_DEBUG 749 if (free_dbg(&addr, mtp) != 0) 750 return; 751 #endif 752 753 /* free(NULL, ...) does nothing */ 754 if (addr == NULL) 755 return; 756 757 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK)); 758 if (slab == NULL) 759 panic("free_domain: address %p(%p) has not been allocated.\n", 760 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK))); 761 762 if (!(slab->us_flags & UMA_SLAB_MALLOC)) { 763 size = slab->us_keg->uk_size; 764 #ifdef INVARIANTS 765 free_save_type(addr, mtp, size); 766 #endif 767 uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones), 768 addr, slab); 769 } else { 770 size = slab->us_size; 771 uma_large_free(slab); 772 } 773 malloc_type_freed(mtp, size); 774 } 775 776 /* 777 * realloc: change the size of a memory block 778 */ 779 void * 780 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags) 781 { 782 uma_slab_t slab; 783 unsigned long alloc; 784 void *newaddr; 785 786 KASSERT(mtp->ks_magic == M_MAGIC, 787 ("realloc: bad malloc type magic")); 788 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(), 789 ("realloc: called with spinlock or critical section held")); 790 791 /* realloc(NULL, ...) is equivalent to malloc(...) */ 792 if (addr == NULL) 793 return (malloc(size, mtp, flags)); 794 795 /* 796 * XXX: Should report free of old memory and alloc of new memory to 797 * per-CPU stats. 798 */ 799 800 #ifdef DEBUG_MEMGUARD 801 if (is_memguard_addr(addr)) 802 return (memguard_realloc(addr, size, mtp, flags)); 803 #endif 804 805 #ifdef DEBUG_REDZONE 806 slab = NULL; 807 alloc = redzone_get_size(addr); 808 #else 809 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK)); 810 811 /* Sanity check */ 812 KASSERT(slab != NULL, 813 ("realloc: address %p out of range", (void *)addr)); 814 815 /* Get the size of the original block */ 816 if (!(slab->us_flags & UMA_SLAB_MALLOC)) 817 alloc = slab->us_keg->uk_size; 818 else 819 alloc = slab->us_size; 820 821 /* Reuse the original block if appropriate */ 822 if (size <= alloc 823 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE)) 824 return (addr); 825 #endif /* !DEBUG_REDZONE */ 826 827 /* Allocate a new, bigger (or smaller) block */ 828 if ((newaddr = malloc(size, mtp, flags)) == NULL) 829 return (NULL); 830 831 /* Copy over original contents */ 832 bcopy(addr, newaddr, min(size, alloc)); 833 free(addr, mtp); 834 return (newaddr); 835 } 836 837 /* 838 * reallocf: same as realloc() but free memory on failure. 839 */ 840 void * 841 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags) 842 { 843 void *mem; 844 845 if ((mem = realloc(addr, size, mtp, flags)) == NULL) 846 free(addr, mtp); 847 return (mem); 848 } 849 850 #ifndef __sparc64__ 851 CTASSERT(VM_KMEM_SIZE_SCALE >= 1); 852 #endif 853 854 /* 855 * Initialize the kernel memory (kmem) arena. 856 */ 857 void 858 kmeminit(void) 859 { 860 u_long mem_size; 861 u_long tmp; 862 863 #ifdef VM_KMEM_SIZE 864 if (vm_kmem_size == 0) 865 vm_kmem_size = VM_KMEM_SIZE; 866 #endif 867 #ifdef VM_KMEM_SIZE_MIN 868 if (vm_kmem_size_min == 0) 869 vm_kmem_size_min = VM_KMEM_SIZE_MIN; 870 #endif 871 #ifdef VM_KMEM_SIZE_MAX 872 if (vm_kmem_size_max == 0) 873 vm_kmem_size_max = VM_KMEM_SIZE_MAX; 874 #endif 875 /* 876 * Calculate the amount of kernel virtual address (KVA) space that is 877 * preallocated to the kmem arena. In order to support a wide range 878 * of machines, it is a function of the physical memory size, 879 * specifically, 880 * 881 * min(max(physical memory size / VM_KMEM_SIZE_SCALE, 882 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX) 883 * 884 * Every architecture must define an integral value for 885 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN 886 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and 887 * ceiling on this preallocation, are optional. Typically, 888 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on 889 * a given architecture. 890 */ 891 mem_size = vm_cnt.v_page_count; 892 if (mem_size <= 32768) /* delphij XXX 128MB */ 893 kmem_zmax = PAGE_SIZE; 894 895 if (vm_kmem_size_scale < 1) 896 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE; 897 898 /* 899 * Check if we should use defaults for the "vm_kmem_size" 900 * variable: 901 */ 902 if (vm_kmem_size == 0) { 903 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE; 904 905 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) 906 vm_kmem_size = vm_kmem_size_min; 907 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max) 908 vm_kmem_size = vm_kmem_size_max; 909 } 910 911 /* 912 * The amount of KVA space that is preallocated to the 913 * kmem arena can be set statically at compile-time or manually 914 * through the kernel environment. However, it is still limited to 915 * twice the physical memory size, which has been sufficient to handle 916 * the most severe cases of external fragmentation in the kmem arena. 917 */ 918 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size) 919 vm_kmem_size = 2 * mem_size * PAGE_SIZE; 920 921 vm_kmem_size = round_page(vm_kmem_size); 922 #ifdef DEBUG_MEMGUARD 923 tmp = memguard_fudge(vm_kmem_size, kernel_map); 924 #else 925 tmp = vm_kmem_size; 926 #endif 927 uma_set_limit(tmp); 928 929 #ifdef DEBUG_MEMGUARD 930 /* 931 * Initialize MemGuard if support compiled in. MemGuard is a 932 * replacement allocator used for detecting tamper-after-free 933 * scenarios as they occur. It is only used for debugging. 934 */ 935 memguard_init(kernel_arena); 936 #endif 937 } 938 939 /* 940 * Initialize the kernel memory allocator 941 */ 942 /* ARGSUSED*/ 943 static void 944 mallocinit(void *dummy) 945 { 946 int i; 947 uint8_t indx; 948 949 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF); 950 951 kmeminit(); 952 953 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX) 954 kmem_zmax = KMEM_ZMAX; 955 956 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal), 957 #ifdef INVARIANTS 958 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini, 959 #else 960 NULL, NULL, NULL, NULL, 961 #endif 962 UMA_ALIGN_PTR, UMA_ZONE_MALLOC); 963 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) { 964 int size = kmemzones[indx].kz_size; 965 char *name = kmemzones[indx].kz_name; 966 int subzone; 967 968 for (subzone = 0; subzone < numzones; subzone++) { 969 kmemzones[indx].kz_zone[subzone] = 970 uma_zcreate(name, size, 971 #ifdef INVARIANTS 972 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini, 973 #else 974 NULL, NULL, NULL, NULL, 975 #endif 976 UMA_ALIGN_PTR, UMA_ZONE_MALLOC); 977 } 978 for (;i <= size; i+= KMEM_ZBASE) 979 kmemsize[i >> KMEM_ZSHIFT] = indx; 980 981 } 982 } 983 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL); 984 985 void 986 malloc_init(void *data) 987 { 988 struct malloc_type_internal *mtip; 989 struct malloc_type *mtp; 990 991 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init")); 992 993 mtp = data; 994 if (mtp->ks_magic != M_MAGIC) 995 panic("malloc_init: bad malloc type magic"); 996 997 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO); 998 mtp->ks_handle = mtip; 999 mtp_set_subzone(mtp); 1000 1001 mtx_lock(&malloc_mtx); 1002 mtp->ks_next = kmemstatistics; 1003 kmemstatistics = mtp; 1004 kmemcount++; 1005 mtx_unlock(&malloc_mtx); 1006 } 1007 1008 void 1009 malloc_uninit(void *data) 1010 { 1011 struct malloc_type_internal *mtip; 1012 struct malloc_type_stats *mtsp; 1013 struct malloc_type *mtp, *temp; 1014 uma_slab_t slab; 1015 long temp_allocs, temp_bytes; 1016 int i; 1017 1018 mtp = data; 1019 KASSERT(mtp->ks_magic == M_MAGIC, 1020 ("malloc_uninit: bad malloc type magic")); 1021 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL")); 1022 1023 mtx_lock(&malloc_mtx); 1024 mtip = mtp->ks_handle; 1025 mtp->ks_handle = NULL; 1026 if (mtp != kmemstatistics) { 1027 for (temp = kmemstatistics; temp != NULL; 1028 temp = temp->ks_next) { 1029 if (temp->ks_next == mtp) { 1030 temp->ks_next = mtp->ks_next; 1031 break; 1032 } 1033 } 1034 KASSERT(temp, 1035 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc)); 1036 } else 1037 kmemstatistics = mtp->ks_next; 1038 kmemcount--; 1039 mtx_unlock(&malloc_mtx); 1040 1041 /* 1042 * Look for memory leaks. 1043 */ 1044 temp_allocs = temp_bytes = 0; 1045 for (i = 0; i < MAXCPU; i++) { 1046 mtsp = &mtip->mti_stats[i]; 1047 temp_allocs += mtsp->mts_numallocs; 1048 temp_allocs -= mtsp->mts_numfrees; 1049 temp_bytes += mtsp->mts_memalloced; 1050 temp_bytes -= mtsp->mts_memfreed; 1051 } 1052 if (temp_allocs > 0 || temp_bytes > 0) { 1053 printf("Warning: memory type %s leaked memory on destroy " 1054 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc, 1055 temp_allocs, temp_bytes); 1056 } 1057 1058 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK)); 1059 uma_zfree_arg(mt_zone, mtip, slab); 1060 } 1061 1062 struct malloc_type * 1063 malloc_desc2type(const char *desc) 1064 { 1065 struct malloc_type *mtp; 1066 1067 mtx_assert(&malloc_mtx, MA_OWNED); 1068 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) { 1069 if (strcmp(mtp->ks_shortdesc, desc) == 0) 1070 return (mtp); 1071 } 1072 return (NULL); 1073 } 1074 1075 static int 1076 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS) 1077 { 1078 struct malloc_type_stream_header mtsh; 1079 struct malloc_type_internal *mtip; 1080 struct malloc_type_header mth; 1081 struct malloc_type *mtp; 1082 int error, i; 1083 struct sbuf sbuf; 1084 1085 error = sysctl_wire_old_buffer(req, 0); 1086 if (error != 0) 1087 return (error); 1088 sbuf_new_for_sysctl(&sbuf, NULL, 128, req); 1089 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL); 1090 mtx_lock(&malloc_mtx); 1091 1092 /* 1093 * Insert stream header. 1094 */ 1095 bzero(&mtsh, sizeof(mtsh)); 1096 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION; 1097 mtsh.mtsh_maxcpus = MAXCPU; 1098 mtsh.mtsh_count = kmemcount; 1099 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)); 1100 1101 /* 1102 * Insert alternating sequence of type headers and type statistics. 1103 */ 1104 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) { 1105 mtip = (struct malloc_type_internal *)mtp->ks_handle; 1106 1107 /* 1108 * Insert type header. 1109 */ 1110 bzero(&mth, sizeof(mth)); 1111 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME); 1112 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth)); 1113 1114 /* 1115 * Insert type statistics for each CPU. 1116 */ 1117 for (i = 0; i < MAXCPU; i++) { 1118 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i], 1119 sizeof(mtip->mti_stats[i])); 1120 } 1121 } 1122 mtx_unlock(&malloc_mtx); 1123 error = sbuf_finish(&sbuf); 1124 sbuf_delete(&sbuf); 1125 return (error); 1126 } 1127 1128 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT, 1129 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats", 1130 "Return malloc types"); 1131 1132 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0, 1133 "Count of kernel malloc types"); 1134 1135 void 1136 malloc_type_list(malloc_type_list_func_t *func, void *arg) 1137 { 1138 struct malloc_type *mtp, **bufmtp; 1139 int count, i; 1140 size_t buflen; 1141 1142 mtx_lock(&malloc_mtx); 1143 restart: 1144 mtx_assert(&malloc_mtx, MA_OWNED); 1145 count = kmemcount; 1146 mtx_unlock(&malloc_mtx); 1147 1148 buflen = sizeof(struct malloc_type *) * count; 1149 bufmtp = malloc(buflen, M_TEMP, M_WAITOK); 1150 1151 mtx_lock(&malloc_mtx); 1152 1153 if (count < kmemcount) { 1154 free(bufmtp, M_TEMP); 1155 goto restart; 1156 } 1157 1158 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++) 1159 bufmtp[i] = mtp; 1160 1161 mtx_unlock(&malloc_mtx); 1162 1163 for (i = 0; i < count; i++) 1164 (func)(bufmtp[i], arg); 1165 1166 free(bufmtp, M_TEMP); 1167 } 1168 1169 #ifdef DDB 1170 DB_SHOW_COMMAND(malloc, db_show_malloc) 1171 { 1172 struct malloc_type_internal *mtip; 1173 struct malloc_type *mtp; 1174 uint64_t allocs, frees; 1175 uint64_t alloced, freed; 1176 int i; 1177 1178 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse", 1179 "Requests"); 1180 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) { 1181 mtip = (struct malloc_type_internal *)mtp->ks_handle; 1182 allocs = 0; 1183 frees = 0; 1184 alloced = 0; 1185 freed = 0; 1186 for (i = 0; i < MAXCPU; i++) { 1187 allocs += mtip->mti_stats[i].mts_numallocs; 1188 frees += mtip->mti_stats[i].mts_numfrees; 1189 alloced += mtip->mti_stats[i].mts_memalloced; 1190 freed += mtip->mti_stats[i].mts_memfreed; 1191 } 1192 db_printf("%18s %12ju %12juK %12ju\n", 1193 mtp->ks_shortdesc, allocs - frees, 1194 (alloced - freed + 1023) / 1024, allocs); 1195 if (db_pager_quit) 1196 break; 1197 } 1198 } 1199 1200 #if MALLOC_DEBUG_MAXZONES > 1 1201 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches) 1202 { 1203 struct malloc_type_internal *mtip; 1204 struct malloc_type *mtp; 1205 u_int subzone; 1206 1207 if (!have_addr) { 1208 db_printf("Usage: show multizone_matches <malloc type/addr>\n"); 1209 return; 1210 } 1211 mtp = (void *)addr; 1212 if (mtp->ks_magic != M_MAGIC) { 1213 db_printf("Magic %lx does not match expected %x\n", 1214 mtp->ks_magic, M_MAGIC); 1215 return; 1216 } 1217 1218 mtip = mtp->ks_handle; 1219 subzone = mtip->mti_zone; 1220 1221 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) { 1222 mtip = mtp->ks_handle; 1223 if (mtip->mti_zone != subzone) 1224 continue; 1225 db_printf("%s\n", mtp->ks_shortdesc); 1226 if (db_pager_quit) 1227 break; 1228 } 1229 } 1230 #endif /* MALLOC_DEBUG_MAXZONES > 1 */ 1231 #endif /* DDB */ 1232 1233 #ifdef MALLOC_PROFILE 1234 1235 static int 1236 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS) 1237 { 1238 struct sbuf sbuf; 1239 uint64_t count; 1240 uint64_t waste; 1241 uint64_t mem; 1242 int error; 1243 int rsize; 1244 int size; 1245 int i; 1246 1247 waste = 0; 1248 mem = 0; 1249 1250 error = sysctl_wire_old_buffer(req, 0); 1251 if (error != 0) 1252 return (error); 1253 sbuf_new_for_sysctl(&sbuf, NULL, 128, req); 1254 sbuf_printf(&sbuf, 1255 "\n Size Requests Real Size\n"); 1256 for (i = 0; i < KMEM_ZSIZE; i++) { 1257 size = i << KMEM_ZSHIFT; 1258 rsize = kmemzones[kmemsize[i]].kz_size; 1259 count = (long long unsigned)krequests[i]; 1260 1261 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size, 1262 (unsigned long long)count, rsize); 1263 1264 if ((rsize * count) > (size * count)) 1265 waste += (rsize * count) - (size * count); 1266 mem += (rsize * count); 1267 } 1268 sbuf_printf(&sbuf, 1269 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n", 1270 (unsigned long long)mem, (unsigned long long)waste); 1271 error = sbuf_finish(&sbuf); 1272 sbuf_delete(&sbuf); 1273 return (error); 1274 } 1275 1276 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD, 1277 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling"); 1278 #endif /* MALLOC_PROFILE */ 1279