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