kern_malloc.c revision 117391
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 117391 2003-07-11 00:01:03Z silby $"); 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; 424 425#if defined(VM_KMEM_SIZE_SCALE) 426 if ((mem_size / VM_KMEM_SIZE_SCALE) > (vm_kmem_size / PAGE_SIZE)) 427 vm_kmem_size = (mem_size / VM_KMEM_SIZE_SCALE) * PAGE_SIZE; 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) / PAGE_SIZE) > cnt.v_page_count) 445 vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE; 446 447 /* 448 * Tune settings based on the kernel map's size at this time. 449 */ 450 init_param3(vm_kmem_size / PAGE_SIZE); 451 452 /* 453 * In mbuf_init(), we set up submaps for mbufs and clusters, in which 454 * case we rounddown() (nmbufs * MSIZE) and (nmbclusters * MCLBYTES), 455 * respectively. Mathematically, this means that what we do here may 456 * amount to slightly more address space than we need for the submaps, 457 * but it never hurts to have an extra page in kmem_map. 458 */ 459 npg = (nmbufs*MSIZE + nmbclusters*MCLBYTES + vm_kmem_size) / PAGE_SIZE; 460 461 kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase, 462 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE)); 463 kmem_map->system_map = 1; 464 465 uma_startup2(); 466 467 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) { 468 int size = kmemzones[indx].kz_size; 469 char *name = kmemzones[indx].kz_name; 470 471 kmemzones[indx].kz_zone = uma_zcreate(name, size, 472#ifdef INVARIANTS 473 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini, 474#else 475 NULL, NULL, NULL, NULL, 476#endif 477 UMA_ALIGN_PTR, UMA_ZONE_MALLOC); 478 479 for (;i <= size; i+= KMEM_ZBASE) 480 kmemsize[i >> KMEM_ZSHIFT] = indx; 481 482 } 483} 484 485void 486malloc_init(data) 487 void *data; 488{ 489 struct malloc_type *type = (struct malloc_type *)data; 490 491 mtx_lock(&malloc_mtx); 492 if (type->ks_magic != M_MAGIC) 493 panic("malloc type lacks magic"); 494 495 if (cnt.v_page_count == 0) 496 panic("malloc_init not allowed before vm init"); 497 498 if (type->ks_next != NULL) 499 return; 500 501 type->ks_next = kmemstatistics; 502 kmemstatistics = type; 503 mtx_init(&type->ks_mtx, type->ks_shortdesc, "Malloc Stats", MTX_DEF); 504 mtx_unlock(&malloc_mtx); 505} 506 507void 508malloc_uninit(data) 509 void *data; 510{ 511 struct malloc_type *type = (struct malloc_type *)data; 512 struct malloc_type *t; 513 514 mtx_lock(&malloc_mtx); 515 mtx_lock(&type->ks_mtx); 516 if (type->ks_magic != M_MAGIC) 517 panic("malloc type lacks magic"); 518 519 if (cnt.v_page_count == 0) 520 panic("malloc_uninit not allowed before vm init"); 521 522 if (type == kmemstatistics) 523 kmemstatistics = type->ks_next; 524 else { 525 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) { 526 if (t->ks_next == type) { 527 t->ks_next = type->ks_next; 528 break; 529 } 530 } 531 } 532 type->ks_next = NULL; 533 mtx_destroy(&type->ks_mtx); 534 mtx_unlock(&malloc_mtx); 535} 536 537static int 538sysctl_kern_malloc(SYSCTL_HANDLER_ARGS) 539{ 540 struct malloc_type *type; 541 int linesize = 128; 542 int curline; 543 int bufsize; 544 int first; 545 int error; 546 char *buf; 547 char *p; 548 int cnt; 549 int len; 550 int i; 551 552 cnt = 0; 553 554 mtx_lock(&malloc_mtx); 555 for (type = kmemstatistics; type != NULL; type = type->ks_next) 556 cnt++; 557 558 mtx_unlock(&malloc_mtx); 559 bufsize = linesize * (cnt + 1); 560 p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO); 561 mtx_lock(&malloc_mtx); 562 563 len = snprintf(p, linesize, 564 "\n Type InUse MemUse HighUse Requests Size(s)\n"); 565 p += len; 566 567 for (type = kmemstatistics; cnt != 0 && type != NULL; 568 type = type->ks_next, cnt--) { 569 if (type->ks_calls == 0) 570 continue; 571 572 curline = linesize - 2; /* Leave room for the \n */ 573 len = snprintf(p, curline, "%13s%6lu%6luK%7luK%9llu", 574 type->ks_shortdesc, 575 type->ks_inuse, 576 (type->ks_memuse + 1023) / 1024, 577 (type->ks_maxused + 1023) / 1024, 578 (long long unsigned)type->ks_calls); 579 curline -= len; 580 p += len; 581 582 first = 1; 583 for (i = 0; i < sizeof(kmemzones) / sizeof(kmemzones[0]) - 1; 584 i++) { 585 if (type->ks_size & (1 << i)) { 586 if (first) 587 len = snprintf(p, curline, " "); 588 else 589 len = snprintf(p, curline, ","); 590 curline -= len; 591 p += len; 592 593 len = snprintf(p, curline, 594 "%s", kmemzones[i].kz_name); 595 curline -= len; 596 p += len; 597 598 first = 0; 599 } 600 } 601 602 len = snprintf(p, 2, "\n"); 603 p += len; 604 } 605 606 mtx_unlock(&malloc_mtx); 607 error = SYSCTL_OUT(req, buf, p - buf); 608 609 free(buf, M_TEMP); 610 return (error); 611} 612 613SYSCTL_OID(_kern, OID_AUTO, malloc, CTLTYPE_STRING|CTLFLAG_RD, 614 NULL, 0, sysctl_kern_malloc, "A", "Malloc Stats"); 615 616#ifdef MALLOC_PROFILE 617 618static int 619sysctl_kern_mprof(SYSCTL_HANDLER_ARGS) 620{ 621 int linesize = 64; 622 uint64_t count; 623 uint64_t waste; 624 uint64_t mem; 625 int bufsize; 626 int error; 627 char *buf; 628 int rsize; 629 int size; 630 char *p; 631 int len; 632 int i; 633 634 bufsize = linesize * (KMEM_ZSIZE + 1); 635 bufsize += 128; /* For the stats line */ 636 bufsize += 128; /* For the banner line */ 637 waste = 0; 638 mem = 0; 639 640 p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO); 641 len = snprintf(p, bufsize, 642 "\n Size Requests Real Size\n"); 643 bufsize -= len; 644 p += len; 645 646 for (i = 0; i < KMEM_ZSIZE; i++) { 647 size = i << KMEM_ZSHIFT; 648 rsize = kmemzones[kmemsize[i]].kz_size; 649 count = (long long unsigned)krequests[i]; 650 651 len = snprintf(p, bufsize, "%6d%28llu%11d\n", 652 size, (unsigned long long)count, rsize); 653 bufsize -= len; 654 p += len; 655 656 if ((rsize * count) > (size * count)) 657 waste += (rsize * count) - (size * count); 658 mem += (rsize * count); 659 } 660 661 len = snprintf(p, bufsize, 662 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n", 663 (unsigned long long)mem, (unsigned long long)waste); 664 p += len; 665 666 error = SYSCTL_OUT(req, buf, p - buf); 667 668 free(buf, M_TEMP); 669 return (error); 670} 671 672SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD, 673 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling"); 674#endif /* MALLOC_PROFILE */ 675