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