1 /* $OpenBSD: kern_malloc.c,v 1.39 2001/09/19 20:50:58 mickey Exp $ */ 2 /* $NetBSD: kern_malloc.c,v 1.15.4.2 1996/06/13 17:10:56 cgd Exp $ */ 3 4 /* 5 * Copyright (c) 1987, 1991, 1993 6 * The Regents of the University of California. All rights reserved. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 3. All advertising materials mentioning features or use of this software 17 * must display the following acknowledgement: 18 * This product includes software developed by the University of 19 * California, Berkeley and its contributors. 20 * 4. Neither the name of the University nor the names of its contributors 21 * may be used to endorse or promote products derived from this software 22 * without specific prior written permission. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 34 * SUCH DAMAGE. 35 * 36 * @(#)kern_malloc.c 8.3 (Berkeley) 1/4/94 37 */ 38 39 #include <sys/param.h> 40 #include <sys/proc.h> 41 #include <sys/map.h> 42 #include <sys/kernel.h> 43 #include <sys/malloc.h> 44 #include <sys/systm.h> 45 #include <sys/sysctl.h> 46 47 #include <vm/vm.h> 48 #include <uvm/uvm_extern.h> 49 50 static struct vm_map_intrsafe kmem_map_store; 51 vm_map_t kmem_map = NULL; 52 53 int nkmempages; 54 55 struct kmembuckets bucket[MINBUCKET + 16]; 56 struct kmemstats kmemstats[M_LAST]; 57 struct kmemusage *kmemusage; 58 char *kmembase, *kmemlimit; 59 char buckstring[16 * sizeof("123456,")]; 60 int buckstring_init = 0; 61 #if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES) 62 char *memname[] = INITKMEMNAMES; 63 char *memall = NULL; 64 extern struct lock sysctl_kmemlock; 65 #endif 66 67 #ifdef DIAGNOSTIC 68 /* 69 * This structure provides a set of masks to catch unaligned frees. 70 */ 71 long addrmask[] = { 0, 72 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 73 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 74 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 75 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff, 76 }; 77 78 /* 79 * The WEIRD_ADDR is used as known text to copy into free objects so 80 * that modifications after frees can be detected. 81 */ 82 #define WEIRD_ADDR ((unsigned) 0xdeadbeef) 83 #define MAX_COPY 32 84 85 /* 86 * Normally the freelist structure is used only to hold the list pointer 87 * for free objects. However, when running with diagnostics, the first 88 * 8 bytes of the structure is unused except for diagnostic information, 89 * and the free list pointer is at offset 8 in the structure. Since the 90 * first 8 bytes is the portion of the structure most often modified, this 91 * helps to detect memory reuse problems and avoid free list corruption. 92 */ 93 struct freelist { 94 int32_t spare0; 95 int16_t type; 96 int16_t spare1; 97 caddr_t next; 98 }; 99 #else /* !DIAGNOSTIC */ 100 struct freelist { 101 caddr_t next; 102 }; 103 #endif /* DIAGNOSTIC */ 104 105 /* 106 * Allocate a block of memory 107 */ 108 void * 109 malloc(size, type, flags) 110 unsigned long size; 111 int type, flags; 112 { 113 register struct kmembuckets *kbp; 114 register struct kmemusage *kup; 115 register struct freelist *freep; 116 long indx, npg, allocsize; 117 int s; 118 caddr_t va, cp, savedlist; 119 #ifdef DIAGNOSTIC 120 int32_t *end, *lp; 121 int copysize; 122 char *savedtype; 123 #endif 124 #ifdef KMEMSTATS 125 register struct kmemstats *ksp = &kmemstats[type]; 126 127 if (((unsigned long)type) > M_LAST) 128 panic("malloc - bogus type"); 129 #endif 130 131 #ifdef MALLOC_DEBUG 132 if (debug_malloc(size, type, flags, (void **)&va)) 133 return ((void *) va); 134 #endif 135 136 indx = BUCKETINDX(size); 137 kbp = &bucket[indx]; 138 s = splimp(); 139 #ifdef KMEMSTATS 140 while (ksp->ks_memuse >= ksp->ks_limit) { 141 if (flags & M_NOWAIT) { 142 splx(s); 143 return ((void *) NULL); 144 } 145 if (ksp->ks_limblocks < 65535) 146 ksp->ks_limblocks++; 147 tsleep((caddr_t)ksp, PSWP+2, memname[type], 0); 148 } 149 ksp->ks_size |= 1 << indx; 150 #endif 151 #ifdef DIAGNOSTIC 152 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY; 153 #endif 154 if (kbp->kb_next == NULL) { 155 kbp->kb_last = NULL; 156 if (size > MAXALLOCSAVE) 157 allocsize = round_page(size); 158 else 159 allocsize = 1 << indx; 160 npg = btoc(allocsize); 161 va = (caddr_t) uvm_km_kmemalloc(kmem_map, uvmexp.kmem_object, 162 (vsize_t)ctob(npg), 163 (flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0); 164 if (va == NULL) { 165 /* 166 * Kmem_malloc() can return NULL, even if it can 167 * wait, if there is no map space available, because 168 * it can't fix that problem. Neither can we, 169 * right now. (We should release pages which 170 * are completely free and which are in buckets 171 * with too many free elements.) 172 */ 173 if ((flags & M_NOWAIT) == 0) 174 panic("malloc: out of space in kmem_map"); 175 splx(s); 176 return ((void *) NULL); 177 } 178 #ifdef KMEMSTATS 179 kbp->kb_total += kbp->kb_elmpercl; 180 #endif 181 kup = btokup(va); 182 kup->ku_indx = indx; 183 if (allocsize > MAXALLOCSAVE) { 184 if (npg > 65535) 185 panic("malloc: allocation too large"); 186 kup->ku_pagecnt = npg; 187 #ifdef KMEMSTATS 188 ksp->ks_memuse += allocsize; 189 #endif 190 goto out; 191 } 192 #ifdef KMEMSTATS 193 kup->ku_freecnt = kbp->kb_elmpercl; 194 kbp->kb_totalfree += kbp->kb_elmpercl; 195 #endif 196 /* 197 * Just in case we blocked while allocating memory, 198 * and someone else also allocated memory for this 199 * bucket, don't assume the list is still empty. 200 */ 201 savedlist = kbp->kb_next; 202 kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize; 203 for (;;) { 204 freep = (struct freelist *)cp; 205 #ifdef DIAGNOSTIC 206 /* 207 * Copy in known text to detect modification 208 * after freeing. 209 */ 210 end = (int32_t *)&cp[copysize]; 211 for (lp = (int32_t *)cp; lp < end; lp++) 212 *lp = WEIRD_ADDR; 213 freep->type = M_FREE; 214 #endif /* DIAGNOSTIC */ 215 if (cp <= va) 216 break; 217 cp -= allocsize; 218 freep->next = cp; 219 } 220 freep->next = savedlist; 221 if (kbp->kb_last == NULL) 222 kbp->kb_last = (caddr_t)freep; 223 } 224 va = kbp->kb_next; 225 kbp->kb_next = ((struct freelist *)va)->next; 226 #ifdef DIAGNOSTIC 227 freep = (struct freelist *)va; 228 savedtype = (unsigned)freep->type < M_LAST ? 229 memname[freep->type] : "???"; 230 if (kbp->kb_next) { 231 int rv; 232 vaddr_t addr = (vaddr_t)kbp->kb_next; 233 234 vm_map_lock(kmem_map); 235 rv = uvm_map_checkprot(kmem_map, addr, 236 addr + sizeof(struct freelist), VM_PROT_WRITE); 237 vm_map_unlock(kmem_map); 238 239 if (!rv) { 240 printf("%s %d of object %p size 0x%lx %s %s (invalid addr %p)\n", 241 "Data modified on freelist: word", 242 (int32_t *)&kbp->kb_next - (int32_t *)kbp, va, size, 243 "previous type", savedtype, kbp->kb_next); 244 kbp->kb_next = NULL; 245 } 246 } 247 248 /* Fill the fields that we've used with WEIRD_ADDR */ 249 #if BYTE_ORDER == BIG_ENDIAN 250 freep->type = WEIRD_ADDR >> 16; 251 #endif 252 #if BYTE_ORDER == LITTLE_ENDIAN 253 freep->type = (short)WEIRD_ADDR; 254 #endif 255 end = (int32_t *)&freep->next + 256 (sizeof(freep->next) / sizeof(int32_t)); 257 for (lp = (int32_t *)&freep->next; lp < end; lp++) 258 *lp = WEIRD_ADDR; 259 260 /* and check that the data hasn't been modified. */ 261 end = (int32_t *)&va[copysize]; 262 for (lp = (int32_t *)va; lp < end; lp++) { 263 if (*lp == WEIRD_ADDR) 264 continue; 265 printf("%s %d of object %p size 0x%lx %s %s (0x%x != 0x%x)\n", 266 "Data modified on freelist: word", lp - (int32_t *)va, 267 va, size, "previous type", savedtype, *lp, WEIRD_ADDR); 268 break; 269 } 270 271 freep->spare0 = 0; 272 #endif /* DIAGNOSTIC */ 273 #ifdef KMEMSTATS 274 kup = btokup(va); 275 if (kup->ku_indx != indx) 276 panic("malloc: wrong bucket"); 277 if (kup->ku_freecnt == 0) 278 panic("malloc: lost data"); 279 kup->ku_freecnt--; 280 kbp->kb_totalfree--; 281 ksp->ks_memuse += 1 << indx; 282 out: 283 kbp->kb_calls++; 284 ksp->ks_inuse++; 285 ksp->ks_calls++; 286 if (ksp->ks_memuse > ksp->ks_maxused) 287 ksp->ks_maxused = ksp->ks_memuse; 288 #else 289 out: 290 #endif 291 splx(s); 292 return ((void *) va); 293 } 294 295 /* 296 * Free a block of memory allocated by malloc. 297 */ 298 void 299 free(addr, type) 300 void *addr; 301 int type; 302 { 303 register struct kmembuckets *kbp; 304 register struct kmemusage *kup; 305 register struct freelist *freep; 306 long size; 307 int s; 308 #ifdef DIAGNOSTIC 309 caddr_t cp; 310 int32_t *end, *lp; 311 long alloc, copysize; 312 #endif 313 #ifdef KMEMSTATS 314 register struct kmemstats *ksp = &kmemstats[type]; 315 #endif 316 317 #ifdef MALLOC_DEBUG 318 if (debug_free(addr, type)) 319 return; 320 #endif 321 322 #ifdef DIAGNOSTIC 323 if (addr < (void *)kmembase || addr >= (void *)kmemlimit) 324 panic("free: non-malloced addr %p type %s", addr, 325 memname[type]); 326 #endif 327 328 kup = btokup(addr); 329 size = 1 << kup->ku_indx; 330 kbp = &bucket[kup->ku_indx]; 331 s = splimp(); 332 #ifdef DIAGNOSTIC 333 /* 334 * Check for returns of data that do not point to the 335 * beginning of the allocation. 336 */ 337 if (size > PAGE_SIZE) 338 alloc = addrmask[BUCKETINDX(PAGE_SIZE)]; 339 else 340 alloc = addrmask[kup->ku_indx]; 341 if (((u_long)addr & alloc) != 0) 342 panic("free: unaligned addr %p, size %ld, type %s, mask %ld", 343 addr, size, memname[type], alloc); 344 #endif /* DIAGNOSTIC */ 345 if (size > MAXALLOCSAVE) { 346 uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt)); 347 #ifdef KMEMSTATS 348 size = kup->ku_pagecnt << PGSHIFT; 349 ksp->ks_memuse -= size; 350 kup->ku_indx = 0; 351 kup->ku_pagecnt = 0; 352 if (ksp->ks_memuse + size >= ksp->ks_limit && 353 ksp->ks_memuse < ksp->ks_limit) 354 wakeup((caddr_t)ksp); 355 ksp->ks_inuse--; 356 kbp->kb_total -= 1; 357 #endif 358 splx(s); 359 return; 360 } 361 freep = (struct freelist *)addr; 362 #ifdef DIAGNOSTIC 363 /* 364 * Check for multiple frees. Use a quick check to see if 365 * it looks free before laboriously searching the freelist. 366 */ 367 if (freep->spare0 == WEIRD_ADDR) { 368 for (cp = kbp->kb_next; cp; 369 cp = ((struct freelist *)cp)->next) { 370 if (addr != cp) 371 continue; 372 printf("multiply freed item %p\n", addr); 373 panic("free: duplicated free"); 374 } 375 } 376 /* 377 * Copy in known text to detect modification after freeing 378 * and to make it look free. Also, save the type being freed 379 * so we can list likely culprit if modification is detected 380 * when the object is reallocated. 381 */ 382 copysize = size < MAX_COPY ? size : MAX_COPY; 383 end = (int32_t *)&((caddr_t)addr)[copysize]; 384 for (lp = (int32_t *)addr; lp < end; lp++) 385 *lp = WEIRD_ADDR; 386 freep->type = type; 387 #endif /* DIAGNOSTIC */ 388 #ifdef KMEMSTATS 389 kup->ku_freecnt++; 390 if (kup->ku_freecnt >= kbp->kb_elmpercl) { 391 if (kup->ku_freecnt > kbp->kb_elmpercl) 392 panic("free: multiple frees"); 393 else if (kbp->kb_totalfree > kbp->kb_highwat) 394 kbp->kb_couldfree++; 395 } 396 kbp->kb_totalfree++; 397 ksp->ks_memuse -= size; 398 if (ksp->ks_memuse + size >= ksp->ks_limit && 399 ksp->ks_memuse < ksp->ks_limit) 400 wakeup((caddr_t)ksp); 401 ksp->ks_inuse--; 402 #endif 403 if (kbp->kb_next == NULL) 404 kbp->kb_next = addr; 405 else 406 ((struct freelist *)kbp->kb_last)->next = addr; 407 freep->next = NULL; 408 kbp->kb_last = addr; 409 splx(s); 410 } 411 412 /* 413 * Initialize the kernel memory allocator 414 */ 415 void 416 kmeminit() 417 { 418 #ifdef KMEMSTATS 419 long indx; 420 #endif 421 int npg; 422 423 #ifdef DIAGNOSTIC 424 if (sizeof(struct freelist) > (1 << MINBUCKET)) 425 panic("kmeminit: minbucket too small/struct freelist too big"); 426 #endif 427 428 npg = VM_KMEM_SIZE / PAGE_SIZE; 429 kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map, 430 (vsize_t)(npg * sizeof(struct kmemusage))); 431 kmem_map = uvm_km_suballoc(kernel_map, (vaddr_t *)&kmembase, 432 (vaddr_t *)&kmemlimit, (vsize_t)(npg * PAGE_SIZE), 433 VM_MAP_INTRSAFE, FALSE, &kmem_map_store.vmi_map); 434 #ifdef KMEMSTATS 435 for (indx = 0; indx < MINBUCKET + 16; indx++) { 436 if (1 << indx >= PAGE_SIZE) 437 bucket[indx].kb_elmpercl = 1; 438 else 439 bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx); 440 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl; 441 } 442 for (indx = 0; indx < M_LAST; indx++) 443 kmemstats[indx].ks_limit = npg * PAGE_SIZE * 6 / 10; 444 #endif 445 #ifdef MALLOC_DEBUG 446 debug_malloc_init(); 447 #endif 448 449 nkmempages = npg; 450 } 451 452 /* 453 * Return kernel malloc statistics information. 454 */ 455 int 456 sysctl_malloc(name, namelen, oldp, oldlenp, newp, newlen, p) 457 int *name; 458 u_int namelen; 459 void *oldp; 460 size_t *oldlenp; 461 void *newp; 462 size_t newlen; 463 struct proc *p; 464 { 465 struct kmembuckets kb; 466 int i, siz; 467 468 if (namelen != 2 && name[0] != KERN_MALLOC_BUCKETS && 469 name[0] != KERN_MALLOC_KMEMNAMES) 470 return (ENOTDIR); /* overloaded */ 471 472 switch (name[0]) { 473 case KERN_MALLOC_BUCKETS: 474 /* Initialize the first time */ 475 if (buckstring_init == 0) { 476 buckstring_init = 1; 477 bzero(buckstring, sizeof(buckstring)); 478 for (siz = 0, i = MINBUCKET; i < MINBUCKET + 16; i++) 479 siz += sprintf(buckstring + siz, 480 "%d,", (u_int)(1<<i)); 481 /* Remove trailing comma */ 482 if (siz) 483 buckstring[siz - 1] = '\0'; 484 } 485 return (sysctl_rdstring(oldp, oldlenp, newp, buckstring)); 486 487 case KERN_MALLOC_BUCKET: 488 bcopy(&bucket[BUCKETINDX(name[1])], &kb, sizeof(kb)); 489 kb.kb_next = kb.kb_last = 0; 490 return (sysctl_rdstruct(oldp, oldlenp, newp, &kb, sizeof(kb))); 491 case KERN_MALLOC_KMEMSTATS: 492 #ifdef KMEMSTATS 493 if ((name[1] < 0) || (name[1] >= M_LAST)) 494 return (EINVAL); 495 return (sysctl_rdstruct(oldp, oldlenp, newp, 496 &kmemstats[name[1]], sizeof(struct kmemstats))); 497 #else 498 return (EOPNOTSUPP); 499 #endif 500 case KERN_MALLOC_KMEMNAMES: 501 #if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES) 502 if (memall == NULL) { 503 int totlen; 504 505 i = lockmgr(&sysctl_kmemlock, LK_EXCLUSIVE, NULL, p); 506 if (i) 507 return (i); 508 509 /* Figure out how large a buffer we need */ 510 for (totlen = 0, i = 0; i < M_LAST; i++) { 511 if (memname[i]) 512 totlen += strlen(memname[i]); 513 totlen++; 514 } 515 memall = malloc(totlen + M_LAST, M_SYSCTL, M_WAITOK); 516 bzero(memall, totlen + M_LAST); 517 for (siz = 0, i = 0; i < M_LAST; i++) 518 siz += sprintf(memall + siz, "%s,", 519 memname[i] ? memname[i] : ""); 520 521 /* Remove trailing comma */ 522 if (siz) 523 memall[siz - 1] = '\0'; 524 525 /* Now, convert all spaces to underscores */ 526 for (i = 0; i < totlen; i++) 527 if (memall[i] == ' ') 528 memall[i] = '_'; 529 lockmgr(&sysctl_kmemlock, LK_RELEASE, NULL, p); 530 } 531 return (sysctl_rdstring(oldp, oldlenp, newp, memall)); 532 #else 533 return (EOPNOTSUPP); 534 #endif 535 default: 536 return (EOPNOTSUPP); 537 } 538 /* NOTREACHED */ 539 } 540