1 /* $NetBSD: kern_malloc.c,v 1.120 2008/09/25 16:23:45 pooka Exp $ */ 2 3 /* 4 * Copyright (c) 1987, 1991, 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the University nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 * 31 * @(#)kern_malloc.c 8.4 (Berkeley) 5/20/95 32 */ 33 34 /* 35 * Copyright (c) 1996 Christopher G. Demetriou. All rights reserved. 36 * 37 * Redistribution and use in source and binary forms, with or without 38 * modification, are permitted provided that the following conditions 39 * are met: 40 * 1. Redistributions of source code must retain the above copyright 41 * notice, this list of conditions and the following disclaimer. 42 * 2. Redistributions in binary form must reproduce the above copyright 43 * notice, this list of conditions and the following disclaimer in the 44 * documentation and/or other materials provided with the distribution. 45 * 3. All advertising materials mentioning features or use of this software 46 * must display the following acknowledgement: 47 * This product includes software developed by the University of 48 * California, Berkeley and its contributors. 49 * 4. Neither the name of the University nor the names of its contributors 50 * may be used to endorse or promote products derived from this software 51 * without specific prior written permission. 52 * 53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 63 * SUCH DAMAGE. 64 * 65 * @(#)kern_malloc.c 8.4 (Berkeley) 5/20/95 66 */ 67 68 #include <sys/cdefs.h> 69 __KERNEL_RCSID(0, "$NetBSD: kern_malloc.c,v 1.120 2008/09/25 16:23:45 pooka Exp $"); 70 71 #include <sys/param.h> 72 #include <sys/proc.h> 73 #include <sys/kernel.h> 74 #include <sys/malloc.h> 75 #include <sys/systm.h> 76 #include <sys/debug.h> 77 #include <sys/mutex.h> 78 #include <sys/lockdebug.h> 79 80 #include <uvm/uvm_extern.h> 81 82 static struct vm_map_kernel kmem_map_store; 83 struct vm_map *kmem_map = NULL; 84 85 #include "opt_kmempages.h" 86 87 #ifdef NKMEMCLUSTERS 88 #error NKMEMCLUSTERS is obsolete; remove it from your kernel config file and use NKMEMPAGES instead or let the kernel auto-size 89 #endif 90 91 /* 92 * Default number of pages in kmem_map. We attempt to calculate this 93 * at run-time, but allow it to be either patched or set in the kernel 94 * config file. 95 */ 96 #ifndef NKMEMPAGES 97 #define NKMEMPAGES 0 98 #endif 99 int nkmempages = NKMEMPAGES; 100 101 /* 102 * Defaults for lower- and upper-bounds for the kmem_map page count. 103 * Can be overridden by kernel config options. 104 */ 105 #ifndef NKMEMPAGES_MIN 106 #define NKMEMPAGES_MIN NKMEMPAGES_MIN_DEFAULT 107 #endif 108 109 #ifndef NKMEMPAGES_MAX 110 #define NKMEMPAGES_MAX NKMEMPAGES_MAX_DEFAULT 111 #endif 112 113 #include "opt_kmemstats.h" 114 #include "opt_malloclog.h" 115 #include "opt_malloc_debug.h" 116 117 #define MINALLOCSIZE (1 << MINBUCKET) 118 #define BUCKETINDX(size) \ 119 ((size) <= (MINALLOCSIZE * 128) \ 120 ? (size) <= (MINALLOCSIZE * 8) \ 121 ? (size) <= (MINALLOCSIZE * 2) \ 122 ? (size) <= (MINALLOCSIZE * 1) \ 123 ? (MINBUCKET + 0) \ 124 : (MINBUCKET + 1) \ 125 : (size) <= (MINALLOCSIZE * 4) \ 126 ? (MINBUCKET + 2) \ 127 : (MINBUCKET + 3) \ 128 : (size) <= (MINALLOCSIZE* 32) \ 129 ? (size) <= (MINALLOCSIZE * 16) \ 130 ? (MINBUCKET + 4) \ 131 : (MINBUCKET + 5) \ 132 : (size) <= (MINALLOCSIZE * 64) \ 133 ? (MINBUCKET + 6) \ 134 : (MINBUCKET + 7) \ 135 : (size) <= (MINALLOCSIZE * 2048) \ 136 ? (size) <= (MINALLOCSIZE * 512) \ 137 ? (size) <= (MINALLOCSIZE * 256) \ 138 ? (MINBUCKET + 8) \ 139 : (MINBUCKET + 9) \ 140 : (size) <= (MINALLOCSIZE * 1024) \ 141 ? (MINBUCKET + 10) \ 142 : (MINBUCKET + 11) \ 143 : (size) <= (MINALLOCSIZE * 8192) \ 144 ? (size) <= (MINALLOCSIZE * 4096) \ 145 ? (MINBUCKET + 12) \ 146 : (MINBUCKET + 13) \ 147 : (size) <= (MINALLOCSIZE * 16384) \ 148 ? (MINBUCKET + 14) \ 149 : (MINBUCKET + 15)) 150 151 /* 152 * Array of descriptors that describe the contents of each page 153 */ 154 struct kmemusage { 155 short ku_indx; /* bucket index */ 156 union { 157 u_short freecnt;/* for small allocations, free pieces in page */ 158 u_short pagecnt;/* for large allocations, pages alloced */ 159 } ku_un; 160 }; 161 #define ku_freecnt ku_un.freecnt 162 #define ku_pagecnt ku_un.pagecnt 163 164 struct kmembuckets kmembuckets[MINBUCKET + 16]; 165 struct kmemusage *kmemusage; 166 char *kmembase, *kmemlimit; 167 168 #ifdef DEBUG 169 static void *malloc_freecheck; 170 #endif 171 172 /* 173 * Turn virtual addresses into kmem map indicies 174 */ 175 #define btokup(addr) (&kmemusage[((char *)(addr) - kmembase) >> PGSHIFT]) 176 177 struct malloc_type *kmemstatistics; 178 179 #ifdef MALLOCLOG 180 #ifndef MALLOCLOGSIZE 181 #define MALLOCLOGSIZE 100000 182 #endif 183 184 struct malloclog { 185 void *addr; 186 long size; 187 struct malloc_type *type; 188 int action; 189 const char *file; 190 long line; 191 } malloclog[MALLOCLOGSIZE]; 192 193 long malloclogptr; 194 195 static void 196 domlog(void *a, long size, struct malloc_type *type, int action, 197 const char *file, long line) 198 { 199 200 malloclog[malloclogptr].addr = a; 201 malloclog[malloclogptr].size = size; 202 malloclog[malloclogptr].type = type; 203 malloclog[malloclogptr].action = action; 204 malloclog[malloclogptr].file = file; 205 malloclog[malloclogptr].line = line; 206 malloclogptr++; 207 if (malloclogptr >= MALLOCLOGSIZE) 208 malloclogptr = 0; 209 } 210 211 static void 212 hitmlog(void *a) 213 { 214 struct malloclog *lp; 215 long l; 216 217 #define PRT do { \ 218 lp = &malloclog[l]; \ 219 if (lp->addr == a && lp->action) { \ 220 printf("malloc log entry %ld:\n", l); \ 221 printf("\taddr = %p\n", lp->addr); \ 222 printf("\tsize = %ld\n", lp->size); \ 223 printf("\ttype = %s\n", lp->type->ks_shortdesc); \ 224 printf("\taction = %s\n", lp->action == 1 ? "alloc" : "free"); \ 225 printf("\tfile = %s\n", lp->file); \ 226 printf("\tline = %ld\n", lp->line); \ 227 } \ 228 } while (/* CONSTCOND */0) 229 230 for (l = malloclogptr; l < MALLOCLOGSIZE; l++) 231 PRT; 232 233 for (l = 0; l < malloclogptr; l++) 234 PRT; 235 #undef PRT 236 } 237 #endif /* MALLOCLOG */ 238 239 #ifdef DIAGNOSTIC 240 /* 241 * This structure provides a set of masks to catch unaligned frees. 242 */ 243 const long addrmask[] = { 0, 244 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 245 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 246 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 247 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff, 248 }; 249 250 /* 251 * The WEIRD_ADDR is used as known text to copy into free objects so 252 * that modifications after frees can be detected. 253 */ 254 #define WEIRD_ADDR ((uint32_t) 0xdeadbeef) 255 #ifdef DEBUG 256 #define MAX_COPY PAGE_SIZE 257 #else 258 #define MAX_COPY 32 259 #endif 260 261 /* 262 * Normally the freelist structure is used only to hold the list pointer 263 * for free objects. However, when running with diagnostics, the first 264 * 8/16 bytes of the structure is unused except for diagnostic information, 265 * and the free list pointer is at offset 8/16 in the structure. Since the 266 * first 8 bytes is the portion of the structure most often modified, this 267 * helps to detect memory reuse problems and avoid free list corruption. 268 */ 269 struct freelist { 270 uint32_t spare0; 271 #ifdef _LP64 272 uint32_t spare1; /* explicit padding */ 273 #endif 274 struct malloc_type *type; 275 void * next; 276 }; 277 #else /* !DIAGNOSTIC */ 278 struct freelist { 279 void * next; 280 }; 281 #endif /* DIAGNOSTIC */ 282 283 kmutex_t malloc_lock; 284 285 /* 286 * Allocate a block of memory 287 */ 288 #ifdef MALLOCLOG 289 void * 290 _malloc(unsigned long size, struct malloc_type *ksp, int flags, 291 const char *file, long line) 292 #else 293 void * 294 malloc(unsigned long size, struct malloc_type *ksp, int flags) 295 #endif /* MALLOCLOG */ 296 { 297 struct kmembuckets *kbp; 298 struct kmemusage *kup; 299 struct freelist *freep; 300 long indx, npg, allocsize; 301 char *va, *cp, *savedlist; 302 #ifdef DIAGNOSTIC 303 uint32_t *end, *lp; 304 int copysize; 305 #endif 306 307 #ifdef LOCKDEBUG 308 if ((flags & M_NOWAIT) == 0) { 309 ASSERT_SLEEPABLE(); 310 } 311 #endif 312 #ifdef MALLOC_DEBUG 313 if (debug_malloc(size, ksp, flags, (void *) &va)) { 314 if (va != 0) 315 FREECHECK_OUT(&malloc_freecheck, (void *)va); 316 return ((void *) va); 317 } 318 #endif 319 indx = BUCKETINDX(size); 320 kbp = &kmembuckets[indx]; 321 mutex_spin_enter(&malloc_lock); 322 #ifdef KMEMSTATS 323 while (ksp->ks_memuse >= ksp->ks_limit) { 324 if (flags & M_NOWAIT) { 325 mutex_spin_exit(&malloc_lock); 326 return ((void *) NULL); 327 } 328 if (ksp->ks_limblocks < 65535) 329 ksp->ks_limblocks++; 330 mtsleep((void *)ksp, PSWP+2, ksp->ks_shortdesc, 0, 331 &malloc_lock); 332 } 333 ksp->ks_size |= 1 << indx; 334 #endif 335 #ifdef DIAGNOSTIC 336 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY; 337 #endif 338 if (kbp->kb_next == NULL) { 339 int s; 340 kbp->kb_last = NULL; 341 if (size > MAXALLOCSAVE) 342 allocsize = round_page(size); 343 else 344 allocsize = 1 << indx; 345 npg = btoc(allocsize); 346 mutex_spin_exit(&malloc_lock); 347 s = splvm(); 348 va = (void *) uvm_km_alloc(kmem_map, 349 (vsize_t)ctob(npg), 0, 350 ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) | 351 ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 0) | 352 UVM_KMF_WIRED); 353 splx(s); 354 if (__predict_false(va == NULL)) { 355 /* 356 * Kmem_malloc() can return NULL, even if it can 357 * wait, if there is no map space available, because 358 * it can't fix that problem. Neither can we, 359 * right now. (We should release pages which 360 * are completely free and which are in kmembuckets 361 * with too many free elements.) 362 */ 363 if ((flags & (M_NOWAIT|M_CANFAIL)) == 0) 364 panic("malloc: out of space in kmem_map"); 365 return (NULL); 366 } 367 mutex_spin_enter(&malloc_lock); 368 #ifdef KMEMSTATS 369 kbp->kb_total += kbp->kb_elmpercl; 370 #endif 371 kup = btokup(va); 372 kup->ku_indx = indx; 373 if (allocsize > MAXALLOCSAVE) { 374 if (npg > 65535) 375 panic("malloc: allocation too large"); 376 kup->ku_pagecnt = npg; 377 #ifdef KMEMSTATS 378 ksp->ks_memuse += allocsize; 379 #endif 380 goto out; 381 } 382 #ifdef KMEMSTATS 383 kup->ku_freecnt = kbp->kb_elmpercl; 384 kbp->kb_totalfree += kbp->kb_elmpercl; 385 #endif 386 /* 387 * Just in case we blocked while allocating memory, 388 * and someone else also allocated memory for this 389 * kmembucket, don't assume the list is still empty. 390 */ 391 savedlist = kbp->kb_next; 392 kbp->kb_next = cp = va + (npg << PAGE_SHIFT) - allocsize; 393 for (;;) { 394 freep = (struct freelist *)cp; 395 #ifdef DIAGNOSTIC 396 /* 397 * Copy in known text to detect modification 398 * after freeing. 399 */ 400 end = (uint32_t *)&cp[copysize]; 401 for (lp = (uint32_t *)cp; lp < end; lp++) 402 *lp = WEIRD_ADDR; 403 freep->type = M_FREE; 404 #endif /* DIAGNOSTIC */ 405 if (cp <= va) 406 break; 407 cp -= allocsize; 408 freep->next = cp; 409 } 410 freep->next = savedlist; 411 if (savedlist == NULL) 412 kbp->kb_last = (void *)freep; 413 } 414 va = kbp->kb_next; 415 kbp->kb_next = ((struct freelist *)va)->next; 416 #ifdef DIAGNOSTIC 417 freep = (struct freelist *)va; 418 /* XXX potential to get garbage pointer here. */ 419 if (kbp->kb_next) { 420 int rv; 421 vaddr_t addr = (vaddr_t)kbp->kb_next; 422 423 vm_map_lock(kmem_map); 424 rv = uvm_map_checkprot(kmem_map, addr, 425 addr + sizeof(struct freelist), VM_PROT_WRITE); 426 vm_map_unlock(kmem_map); 427 428 if (__predict_false(rv == 0)) { 429 printf("Data modified on freelist: " 430 "word %ld of object %p size %ld previous type %s " 431 "(invalid addr %p)\n", 432 (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp), 433 va, size, "foo", kbp->kb_next); 434 #ifdef MALLOCLOG 435 hitmlog(va); 436 #endif 437 kbp->kb_next = NULL; 438 } 439 } 440 441 /* Fill the fields that we've used with WEIRD_ADDR */ 442 #ifdef _LP64 443 freep->type = (struct malloc_type *) 444 (WEIRD_ADDR | (((u_long) WEIRD_ADDR) << 32)); 445 #else 446 freep->type = (struct malloc_type *) WEIRD_ADDR; 447 #endif 448 end = (uint32_t *)&freep->next + 449 (sizeof(freep->next) / sizeof(int32_t)); 450 for (lp = (uint32_t *)&freep->next; lp < end; lp++) 451 *lp = WEIRD_ADDR; 452 453 /* and check that the data hasn't been modified. */ 454 end = (uint32_t *)&va[copysize]; 455 for (lp = (uint32_t *)va; lp < end; lp++) { 456 if (__predict_true(*lp == WEIRD_ADDR)) 457 continue; 458 printf("Data modified on freelist: " 459 "word %ld of object %p size %ld previous type %s " 460 "(0x%x != 0x%x)\n", 461 (long)(lp - (uint32_t *)va), va, size, 462 "bar", *lp, WEIRD_ADDR); 463 #ifdef MALLOCLOG 464 hitmlog(va); 465 #endif 466 break; 467 } 468 469 freep->spare0 = 0; 470 #endif /* DIAGNOSTIC */ 471 #ifdef KMEMSTATS 472 kup = btokup(va); 473 if (kup->ku_indx != indx) 474 panic("malloc: wrong bucket"); 475 if (kup->ku_freecnt == 0) 476 panic("malloc: lost data"); 477 kup->ku_freecnt--; 478 kbp->kb_totalfree--; 479 ksp->ks_memuse += 1 << indx; 480 out: 481 kbp->kb_calls++; 482 ksp->ks_inuse++; 483 ksp->ks_calls++; 484 if (ksp->ks_memuse > ksp->ks_maxused) 485 ksp->ks_maxused = ksp->ks_memuse; 486 #else 487 out: 488 #endif 489 #ifdef MALLOCLOG 490 domlog(va, size, ksp, 1, file, line); 491 #endif 492 mutex_spin_exit(&malloc_lock); 493 if ((flags & M_ZERO) != 0) 494 memset(va, 0, size); 495 FREECHECK_OUT(&malloc_freecheck, (void *)va); 496 return ((void *) va); 497 } 498 499 /* 500 * Free a block of memory allocated by malloc. 501 */ 502 #ifdef MALLOCLOG 503 void 504 _free(void *addr, struct malloc_type *ksp, const char *file, long line) 505 #else 506 void 507 free(void *addr, struct malloc_type *ksp) 508 #endif /* MALLOCLOG */ 509 { 510 struct kmembuckets *kbp; 511 struct kmemusage *kup; 512 struct freelist *freep; 513 long size; 514 #ifdef DIAGNOSTIC 515 void *cp; 516 int32_t *end, *lp; 517 long alloc, copysize; 518 #endif 519 520 FREECHECK_IN(&malloc_freecheck, addr); 521 #ifdef MALLOC_DEBUG 522 if (debug_free(addr, ksp)) 523 return; 524 #endif 525 526 #ifdef DIAGNOSTIC 527 /* 528 * Ensure that we're free'ing something that we could 529 * have allocated in the first place. That is, check 530 * to see that the address is within kmem_map. 531 */ 532 if (__predict_false((vaddr_t)addr < vm_map_min(kmem_map) || 533 (vaddr_t)addr >= vm_map_max(kmem_map))) 534 panic("free: addr %p not within kmem_map", addr); 535 #endif 536 537 kup = btokup(addr); 538 size = 1 << kup->ku_indx; 539 kbp = &kmembuckets[kup->ku_indx]; 540 541 LOCKDEBUG_MEM_CHECK(addr, 542 size <= MAXALLOCSAVE ? size : ctob(kup->ku_pagecnt)); 543 544 mutex_spin_enter(&malloc_lock); 545 #ifdef MALLOCLOG 546 domlog(addr, 0, ksp, 2, file, line); 547 #endif 548 #ifdef DIAGNOSTIC 549 /* 550 * Check for returns of data that do not point to the 551 * beginning of the allocation. 552 */ 553 if (size > PAGE_SIZE) 554 alloc = addrmask[BUCKETINDX(PAGE_SIZE)]; 555 else 556 alloc = addrmask[kup->ku_indx]; 557 if (((u_long)addr & alloc) != 0) 558 panic("free: unaligned addr %p, size %ld, type %s, mask %ld", 559 addr, size, ksp->ks_shortdesc, alloc); 560 #endif /* DIAGNOSTIC */ 561 if (size > MAXALLOCSAVE) { 562 uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt), 563 UVM_KMF_WIRED); 564 #ifdef KMEMSTATS 565 size = kup->ku_pagecnt << PGSHIFT; 566 ksp->ks_memuse -= size; 567 kup->ku_indx = 0; 568 kup->ku_pagecnt = 0; 569 if (ksp->ks_memuse + size >= ksp->ks_limit && 570 ksp->ks_memuse < ksp->ks_limit) 571 wakeup((void *)ksp); 572 #ifdef DIAGNOSTIC 573 if (ksp->ks_inuse == 0) 574 panic("free 1: inuse 0, probable double free"); 575 #endif 576 ksp->ks_inuse--; 577 kbp->kb_total -= 1; 578 #endif 579 mutex_spin_exit(&malloc_lock); 580 return; 581 } 582 freep = (struct freelist *)addr; 583 #ifdef DIAGNOSTIC 584 /* 585 * Check for multiple frees. Use a quick check to see if 586 * it looks free before laboriously searching the freelist. 587 */ 588 if (__predict_false(freep->spare0 == WEIRD_ADDR)) { 589 for (cp = kbp->kb_next; cp; 590 cp = ((struct freelist *)cp)->next) { 591 if (addr != cp) 592 continue; 593 printf("multiply freed item %p\n", addr); 594 #ifdef MALLOCLOG 595 hitmlog(addr); 596 #endif 597 panic("free: duplicated free"); 598 } 599 } 600 601 /* 602 * Copy in known text to detect modification after freeing 603 * and to make it look free. Also, save the type being freed 604 * so we can list likely culprit if modification is detected 605 * when the object is reallocated. 606 */ 607 copysize = size < MAX_COPY ? size : MAX_COPY; 608 end = (int32_t *)&((char *)addr)[copysize]; 609 for (lp = (int32_t *)addr; lp < end; lp++) 610 *lp = WEIRD_ADDR; 611 freep->type = ksp; 612 #endif /* DIAGNOSTIC */ 613 #ifdef KMEMSTATS 614 kup->ku_freecnt++; 615 if (kup->ku_freecnt >= kbp->kb_elmpercl) { 616 if (kup->ku_freecnt > kbp->kb_elmpercl) 617 panic("free: multiple frees"); 618 else if (kbp->kb_totalfree > kbp->kb_highwat) 619 kbp->kb_couldfree++; 620 } 621 kbp->kb_totalfree++; 622 ksp->ks_memuse -= size; 623 if (ksp->ks_memuse + size >= ksp->ks_limit && 624 ksp->ks_memuse < ksp->ks_limit) 625 wakeup((void *)ksp); 626 #ifdef DIAGNOSTIC 627 if (ksp->ks_inuse == 0) 628 panic("free 2: inuse 0, probable double free"); 629 #endif 630 ksp->ks_inuse--; 631 #endif 632 if (kbp->kb_next == NULL) 633 kbp->kb_next = addr; 634 else 635 ((struct freelist *)kbp->kb_last)->next = addr; 636 freep->next = NULL; 637 kbp->kb_last = addr; 638 mutex_spin_exit(&malloc_lock); 639 } 640 641 /* 642 * Change the size of a block of memory. 643 */ 644 void * 645 realloc(void *curaddr, unsigned long newsize, struct malloc_type *ksp, 646 int flags) 647 { 648 struct kmemusage *kup; 649 unsigned long cursize; 650 void *newaddr; 651 #ifdef DIAGNOSTIC 652 long alloc; 653 #endif 654 655 /* 656 * realloc() with a NULL pointer is the same as malloc(). 657 */ 658 if (curaddr == NULL) 659 return (malloc(newsize, ksp, flags)); 660 661 /* 662 * realloc() with zero size is the same as free(). 663 */ 664 if (newsize == 0) { 665 free(curaddr, ksp); 666 return (NULL); 667 } 668 669 #ifdef LOCKDEBUG 670 if ((flags & M_NOWAIT) == 0) { 671 ASSERT_SLEEPABLE(); 672 } 673 #endif 674 675 /* 676 * Find out how large the old allocation was (and do some 677 * sanity checking). 678 */ 679 kup = btokup(curaddr); 680 cursize = 1 << kup->ku_indx; 681 682 #ifdef DIAGNOSTIC 683 /* 684 * Check for returns of data that do not point to the 685 * beginning of the allocation. 686 */ 687 if (cursize > PAGE_SIZE) 688 alloc = addrmask[BUCKETINDX(PAGE_SIZE)]; 689 else 690 alloc = addrmask[kup->ku_indx]; 691 if (((u_long)curaddr & alloc) != 0) 692 panic("realloc: " 693 "unaligned addr %p, size %ld, type %s, mask %ld\n", 694 curaddr, cursize, ksp->ks_shortdesc, alloc); 695 #endif /* DIAGNOSTIC */ 696 697 if (cursize > MAXALLOCSAVE) 698 cursize = ctob(kup->ku_pagecnt); 699 700 /* 701 * If we already actually have as much as they want, we're done. 702 */ 703 if (newsize <= cursize) 704 return (curaddr); 705 706 /* 707 * Can't satisfy the allocation with the existing block. 708 * Allocate a new one and copy the data. 709 */ 710 newaddr = malloc(newsize, ksp, flags); 711 if (__predict_false(newaddr == NULL)) { 712 /* 713 * malloc() failed, because flags included M_NOWAIT. 714 * Return NULL to indicate that failure. The old 715 * pointer is still valid. 716 */ 717 return (NULL); 718 } 719 memcpy(newaddr, curaddr, cursize); 720 721 /* 722 * We were successful: free the old allocation and return 723 * the new one. 724 */ 725 free(curaddr, ksp); 726 return (newaddr); 727 } 728 729 /* 730 * Roundup size to the actual allocation size. 731 */ 732 unsigned long 733 malloc_roundup(unsigned long size) 734 { 735 736 if (size > MAXALLOCSAVE) 737 return (roundup(size, PAGE_SIZE)); 738 else 739 return (1 << BUCKETINDX(size)); 740 } 741 742 /* 743 * Add a malloc type to the system. 744 */ 745 void 746 malloc_type_attach(struct malloc_type *type) 747 { 748 749 if (nkmempages == 0) 750 panic("malloc_type_attach: nkmempages == 0"); 751 752 if (type->ks_magic != M_MAGIC) 753 panic("malloc_type_attach: bad magic"); 754 755 #ifdef DIAGNOSTIC 756 { 757 struct malloc_type *ksp; 758 for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) { 759 if (ksp == type) 760 panic("malloc_type_attach: already on list"); 761 } 762 } 763 #endif 764 765 #ifdef KMEMSTATS 766 if (type->ks_limit == 0) 767 type->ks_limit = ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U; 768 #else 769 type->ks_limit = 0; 770 #endif 771 772 type->ks_next = kmemstatistics; 773 kmemstatistics = type; 774 } 775 776 /* 777 * Remove a malloc type from the system.. 778 */ 779 void 780 malloc_type_detach(struct malloc_type *type) 781 { 782 struct malloc_type *ksp; 783 784 #ifdef DIAGNOSTIC 785 if (type->ks_magic != M_MAGIC) 786 panic("malloc_type_detach: bad magic"); 787 #endif 788 789 if (type == kmemstatistics) 790 kmemstatistics = type->ks_next; 791 else { 792 for (ksp = kmemstatistics; ksp->ks_next != NULL; 793 ksp = ksp->ks_next) { 794 if (ksp->ks_next == type) { 795 ksp->ks_next = type->ks_next; 796 break; 797 } 798 } 799 #ifdef DIAGNOSTIC 800 if (ksp->ks_next == NULL) 801 panic("malloc_type_detach: not on list"); 802 #endif 803 } 804 type->ks_next = NULL; 805 } 806 807 /* 808 * Set the limit on a malloc type. 809 */ 810 void 811 malloc_type_setlimit(struct malloc_type *type, u_long limit) 812 { 813 #ifdef KMEMSTATS 814 mutex_spin_enter(&malloc_lock); 815 type->ks_limit = limit; 816 mutex_spin_exit(&malloc_lock); 817 #endif 818 } 819 820 /* 821 * Compute the number of pages that kmem_map will map, that is, 822 * the size of the kernel malloc arena. 823 */ 824 void 825 kmeminit_nkmempages(void) 826 { 827 int npages; 828 829 if (nkmempages != 0) { 830 /* 831 * It's already been set (by us being here before, or 832 * by patching or kernel config options), bail out now. 833 */ 834 return; 835 } 836 837 npages = physmem; 838 839 if (npages > NKMEMPAGES_MAX) 840 npages = NKMEMPAGES_MAX; 841 842 if (npages < NKMEMPAGES_MIN) 843 npages = NKMEMPAGES_MIN; 844 845 nkmempages = npages; 846 } 847 848 /* 849 * Initialize the kernel memory allocator 850 */ 851 void 852 kmeminit(void) 853 { 854 __link_set_decl(malloc_types, struct malloc_type); 855 struct malloc_type * const *ksp; 856 vaddr_t kmb, kml; 857 #ifdef KMEMSTATS 858 long indx; 859 #endif 860 861 #if ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0) 862 ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2 863 #endif 864 #if (MAXALLOCSAVE > MINALLOCSIZE * 32768) 865 ERROR!_kmeminit:_MAXALLOCSAVE_too_big 866 #endif 867 #if (MAXALLOCSAVE < NBPG) 868 ERROR!_kmeminit:_MAXALLOCSAVE_too_small 869 #endif 870 871 if (sizeof(struct freelist) > (1 << MINBUCKET)) 872 panic("minbucket too small/struct freelist too big"); 873 874 mutex_init(&malloc_lock, MUTEX_DEFAULT, IPL_VM); 875 876 /* 877 * Compute the number of kmem_map pages, if we have not 878 * done so already. 879 */ 880 kmeminit_nkmempages(); 881 882 kmemusage = (struct kmemusage *) uvm_km_alloc(kernel_map, 883 (vsize_t)(nkmempages * sizeof(struct kmemusage)), 0, 884 UVM_KMF_WIRED|UVM_KMF_ZERO); 885 kmb = 0; 886 kmem_map = uvm_km_suballoc(kernel_map, &kmb, 887 &kml, ((vsize_t)nkmempages << PAGE_SHIFT), 888 VM_MAP_INTRSAFE, false, &kmem_map_store); 889 uvm_km_vacache_init(kmem_map, "kvakmem", 0); 890 kmembase = (char *)kmb; 891 kmemlimit = (char *)kml; 892 #ifdef KMEMSTATS 893 for (indx = 0; indx < MINBUCKET + 16; indx++) { 894 if (1 << indx >= PAGE_SIZE) 895 kmembuckets[indx].kb_elmpercl = 1; 896 else 897 kmembuckets[indx].kb_elmpercl = PAGE_SIZE / (1 << indx); 898 kmembuckets[indx].kb_highwat = 899 5 * kmembuckets[indx].kb_elmpercl; 900 } 901 #endif 902 903 /* Attach all of the statically-linked malloc types. */ 904 __link_set_foreach(ksp, malloc_types) 905 malloc_type_attach(*ksp); 906 } 907 908 #ifdef DDB 909 #include <ddb/db_output.h> 910 911 /* 912 * Dump kmem statistics from ddb. 913 * 914 * usage: call dump_kmemstats 915 */ 916 void dump_kmemstats(void); 917 918 void 919 dump_kmemstats(void) 920 { 921 #ifdef KMEMSTATS 922 struct malloc_type *ksp; 923 924 for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) { 925 if (ksp->ks_memuse == 0) 926 continue; 927 db_printf("%s%.*s %ld\n", ksp->ks_shortdesc, 928 (int)(20 - strlen(ksp->ks_shortdesc)), 929 " ", 930 ksp->ks_memuse); 931 } 932 #else 933 db_printf("Kmem stats are not being collected.\n"); 934 #endif /* KMEMSTATS */ 935 } 936 #endif /* DDB */ 937 938 939 #if 0 940 /* 941 * Diagnostic messages about "Data modified on 942 * freelist" indicate a memory corruption, but 943 * they do not help tracking it down. 944 * This function can be called at various places 945 * to sanity check malloc's freelist and discover 946 * where does the corruption take place. 947 */ 948 int 949 freelist_sanitycheck(void) { 950 int i,j; 951 struct kmembuckets *kbp; 952 struct freelist *freep; 953 int rv = 0; 954 955 for (i = MINBUCKET; i <= MINBUCKET + 15; i++) { 956 kbp = &kmembuckets[i]; 957 freep = (struct freelist *)kbp->kb_next; 958 j = 0; 959 while(freep) { 960 vm_map_lock(kmem_map); 961 rv = uvm_map_checkprot(kmem_map, (vaddr_t)freep, 962 (vaddr_t)freep + sizeof(struct freelist), 963 VM_PROT_WRITE); 964 vm_map_unlock(kmem_map); 965 966 if ((rv == 0) || (*(int *)freep != WEIRD_ADDR)) { 967 printf("bucket %i, chunck %d at %p modified\n", 968 i, j, freep); 969 return 1; 970 } 971 freep = (struct freelist *)freep->next; 972 j++; 973 } 974 } 975 976 return 0; 977 } 978 #endif 979