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