kern_malloc.c revision 116182
1/* 2 * Copyright (c) 1987, 1991, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. All advertising materials mentioning features or use of this software 14 * must display the following acknowledgement: 15 * This product includes software developed by the University of 16 * California, Berkeley and its contributors. 17 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * @(#)kern_malloc.c 8.3 (Berkeley) 1/4/94 34 */ 35 36#include <sys/cdefs.h> 37__FBSDID("$FreeBSD: head/sys/kern/kern_malloc.c 116182 2003-06-11 00:56:59Z obrien $"); 38 39#include "opt_vm.h" 40 41#include <sys/param.h> 42#include <sys/systm.h> 43#include <sys/kernel.h> 44#include <sys/lock.h> 45#include <sys/malloc.h> 46#include <sys/mbuf.h> 47#include <sys/mutex.h> 48#include <sys/vmmeter.h> 49#include <sys/proc.h> 50#include <sys/sysctl.h> 51#include <sys/time.h> 52 53#include <vm/vm.h> 54#include <vm/pmap.h> 55#include <vm/vm_param.h> 56#include <vm/vm_kern.h> 57#include <vm/vm_extern.h> 58#include <vm/vm_map.h> 59#include <vm/vm_page.h> 60#include <vm/uma.h> 61#include <vm/uma_int.h> 62#include <vm/uma_dbg.h> 63 64#if defined(INVARIANTS) && defined(__i386__) 65#include <machine/cpu.h> 66#endif 67 68/* 69 * When realloc() is called, if the new size is sufficiently smaller than 70 * the old size, realloc() will allocate a new, smaller block to avoid 71 * wasting memory. 'Sufficiently smaller' is defined as: newsize <= 72 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'. 73 */ 74#ifndef REALLOC_FRACTION 75#define REALLOC_FRACTION 1 /* new block if <= half the size */ 76#endif 77 78MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches"); 79MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory"); 80MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers"); 81 82MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options"); 83MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery"); 84 85static void kmeminit(void *); 86SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL) 87 88static MALLOC_DEFINE(M_FREE, "free", "should be on free list"); 89 90static struct malloc_type *kmemstatistics; 91static char *kmembase; 92static char *kmemlimit; 93 94#define KMEM_ZSHIFT 4 95#define KMEM_ZBASE 16 96#define KMEM_ZMASK (KMEM_ZBASE - 1) 97 98#define KMEM_ZMAX 65536 99#define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT) 100static u_int8_t kmemsize[KMEM_ZSIZE + 1]; 101 102/* These won't be powers of two for long */ 103struct { 104 int kz_size; 105 char *kz_name; 106 uma_zone_t kz_zone; 107} kmemzones[] = { 108 {16, "16", NULL}, 109 {32, "32", NULL}, 110 {64, "64", NULL}, 111 {128, "128", NULL}, 112 {256, "256", NULL}, 113 {512, "512", NULL}, 114 {1024, "1024", NULL}, 115 {2048, "2048", NULL}, 116 {4096, "4096", NULL}, 117 {8192, "8192", NULL}, 118 {16384, "16384", NULL}, 119 {32768, "32768", NULL}, 120 {65536, "65536", NULL}, 121 {0, NULL}, 122}; 123 124u_int vm_kmem_size; 125 126/* 127 * The malloc_mtx protects the kmemstatistics linked list. 128 */ 129 130struct mtx malloc_mtx; 131 132#ifdef MALLOC_PROFILE 133uint64_t krequests[KMEM_ZSIZE + 1]; 134 135static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS); 136#endif 137 138static int sysctl_kern_malloc(SYSCTL_HANDLER_ARGS); 139 140/* time_uptime of last malloc(9) failure */ 141static time_t t_malloc_fail; 142 143#ifdef MALLOC_MAKE_FAILURES 144/* 145 * Causes malloc failures every (n) mallocs with M_NOWAIT. If set to 0, 146 * doesn't cause failures. 147 */ 148SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0, 149 "Kernel malloc debugging options"); 150 151static int malloc_failure_rate; 152static int malloc_nowait_count; 153static int malloc_failure_count; 154SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW, 155 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail"); 156TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate); 157SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD, 158 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures"); 159#endif 160 161int 162malloc_last_fail(void) 163{ 164 165 return (time_uptime - t_malloc_fail); 166} 167 168/* 169 * malloc: 170 * 171 * Allocate a block of memory. 172 * 173 * If M_NOWAIT is set, this routine will not block and return NULL if 174 * the allocation fails. 175 */ 176void * 177malloc(size, type, flags) 178 unsigned long size; 179 struct malloc_type *type; 180 int flags; 181{ 182 int indx; 183 caddr_t va; 184 uma_zone_t zone; 185#ifdef DIAGNOSTIC 186 unsigned long osize = size; 187#endif 188 register struct malloc_type *ksp = type; 189 190#ifdef INVARIANTS 191 /* 192 * To make sure that WAITOK or NOWAIT is set, but not more than 193 * one, and check against the API botches that are common. 194 */ 195 indx = flags & (M_WAITOK | M_NOWAIT | M_DONTWAIT | M_TRYWAIT); 196 if (indx != M_NOWAIT && indx != M_WAITOK) { 197 static struct timeval lasterr; 198 static int curerr, once; 199 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) { 200 printf("Bad malloc flags: %x\n", indx); 201 backtrace(); 202 flags |= M_WAITOK; 203 once++; 204 } 205 } 206#endif 207#if 0 208 if (size == 0) 209 Debugger("zero size malloc"); 210#endif 211#ifdef MALLOC_MAKE_FAILURES 212 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) { 213 atomic_add_int(&malloc_nowait_count, 1); 214 if ((malloc_nowait_count % malloc_failure_rate) == 0) { 215 atomic_add_int(&malloc_failure_count, 1); 216 t_malloc_fail = time_uptime; 217 return (NULL); 218 } 219 } 220#endif 221 if (flags & M_WAITOK) 222 KASSERT(curthread->td_intr_nesting_level == 0, 223 ("malloc(M_WAITOK) in interrupt context")); 224 if (size <= KMEM_ZMAX) { 225 if (size & KMEM_ZMASK) 226 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE; 227 indx = kmemsize[size >> KMEM_ZSHIFT]; 228 zone = kmemzones[indx].kz_zone; 229#ifdef MALLOC_PROFILE 230 krequests[size >> KMEM_ZSHIFT]++; 231#endif 232 va = uma_zalloc(zone, flags); 233 mtx_lock(&ksp->ks_mtx); 234 if (va == NULL) 235 goto out; 236 237 ksp->ks_size |= 1 << indx; 238 size = zone->uz_size; 239 } else { 240 size = roundup(size, PAGE_SIZE); 241 zone = NULL; 242 va = uma_large_malloc(size, flags); 243 mtx_lock(&ksp->ks_mtx); 244 if (va == NULL) 245 goto out; 246 } 247 ksp->ks_memuse += size; 248 ksp->ks_inuse++; 249out: 250 ksp->ks_calls++; 251 if (ksp->ks_memuse > ksp->ks_maxused) 252 ksp->ks_maxused = ksp->ks_memuse; 253 254 mtx_unlock(&ksp->ks_mtx); 255 if (flags & M_WAITOK) 256 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL")); 257 else if (va == NULL) 258 t_malloc_fail = time_uptime; 259#ifdef DIAGNOSTIC 260 if (va != NULL && !(flags & M_ZERO)) { 261 memset(va, 0x70, osize); 262 } 263#endif 264 return ((void *) va); 265} 266 267/* 268 * free: 269 * 270 * Free a block of memory allocated by malloc. 271 * 272 * This routine may not block. 273 */ 274void 275free(addr, type) 276 void *addr; 277 struct malloc_type *type; 278{ 279 register struct malloc_type *ksp = type; 280 uma_slab_t slab; 281 u_long size; 282 283 /* free(NULL, ...) does nothing */ 284 if (addr == NULL) 285 return; 286 287 KASSERT(ksp->ks_memuse > 0, 288 ("malloc(9)/free(9) confusion.\n%s", 289 "Probably freeing with wrong type, but maybe not here.")); 290 size = 0; 291 292 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK)); 293 294 if (slab == NULL) 295 panic("free: address %p(%p) has not been allocated.\n", 296 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK))); 297 298 299 if (!(slab->us_flags & UMA_SLAB_MALLOC)) { 300#ifdef INVARIANTS 301 struct malloc_type **mtp = addr; 302#endif 303 size = slab->us_zone->uz_size; 304#ifdef INVARIANTS 305 /* 306 * Cache a pointer to the malloc_type that most recently freed 307 * this memory here. This way we know who is most likely to 308 * have stepped on it later. 309 * 310 * This code assumes that size is a multiple of 8 bytes for 311 * 64 bit machines 312 */ 313 mtp = (struct malloc_type **) 314 ((unsigned long)mtp & ~UMA_ALIGN_PTR); 315 mtp += (size - sizeof(struct malloc_type *)) / 316 sizeof(struct malloc_type *); 317 *mtp = type; 318#endif 319 uma_zfree_arg(slab->us_zone, addr, slab); 320 } else { 321 size = slab->us_size; 322 uma_large_free(slab); 323 } 324 mtx_lock(&ksp->ks_mtx); 325 KASSERT(size <= ksp->ks_memuse, 326 ("malloc(9)/free(9) confusion.\n%s", 327 "Probably freeing with wrong type, but maybe not here.")); 328 ksp->ks_memuse -= size; 329 ksp->ks_inuse--; 330 mtx_unlock(&ksp->ks_mtx); 331} 332 333/* 334 * realloc: change the size of a memory block 335 */ 336void * 337realloc(addr, size, type, flags) 338 void *addr; 339 unsigned long size; 340 struct malloc_type *type; 341 int flags; 342{ 343 uma_slab_t slab; 344 unsigned long alloc; 345 void *newaddr; 346 347 /* realloc(NULL, ...) is equivalent to malloc(...) */ 348 if (addr == NULL) 349 return (malloc(size, type, flags)); 350 351 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK)); 352 353 /* Sanity check */ 354 KASSERT(slab != NULL, 355 ("realloc: address %p out of range", (void *)addr)); 356 357 /* Get the size of the original block */ 358 if (slab->us_zone) 359 alloc = slab->us_zone->uz_size; 360 else 361 alloc = slab->us_size; 362 363 /* Reuse the original block if appropriate */ 364 if (size <= alloc 365 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE)) 366 return (addr); 367 368 /* Allocate a new, bigger (or smaller) block */ 369 if ((newaddr = malloc(size, type, flags)) == NULL) 370 return (NULL); 371 372 /* Copy over original contents */ 373 bcopy(addr, newaddr, min(size, alloc)); 374 free(addr, type); 375 return (newaddr); 376} 377 378/* 379 * reallocf: same as realloc() but free memory on failure. 380 */ 381void * 382reallocf(addr, size, type, flags) 383 void *addr; 384 unsigned long size; 385 struct malloc_type *type; 386 int flags; 387{ 388 void *mem; 389 390 if ((mem = realloc(addr, size, type, flags)) == NULL) 391 free(addr, type); 392 return (mem); 393} 394 395/* 396 * Initialize the kernel memory allocator 397 */ 398/* ARGSUSED*/ 399static void 400kmeminit(dummy) 401 void *dummy; 402{ 403 u_int8_t indx; 404 u_long npg; 405 u_long mem_size; 406 int i; 407 408 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF); 409 410 /* 411 * Try to auto-tune the kernel memory size, so that it is 412 * more applicable for a wider range of machine sizes. 413 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while 414 * a VM_KMEM_SIZE of 12MB is a fair compromise. The 415 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space 416 * available, and on an X86 with a total KVA space of 256MB, 417 * try to keep VM_KMEM_SIZE_MAX at 80MB or below. 418 * 419 * Note that the kmem_map is also used by the zone allocator, 420 * so make sure that there is enough space. 421 */ 422 vm_kmem_size = VM_KMEM_SIZE; 423 mem_size = cnt.v_page_count * PAGE_SIZE; 424 425#if defined(VM_KMEM_SIZE_SCALE) 426 if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size) 427 vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE; 428#endif 429 430#if defined(VM_KMEM_SIZE_MAX) 431 if (vm_kmem_size >= VM_KMEM_SIZE_MAX) 432 vm_kmem_size = VM_KMEM_SIZE_MAX; 433#endif 434 435 /* Allow final override from the kernel environment */ 436 TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size); 437 438 /* 439 * Limit kmem virtual size to twice the physical memory. 440 * This allows for kmem map sparseness, but limits the size 441 * to something sane. Be careful to not overflow the 32bit 442 * ints while doing the check. 443 */ 444 if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE)) 445 vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE; 446 447 /* 448 * In mbuf_init(), we set up submaps for mbufs and clusters, in which 449 * case we rounddown() (nmbufs * MSIZE) and (nmbclusters * MCLBYTES), 450 * respectively. Mathematically, this means that what we do here may 451 * amount to slightly more address space than we need for the submaps, 452 * but it never hurts to have an extra page in kmem_map. 453 */ 454 npg = (nmbufs*MSIZE + nmbclusters*MCLBYTES + vm_kmem_size) / PAGE_SIZE; 455 456 kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase, 457 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE)); 458 kmem_map->system_map = 1; 459 460 uma_startup2(); 461 462 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) { 463 int size = kmemzones[indx].kz_size; 464 char *name = kmemzones[indx].kz_name; 465 466 kmemzones[indx].kz_zone = uma_zcreate(name, size, 467#ifdef INVARIANTS 468 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini, 469#else 470 NULL, NULL, NULL, NULL, 471#endif 472 UMA_ALIGN_PTR, UMA_ZONE_MALLOC); 473 474 for (;i <= size; i+= KMEM_ZBASE) 475 kmemsize[i >> KMEM_ZSHIFT] = indx; 476 477 } 478} 479 480void 481malloc_init(data) 482 void *data; 483{ 484 struct malloc_type *type = (struct malloc_type *)data; 485 486 mtx_lock(&malloc_mtx); 487 if (type->ks_magic != M_MAGIC) 488 panic("malloc type lacks magic"); 489 490 if (cnt.v_page_count == 0) 491 panic("malloc_init not allowed before vm init"); 492 493 if (type->ks_next != NULL) 494 return; 495 496 type->ks_next = kmemstatistics; 497 kmemstatistics = type; 498 mtx_init(&type->ks_mtx, type->ks_shortdesc, "Malloc Stats", MTX_DEF); 499 mtx_unlock(&malloc_mtx); 500} 501 502void 503malloc_uninit(data) 504 void *data; 505{ 506 struct malloc_type *type = (struct malloc_type *)data; 507 struct malloc_type *t; 508 509 mtx_lock(&malloc_mtx); 510 mtx_lock(&type->ks_mtx); 511 if (type->ks_magic != M_MAGIC) 512 panic("malloc type lacks magic"); 513 514 if (cnt.v_page_count == 0) 515 panic("malloc_uninit not allowed before vm init"); 516 517 if (type == kmemstatistics) 518 kmemstatistics = type->ks_next; 519 else { 520 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) { 521 if (t->ks_next == type) { 522 t->ks_next = type->ks_next; 523 break; 524 } 525 } 526 } 527 type->ks_next = NULL; 528 mtx_destroy(&type->ks_mtx); 529 mtx_unlock(&malloc_mtx); 530} 531 532static int 533sysctl_kern_malloc(SYSCTL_HANDLER_ARGS) 534{ 535 struct malloc_type *type; 536 int linesize = 128; 537 int curline; 538 int bufsize; 539 int first; 540 int error; 541 char *buf; 542 char *p; 543 int cnt; 544 int len; 545 int i; 546 547 cnt = 0; 548 549 mtx_lock(&malloc_mtx); 550 for (type = kmemstatistics; type != NULL; type = type->ks_next) 551 cnt++; 552 553 mtx_unlock(&malloc_mtx); 554 bufsize = linesize * (cnt + 1); 555 p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO); 556 mtx_lock(&malloc_mtx); 557 558 len = snprintf(p, linesize, 559 "\n Type InUse MemUse HighUse Requests Size(s)\n"); 560 p += len; 561 562 for (type = kmemstatistics; cnt != 0 && type != NULL; 563 type = type->ks_next, cnt--) { 564 if (type->ks_calls == 0) 565 continue; 566 567 curline = linesize - 2; /* Leave room for the \n */ 568 len = snprintf(p, curline, "%13s%6lu%6luK%7luK%9llu", 569 type->ks_shortdesc, 570 type->ks_inuse, 571 (type->ks_memuse + 1023) / 1024, 572 (type->ks_maxused + 1023) / 1024, 573 (long long unsigned)type->ks_calls); 574 curline -= len; 575 p += len; 576 577 first = 1; 578 for (i = 0; i < sizeof(kmemzones) / sizeof(kmemzones[0]) - 1; 579 i++) { 580 if (type->ks_size & (1 << i)) { 581 if (first) 582 len = snprintf(p, curline, " "); 583 else 584 len = snprintf(p, curline, ","); 585 curline -= len; 586 p += len; 587 588 len = snprintf(p, curline, 589 "%s", kmemzones[i].kz_name); 590 curline -= len; 591 p += len; 592 593 first = 0; 594 } 595 } 596 597 len = snprintf(p, 2, "\n"); 598 p += len; 599 } 600 601 mtx_unlock(&malloc_mtx); 602 error = SYSCTL_OUT(req, buf, p - buf); 603 604 free(buf, M_TEMP); 605 return (error); 606} 607 608SYSCTL_OID(_kern, OID_AUTO, malloc, CTLTYPE_STRING|CTLFLAG_RD, 609 NULL, 0, sysctl_kern_malloc, "A", "Malloc Stats"); 610 611#ifdef MALLOC_PROFILE 612 613static int 614sysctl_kern_mprof(SYSCTL_HANDLER_ARGS) 615{ 616 int linesize = 64; 617 uint64_t count; 618 uint64_t waste; 619 uint64_t mem; 620 int bufsize; 621 int error; 622 char *buf; 623 int rsize; 624 int size; 625 char *p; 626 int len; 627 int i; 628 629 bufsize = linesize * (KMEM_ZSIZE + 1); 630 bufsize += 128; /* For the stats line */ 631 bufsize += 128; /* For the banner line */ 632 waste = 0; 633 mem = 0; 634 635 p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO); 636 len = snprintf(p, bufsize, 637 "\n Size Requests Real Size\n"); 638 bufsize -= len; 639 p += len; 640 641 for (i = 0; i < KMEM_ZSIZE; i++) { 642 size = i << KMEM_ZSHIFT; 643 rsize = kmemzones[kmemsize[i]].kz_size; 644 count = (long long unsigned)krequests[i]; 645 646 len = snprintf(p, bufsize, "%6d%28llu%11d\n", 647 size, (unsigned long long)count, rsize); 648 bufsize -= len; 649 p += len; 650 651 if ((rsize * count) > (size * count)) 652 waste += (rsize * count) - (size * count); 653 mem += (rsize * count); 654 } 655 656 len = snprintf(p, bufsize, 657 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n", 658 (unsigned long long)mem, (unsigned long long)waste); 659 p += len; 660 661 error = SYSCTL_OUT(req, buf, p - buf); 662 663 free(buf, M_TEMP); 664 return (error); 665} 666 667SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD, 668 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling"); 669#endif /* MALLOC_PROFILE */ 670