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_vm.h" 50 51 #include <sys/param.h> 52 #include <sys/systm.h> 53 #include <sys/kdb.h> 54 #include <sys/kernel.h> 55 #include <sys/lock.h> 56 #include <sys/malloc.h> 57 #include <sys/mutex.h> 58 #include <sys/vmmeter.h> 59 #include <sys/proc.h> 60 #include <sys/sbuf.h> 61 #include <sys/sysctl.h> 62 #include <sys/time.h> 63 #include <sys/vmem.h> 64 65 #include <vm/vm.h> 66 #include <vm/pmap.h> 67 #include <vm/vm_pageout.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 struct malloc_type *kmemstatistics; 117 static int kmemcount; 118 119 #define KMEM_ZSHIFT 4 120 #define KMEM_ZBASE 16 121 #define KMEM_ZMASK (KMEM_ZBASE - 1) 122 123 #define KMEM_ZMAX PAGE_SIZE 124 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT) 125 static uint8_t kmemsize[KMEM_ZSIZE + 1]; 126 127 #ifndef MALLOC_DEBUG_MAXZONES 128 #define MALLOC_DEBUG_MAXZONES 1 129 #endif 130 static int numzones = MALLOC_DEBUG_MAXZONES; 131 132 /* 133 * Small malloc(9) memory allocations are allocated from a set of UMA buckets 134 * of various sizes. 135 * 136 * XXX: The comment here used to read "These won't be powers of two for 137 * long." It's possible that a significant amount of wasted memory could be 138 * recovered by tuning the sizes of these buckets. 139 */ 140 struct { 141 int kz_size; 142 char *kz_name; 143 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES]; 144 } kmemzones[] = { 145 {16, "16", }, 146 {32, "32", }, 147 {64, "64", }, 148 {128, "128", }, 149 {256, "256", }, 150 {512, "512", }, 151 {1024, "1024", }, 152 {2048, "2048", }, 153 {4096, "4096", }, 154 #if PAGE_SIZE > 4096 155 {8192, "8192", }, 156 #if PAGE_SIZE > 8192 157 {16384, "16384", }, 158 #if PAGE_SIZE > 16384 159 {32768, "32768", }, 160 #if PAGE_SIZE > 32768 161 {65536, "65536", }, 162 #if PAGE_SIZE > 65536 163 #error "Unsupported PAGE_SIZE" 164 #endif /* 65536 */ 165 #endif /* 32768 */ 166 #endif /* 16384 */ 167 #endif /* 8192 */ 168 #endif /* 4096 */ 169 {0, NULL}, 170 }; 171 172 /* 173 * Zone to allocate malloc type descriptions from. For ABI reasons, memory 174 * types are described by a data structure passed by the declaring code, but 175 * the malloc(9) implementation has its own data structure describing the 176 * type and statistics. This permits the malloc(9)-internal data structures 177 * to be modified without breaking binary-compiled kernel modules that 178 * declare malloc types. 179 */ 180 static uma_zone_t mt_zone; 181 182 u_long vm_kmem_size; 183 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0, 184 "Size of kernel memory"); 185 186 static u_long vm_kmem_size_min; 187 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0, 188 "Minimum size of kernel memory"); 189 190 static u_long vm_kmem_size_max; 191 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0, 192 "Maximum size of kernel memory"); 193 194 static u_int vm_kmem_size_scale; 195 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0, 196 "Scale factor for kernel memory size"); 197 198 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS); 199 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size, 200 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0, 201 sysctl_kmem_map_size, "LU", "Current kmem allocation size"); 202 203 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS); 204 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free, 205 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0, 206 sysctl_kmem_map_free, "LU", "Free space in kmem"); 207 208 /* 209 * The malloc_mtx protects the kmemstatistics linked list. 210 */ 211 struct mtx malloc_mtx; 212 213 #ifdef MALLOC_PROFILE 214 uint64_t krequests[KMEM_ZSIZE + 1]; 215 216 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS); 217 #endif 218 219 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS); 220 221 /* 222 * time_uptime of the last malloc(9) failure (induced or real). 223 */ 224 static time_t t_malloc_fail; 225 226 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1) 227 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0, 228 "Kernel malloc debugging options"); 229 #endif 230 231 /* 232 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when 233 * the caller specifies M_NOWAIT. If set to 0, no failures are caused. 234 */ 235 #ifdef MALLOC_MAKE_FAILURES 236 static int malloc_failure_rate; 237 static int malloc_nowait_count; 238 static int malloc_failure_count; 239 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN, 240 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail"); 241 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD, 242 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures"); 243 #endif 244 245 static int 246 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS) 247 { 248 u_long size; 249 250 size = vmem_size(kmem_arena, VMEM_ALLOC); 251 return (sysctl_handle_long(oidp, &size, 0, req)); 252 } 253 254 static int 255 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS) 256 { 257 u_long size; 258 259 size = vmem_size(kmem_arena, VMEM_FREE); 260 return (sysctl_handle_long(oidp, &size, 0, req)); 261 } 262 263 /* 264 * malloc(9) uma zone separation -- sub-page buffer overruns in one 265 * malloc type will affect only a subset of other malloc types. 266 */ 267 #if MALLOC_DEBUG_MAXZONES > 1 268 static void 269 tunable_set_numzones(void) 270 { 271 272 TUNABLE_INT_FETCH("debug.malloc.numzones", 273 &numzones); 274 275 /* Sanity check the number of malloc uma zones. */ 276 if (numzones <= 0) 277 numzones = 1; 278 if (numzones > MALLOC_DEBUG_MAXZONES) 279 numzones = MALLOC_DEBUG_MAXZONES; 280 } 281 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL); 282 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, 283 &numzones, 0, "Number of malloc uma subzones"); 284 285 /* 286 * Any number that changes regularly is an okay choice for the 287 * offset. Build numbers are pretty good of you have them. 288 */ 289 static u_int zone_offset = __FreeBSD_version; 290 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset); 291 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN, 292 &zone_offset, 0, "Separate malloc types by examining the " 293 "Nth character in the malloc type short description."); 294 295 static u_int 296 mtp_get_subzone(const char *desc) 297 { 298 size_t len; 299 u_int val; 300 301 if (desc == NULL || (len = strlen(desc)) == 0) 302 return (0); 303 val = desc[zone_offset % len]; 304 return (val % numzones); 305 } 306 #elif MALLOC_DEBUG_MAXZONES == 0 307 #error "MALLOC_DEBUG_MAXZONES must be positive." 308 #else 309 static inline u_int 310 mtp_get_subzone(const char *desc) 311 { 312 313 return (0); 314 } 315 #endif /* MALLOC_DEBUG_MAXZONES > 1 */ 316 317 int 318 malloc_last_fail(void) 319 { 320 321 return (time_uptime - t_malloc_fail); 322 } 323 324 /* 325 * An allocation has succeeded -- update malloc type statistics for the 326 * amount of bucket size. Occurs within a critical section so that the 327 * thread isn't preempted and doesn't migrate while updating per-PCU 328 * statistics. 329 */ 330 static void 331 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size, 332 int zindx) 333 { 334 struct malloc_type_internal *mtip; 335 struct malloc_type_stats *mtsp; 336 337 critical_enter(); 338 mtip = mtp->ks_handle; 339 mtsp = &mtip->mti_stats[curcpu]; 340 if (size > 0) { 341 mtsp->mts_memalloced += size; 342 mtsp->mts_numallocs++; 343 } 344 if (zindx != -1) 345 mtsp->mts_size |= 1 << zindx; 346 347 #ifdef KDTRACE_HOOKS 348 if (dtrace_malloc_probe != NULL) { 349 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC]; 350 if (probe_id != 0) 351 (dtrace_malloc_probe)(probe_id, 352 (uintptr_t) mtp, (uintptr_t) mtip, 353 (uintptr_t) mtsp, size, zindx); 354 } 355 #endif 356 357 critical_exit(); 358 } 359 360 void 361 malloc_type_allocated(struct malloc_type *mtp, unsigned long size) 362 { 363 364 if (size > 0) 365 malloc_type_zone_allocated(mtp, size, -1); 366 } 367 368 /* 369 * A free operation has occurred -- update malloc type statistics for the 370 * amount of the bucket size. Occurs within a critical section so that the 371 * thread isn't preempted and doesn't migrate while updating per-CPU 372 * statistics. 373 */ 374 void 375 malloc_type_freed(struct malloc_type *mtp, unsigned long size) 376 { 377 struct malloc_type_internal *mtip; 378 struct malloc_type_stats *mtsp; 379 380 critical_enter(); 381 mtip = mtp->ks_handle; 382 mtsp = &mtip->mti_stats[curcpu]; 383 mtsp->mts_memfreed += size; 384 mtsp->mts_numfrees++; 385 386 #ifdef KDTRACE_HOOKS 387 if (dtrace_malloc_probe != NULL) { 388 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE]; 389 if (probe_id != 0) 390 (dtrace_malloc_probe)(probe_id, 391 (uintptr_t) mtp, (uintptr_t) mtip, 392 (uintptr_t) mtsp, size, 0); 393 } 394 #endif 395 396 critical_exit(); 397 } 398 399 /* 400 * contigmalloc: 401 * 402 * Allocate a block of physically contiguous memory. 403 * 404 * If M_NOWAIT is set, this routine will not block and return NULL if 405 * the allocation fails. 406 */ 407 void * 408 contigmalloc(unsigned long size, struct malloc_type *type, int flags, 409 vm_paddr_t low, vm_paddr_t high, unsigned long alignment, 410 vm_paddr_t boundary) 411 { 412 void *ret; 413 414 ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high, 415 alignment, boundary, VM_MEMATTR_DEFAULT); 416 if (ret != NULL) 417 malloc_type_allocated(type, round_page(size)); 418 return (ret); 419 } 420 421 /* 422 * contigfree: 423 * 424 * Free a block of memory allocated by contigmalloc. 425 * 426 * This routine may not block. 427 */ 428 void 429 contigfree(void *addr, unsigned long size, struct malloc_type *type) 430 { 431 432 kmem_free(kernel_arena, (vm_offset_t)addr, size); 433 malloc_type_freed(type, round_page(size)); 434 } 435 436 /* 437 * malloc: 438 * 439 * Allocate a block of memory. 440 * 441 * If M_NOWAIT is set, this routine will not block and return NULL if 442 * the allocation fails. 443 */ 444 void * 445 malloc(unsigned long size, struct malloc_type *mtp, int flags) 446 { 447 int indx; 448 struct malloc_type_internal *mtip; 449 caddr_t va; 450 uma_zone_t zone; 451 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE) 452 unsigned long osize = size; 453 #endif 454 455 #ifdef INVARIANTS 456 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic")); 457 /* 458 * Check that exactly one of M_WAITOK or M_NOWAIT is specified. 459 */ 460 indx = flags & (M_WAITOK | M_NOWAIT); 461 if (indx != M_NOWAIT && indx != M_WAITOK) { 462 static struct timeval lasterr; 463 static int curerr, once; 464 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) { 465 printf("Bad malloc flags: %x\n", indx); 466 kdb_backtrace(); 467 flags |= M_WAITOK; 468 once++; 469 } 470 } 471 #endif 472 #ifdef MALLOC_MAKE_FAILURES 473 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) { 474 atomic_add_int(&malloc_nowait_count, 1); 475 if ((malloc_nowait_count % malloc_failure_rate) == 0) { 476 atomic_add_int(&malloc_failure_count, 1); 477 t_malloc_fail = time_uptime; 478 return (NULL); 479 } 480 } 481 #endif 482 if (flags & M_WAITOK) 483 KASSERT(curthread->td_intr_nesting_level == 0, 484 ("malloc(M_WAITOK) in interrupt context")); 485 486 #ifdef DEBUG_MEMGUARD 487 if (memguard_cmp_mtp(mtp, size)) { 488 va = memguard_alloc(size, flags); 489 if (va != NULL) 490 return (va); 491 /* This is unfortunate but should not be fatal. */ 492 } 493 #endif 494 495 #ifdef DEBUG_REDZONE 496 size = redzone_size_ntor(size); 497 #endif 498 499 if (size <= KMEM_ZMAX) { 500 mtip = mtp->ks_handle; 501 if (size & KMEM_ZMASK) 502 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE; 503 indx = kmemsize[size >> KMEM_ZSHIFT]; 504 KASSERT(mtip->mti_zone < numzones, 505 ("mti_zone %u out of range %d", 506 mtip->mti_zone, numzones)); 507 zone = kmemzones[indx].kz_zone[mtip->mti_zone]; 508 #ifdef MALLOC_PROFILE 509 krequests[size >> KMEM_ZSHIFT]++; 510 #endif 511 va = uma_zalloc(zone, flags); 512 if (va != NULL) 513 size = zone->uz_size; 514 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx); 515 } else { 516 size = roundup(size, PAGE_SIZE); 517 zone = NULL; 518 va = uma_large_malloc(size, flags); 519 malloc_type_allocated(mtp, va == NULL ? 0 : size); 520 } 521 if (flags & M_WAITOK) 522 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL")); 523 else if (va == NULL) 524 t_malloc_fail = time_uptime; 525 #ifdef DIAGNOSTIC 526 if (va != NULL && !(flags & M_ZERO)) { 527 memset(va, 0x70, osize); 528 } 529 #endif 530 #ifdef DEBUG_REDZONE 531 if (va != NULL) 532 va = redzone_setup(va, osize); 533 #endif 534 return ((void *) va); 535 } 536 537 /* 538 * free: 539 * 540 * Free a block of memory allocated by malloc. 541 * 542 * This routine may not block. 543 */ 544 void 545 free(void *addr, struct malloc_type *mtp) 546 { 547 uma_slab_t slab; 548 u_long size; 549 550 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic")); 551 552 /* free(NULL, ...) does nothing */ 553 if (addr == NULL) 554 return; 555 556 #ifdef DEBUG_MEMGUARD 557 if (is_memguard_addr(addr)) { 558 memguard_free(addr); 559 return; 560 } 561 #endif 562 563 #ifdef DEBUG_REDZONE 564 redzone_check(addr); 565 addr = redzone_addr_ntor(addr); 566 #endif 567 568 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK)); 569 570 if (slab == NULL) 571 panic("free: address %p(%p) has not been allocated.\n", 572 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK))); 573 574 if (!(slab->us_flags & UMA_SLAB_MALLOC)) { 575 #ifdef INVARIANTS 576 struct malloc_type **mtpp = addr; 577 #endif 578 size = slab->us_keg->uk_size; 579 #ifdef INVARIANTS 580 /* 581 * Cache a pointer to the malloc_type that most recently freed 582 * this memory here. This way we know who is most likely to 583 * have stepped on it later. 584 * 585 * This code assumes that size is a multiple of 8 bytes for 586 * 64 bit machines 587 */ 588 mtpp = (struct malloc_type **) 589 ((unsigned long)mtpp & ~UMA_ALIGN_PTR); 590 mtpp += (size - sizeof(struct malloc_type *)) / 591 sizeof(struct malloc_type *); 592 *mtpp = mtp; 593 #endif 594 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab); 595 } else { 596 size = slab->us_size; 597 uma_large_free(slab); 598 } 599 malloc_type_freed(mtp, size); 600 } 601 602 /* 603 * realloc: change the size of a memory block 604 */ 605 void * 606 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags) 607 { 608 uma_slab_t slab; 609 unsigned long alloc; 610 void *newaddr; 611 612 KASSERT(mtp->ks_magic == M_MAGIC, 613 ("realloc: bad malloc type magic")); 614 615 /* realloc(NULL, ...) is equivalent to malloc(...) */ 616 if (addr == NULL) 617 return (malloc(size, mtp, flags)); 618 619 /* 620 * XXX: Should report free of old memory and alloc of new memory to 621 * per-CPU stats. 622 */ 623 624 #ifdef DEBUG_MEMGUARD 625 if (is_memguard_addr(addr)) 626 return (memguard_realloc(addr, size, mtp, flags)); 627 #endif 628 629 #ifdef DEBUG_REDZONE 630 slab = NULL; 631 alloc = redzone_get_size(addr); 632 #else 633 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK)); 634 635 /* Sanity check */ 636 KASSERT(slab != NULL, 637 ("realloc: address %p out of range", (void *)addr)); 638 639 /* Get the size of the original block */ 640 if (!(slab->us_flags & UMA_SLAB_MALLOC)) 641 alloc = slab->us_keg->uk_size; 642 else 643 alloc = slab->us_size; 644 645 /* Reuse the original block if appropriate */ 646 if (size <= alloc 647 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE)) 648 return (addr); 649 #endif /* !DEBUG_REDZONE */ 650 651 /* Allocate a new, bigger (or smaller) block */ 652 if ((newaddr = malloc(size, mtp, flags)) == NULL) 653 return (NULL); 654 655 /* Copy over original contents */ 656 bcopy(addr, newaddr, min(size, alloc)); 657 free(addr, mtp); 658 return (newaddr); 659 } 660 661 /* 662 * reallocf: same as realloc() but free memory on failure. 663 */ 664 void * 665 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags) 666 { 667 void *mem; 668 669 if ((mem = realloc(addr, size, mtp, flags)) == NULL) 670 free(addr, mtp); 671 return (mem); 672 } 673 674 /* 675 * Wake the page daemon when we exhaust KVA. It will call the lowmem handler 676 * and uma_reclaim() callbacks in a context that is safe. 677 */ 678 static void 679 kmem_reclaim(vmem_t *vm, int flags) 680 { 681 682 pagedaemon_wakeup(); 683 } 684 685 #ifndef __sparc64__ 686 CTASSERT(VM_KMEM_SIZE_SCALE >= 1); 687 #endif 688 689 /* 690 * Initialize the kernel memory (kmem) arena. 691 */ 692 void 693 kmeminit(void) 694 { 695 u_long mem_size; 696 u_long tmp; 697 698 #ifdef VM_KMEM_SIZE 699 if (vm_kmem_size == 0) 700 vm_kmem_size = VM_KMEM_SIZE; 701 #endif 702 #ifdef VM_KMEM_SIZE_MIN 703 if (vm_kmem_size_min == 0) 704 vm_kmem_size_min = VM_KMEM_SIZE_MIN; 705 #endif 706 #ifdef VM_KMEM_SIZE_MAX 707 if (vm_kmem_size_max == 0) 708 vm_kmem_size_max = VM_KMEM_SIZE_MAX; 709 #endif 710 /* 711 * Calculate the amount of kernel virtual address (KVA) space that is 712 * preallocated to the kmem arena. In order to support a wide range 713 * of machines, it is a function of the physical memory size, 714 * specifically, 715 * 716 * min(max(physical memory size / VM_KMEM_SIZE_SCALE, 717 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX) 718 * 719 * Every architecture must define an integral value for 720 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN 721 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and 722 * ceiling on this preallocation, are optional. Typically, 723 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on 724 * a given architecture. 725 */ 726 mem_size = vm_cnt.v_page_count; 727 728 if (vm_kmem_size_scale < 1) 729 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE; 730 731 /* 732 * Check if we should use defaults for the "vm_kmem_size" 733 * variable: 734 */ 735 if (vm_kmem_size == 0) { 736 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE; 737 738 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) 739 vm_kmem_size = vm_kmem_size_min; 740 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max) 741 vm_kmem_size = vm_kmem_size_max; 742 } 743 744 /* 745 * The amount of KVA space that is preallocated to the 746 * kmem arena can be set statically at compile-time or manually 747 * through the kernel environment. However, it is still limited to 748 * twice the physical memory size, which has been sufficient to handle 749 * the most severe cases of external fragmentation in the kmem arena. 750 */ 751 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size) 752 vm_kmem_size = 2 * mem_size * PAGE_SIZE; 753 754 vm_kmem_size = round_page(vm_kmem_size); 755 #ifdef DEBUG_MEMGUARD 756 tmp = memguard_fudge(vm_kmem_size, kernel_map); 757 #else 758 tmp = vm_kmem_size; 759 #endif 760 vmem_init(kmem_arena, "kmem arena", kva_alloc(tmp), tmp, PAGE_SIZE, 761 0, 0); 762 vmem_set_reclaim(kmem_arena, kmem_reclaim); 763 764 #ifdef DEBUG_MEMGUARD 765 /* 766 * Initialize MemGuard if support compiled in. MemGuard is a 767 * replacement allocator used for detecting tamper-after-free 768 * scenarios as they occur. It is only used for debugging. 769 */ 770 memguard_init(kmem_arena); 771 #endif 772 } 773 774 /* 775 * Initialize the kernel memory allocator 776 */ 777 /* ARGSUSED*/ 778 static void 779 mallocinit(void *dummy) 780 { 781 int i; 782 uint8_t indx; 783 784 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF); 785 786 kmeminit(); 787 788 uma_startup2(); 789 790 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal), 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 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) { 798 int size = kmemzones[indx].kz_size; 799 char *name = kmemzones[indx].kz_name; 800 int subzone; 801 802 for (subzone = 0; subzone < numzones; subzone++) { 803 kmemzones[indx].kz_zone[subzone] = 804 uma_zcreate(name, size, 805 #ifdef INVARIANTS 806 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini, 807 #else 808 NULL, NULL, NULL, NULL, 809 #endif 810 UMA_ALIGN_PTR, UMA_ZONE_MALLOC); 811 } 812 for (;i <= size; i+= KMEM_ZBASE) 813 kmemsize[i >> KMEM_ZSHIFT] = indx; 814 815 } 816 } 817 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL); 818 819 void 820 malloc_init(void *data) 821 { 822 struct malloc_type_internal *mtip; 823 struct malloc_type *mtp; 824 825 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init")); 826 827 mtp = data; 828 if (mtp->ks_magic != M_MAGIC) 829 panic("malloc_init: bad malloc type magic"); 830 831 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO); 832 mtp->ks_handle = mtip; 833 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc); 834 835 mtx_lock(&malloc_mtx); 836 mtp->ks_next = kmemstatistics; 837 kmemstatistics = mtp; 838 kmemcount++; 839 mtx_unlock(&malloc_mtx); 840 } 841 842 void 843 malloc_uninit(void *data) 844 { 845 struct malloc_type_internal *mtip; 846 struct malloc_type_stats *mtsp; 847 struct malloc_type *mtp, *temp; 848 uma_slab_t slab; 849 long temp_allocs, temp_bytes; 850 int i; 851 852 mtp = data; 853 KASSERT(mtp->ks_magic == M_MAGIC, 854 ("malloc_uninit: bad malloc type magic")); 855 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL")); 856 857 mtx_lock(&malloc_mtx); 858 mtip = mtp->ks_handle; 859 mtp->ks_handle = NULL; 860 if (mtp != kmemstatistics) { 861 for (temp = kmemstatistics; temp != NULL; 862 temp = temp->ks_next) { 863 if (temp->ks_next == mtp) { 864 temp->ks_next = mtp->ks_next; 865 break; 866 } 867 } 868 KASSERT(temp, 869 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc)); 870 } else 871 kmemstatistics = mtp->ks_next; 872 kmemcount--; 873 mtx_unlock(&malloc_mtx); 874 875 /* 876 * Look for memory leaks. 877 */ 878 temp_allocs = temp_bytes = 0; 879 for (i = 0; i < MAXCPU; i++) { 880 mtsp = &mtip->mti_stats[i]; 881 temp_allocs += mtsp->mts_numallocs; 882 temp_allocs -= mtsp->mts_numfrees; 883 temp_bytes += mtsp->mts_memalloced; 884 temp_bytes -= mtsp->mts_memfreed; 885 } 886 if (temp_allocs > 0 || temp_bytes > 0) { 887 printf("Warning: memory type %s leaked memory on destroy " 888 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc, 889 temp_allocs, temp_bytes); 890 } 891 892 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK)); 893 uma_zfree_arg(mt_zone, mtip, slab); 894 } 895 896 struct malloc_type * 897 malloc_desc2type(const char *desc) 898 { 899 struct malloc_type *mtp; 900 901 mtx_assert(&malloc_mtx, MA_OWNED); 902 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) { 903 if (strcmp(mtp->ks_shortdesc, desc) == 0) 904 return (mtp); 905 } 906 return (NULL); 907 } 908 909 static int 910 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS) 911 { 912 struct malloc_type_stream_header mtsh; 913 struct malloc_type_internal *mtip; 914 struct malloc_type_header mth; 915 struct malloc_type *mtp; 916 int error, i; 917 struct sbuf sbuf; 918 919 error = sysctl_wire_old_buffer(req, 0); 920 if (error != 0) 921 return (error); 922 sbuf_new_for_sysctl(&sbuf, NULL, 128, req); 923 mtx_lock(&malloc_mtx); 924 925 /* 926 * Insert stream header. 927 */ 928 bzero(&mtsh, sizeof(mtsh)); 929 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION; 930 mtsh.mtsh_maxcpus = MAXCPU; 931 mtsh.mtsh_count = kmemcount; 932 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)); 933 934 /* 935 * Insert alternating sequence of type headers and type statistics. 936 */ 937 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) { 938 mtip = (struct malloc_type_internal *)mtp->ks_handle; 939 940 /* 941 * Insert type header. 942 */ 943 bzero(&mth, sizeof(mth)); 944 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME); 945 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth)); 946 947 /* 948 * Insert type statistics for each CPU. 949 */ 950 for (i = 0; i < MAXCPU; i++) { 951 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i], 952 sizeof(mtip->mti_stats[i])); 953 } 954 } 955 mtx_unlock(&malloc_mtx); 956 error = sbuf_finish(&sbuf); 957 sbuf_delete(&sbuf); 958 return (error); 959 } 960 961 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT, 962 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats", 963 "Return malloc types"); 964 965 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0, 966 "Count of kernel malloc types"); 967 968 void 969 malloc_type_list(malloc_type_list_func_t *func, void *arg) 970 { 971 struct malloc_type *mtp, **bufmtp; 972 int count, i; 973 size_t buflen; 974 975 mtx_lock(&malloc_mtx); 976 restart: 977 mtx_assert(&malloc_mtx, MA_OWNED); 978 count = kmemcount; 979 mtx_unlock(&malloc_mtx); 980 981 buflen = sizeof(struct malloc_type *) * count; 982 bufmtp = malloc(buflen, M_TEMP, M_WAITOK); 983 984 mtx_lock(&malloc_mtx); 985 986 if (count < kmemcount) { 987 free(bufmtp, M_TEMP); 988 goto restart; 989 } 990 991 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++) 992 bufmtp[i] = mtp; 993 994 mtx_unlock(&malloc_mtx); 995 996 for (i = 0; i < count; i++) 997 (func)(bufmtp[i], arg); 998 999 free(bufmtp, M_TEMP); 1000 } 1001 1002 #ifdef DDB 1003 DB_SHOW_COMMAND(malloc, db_show_malloc) 1004 { 1005 struct malloc_type_internal *mtip; 1006 struct malloc_type *mtp; 1007 uint64_t allocs, frees; 1008 uint64_t alloced, freed; 1009 int i; 1010 1011 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse", 1012 "Requests"); 1013 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) { 1014 mtip = (struct malloc_type_internal *)mtp->ks_handle; 1015 allocs = 0; 1016 frees = 0; 1017 alloced = 0; 1018 freed = 0; 1019 for (i = 0; i < MAXCPU; i++) { 1020 allocs += mtip->mti_stats[i].mts_numallocs; 1021 frees += mtip->mti_stats[i].mts_numfrees; 1022 alloced += mtip->mti_stats[i].mts_memalloced; 1023 freed += mtip->mti_stats[i].mts_memfreed; 1024 } 1025 db_printf("%18s %12ju %12juK %12ju\n", 1026 mtp->ks_shortdesc, allocs - frees, 1027 (alloced - freed + 1023) / 1024, allocs); 1028 if (db_pager_quit) 1029 break; 1030 } 1031 } 1032 1033 #if MALLOC_DEBUG_MAXZONES > 1 1034 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches) 1035 { 1036 struct malloc_type_internal *mtip; 1037 struct malloc_type *mtp; 1038 u_int subzone; 1039 1040 if (!have_addr) { 1041 db_printf("Usage: show multizone_matches <malloc type/addr>\n"); 1042 return; 1043 } 1044 mtp = (void *)addr; 1045 if (mtp->ks_magic != M_MAGIC) { 1046 db_printf("Magic %lx does not match expected %x\n", 1047 mtp->ks_magic, M_MAGIC); 1048 return; 1049 } 1050 1051 mtip = mtp->ks_handle; 1052 subzone = mtip->mti_zone; 1053 1054 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) { 1055 mtip = mtp->ks_handle; 1056 if (mtip->mti_zone != subzone) 1057 continue; 1058 db_printf("%s\n", mtp->ks_shortdesc); 1059 if (db_pager_quit) 1060 break; 1061 } 1062 } 1063 #endif /* MALLOC_DEBUG_MAXZONES > 1 */ 1064 #endif /* DDB */ 1065 1066 #ifdef MALLOC_PROFILE 1067 1068 static int 1069 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS) 1070 { 1071 struct sbuf sbuf; 1072 uint64_t count; 1073 uint64_t waste; 1074 uint64_t mem; 1075 int error; 1076 int rsize; 1077 int size; 1078 int i; 1079 1080 waste = 0; 1081 mem = 0; 1082 1083 error = sysctl_wire_old_buffer(req, 0); 1084 if (error != 0) 1085 return (error); 1086 sbuf_new_for_sysctl(&sbuf, NULL, 128, req); 1087 sbuf_printf(&sbuf, 1088 "\n Size Requests Real Size\n"); 1089 for (i = 0; i < KMEM_ZSIZE; i++) { 1090 size = i << KMEM_ZSHIFT; 1091 rsize = kmemzones[kmemsize[i]].kz_size; 1092 count = (long long unsigned)krequests[i]; 1093 1094 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size, 1095 (unsigned long long)count, rsize); 1096 1097 if ((rsize * count) > (size * count)) 1098 waste += (rsize * count) - (size * count); 1099 mem += (rsize * count); 1100 } 1101 sbuf_printf(&sbuf, 1102 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n", 1103 (unsigned long long)mem, (unsigned long long)waste); 1104 error = sbuf_finish(&sbuf); 1105 sbuf_delete(&sbuf); 1106 return (error); 1107 } 1108 1109 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD, 1110 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling"); 1111 #endif /* MALLOC_PROFILE */ 1112