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