1 /* $NetBSD: subr_kmem.c,v 1.61 2015/07/27 09:24:28 maxv Exp $ */ 2 3 /*- 4 * Copyright (c) 2009-2015 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Andrew Doran and Maxime Villard. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 /*- 33 * Copyright (c)2006 YAMAMOTO Takashi, 34 * All rights reserved. 35 * 36 * Redistribution and use in source and binary forms, with or without 37 * modification, are permitted provided that the following conditions 38 * are met: 39 * 1. Redistributions of source code must retain the above copyright 40 * notice, this list of conditions and the following disclaimer. 41 * 2. Redistributions in binary form must reproduce the above copyright 42 * notice, this list of conditions and the following disclaimer in the 43 * documentation and/or other materials provided with the distribution. 44 * 45 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 48 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 55 * SUCH DAMAGE. 56 */ 57 58 /* 59 * Allocator of kernel wired memory. This allocator has some debug features 60 * enabled with "option DIAGNOSTIC" and "option DEBUG". 61 */ 62 63 /* 64 * KMEM_SIZE: detect alloc/free size mismatch bugs. 65 * Prefix each allocations with a fixed-sized, aligned header and record 66 * the exact user-requested allocation size in it. When freeing, compare 67 * it with kmem_free's "size" argument. 68 * 69 * KMEM_REDZONE: detect overrun bugs. 70 * Add a 2-byte pattern (allocate one more memory chunk if needed) at the 71 * end of each allocated buffer. Check this pattern on kmem_free. 72 * 73 * These options are enabled on DIAGNOSTIC. 74 * 75 * |CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK| 76 * +-----+-----+-----+-----+-----+-----+-----+-----+-----+---+-+--+--+ 77 * |/////| | | | | | | | | |*|**|UU| 78 * |/HSZ/| | | | | | | | | |*|**|UU| 79 * |/////| | | | | | | | | |*|**|UU| 80 * +-----+-----+-----+-----+-----+-----+-----+-----+-----+---+-+--+--+ 81 * |Size | Buffer usable by the caller (requested size) |RedZ|Unused\ 82 */ 83 84 /* 85 * KMEM_POISON: detect modify-after-free bugs. 86 * Fill freed (in the sense of kmem_free) memory with a garbage pattern. 87 * Check the pattern on allocation. 88 * 89 * KMEM_GUARD 90 * A kernel with "option DEBUG" has "kmem_guard" debugging feature compiled 91 * in. See the comment below for what kind of bugs it tries to detect. Even 92 * if compiled in, it's disabled by default because it's very expensive. 93 * You can enable it on boot by: 94 * boot -d 95 * db> w kmem_guard_depth 0t30000 96 * db> c 97 * 98 * The default value of kmem_guard_depth is 0, which means disabled. 99 * It can be changed by KMEM_GUARD_DEPTH kernel config option. 100 */ 101 102 #include <sys/cdefs.h> 103 __KERNEL_RCSID(0, "$NetBSD: subr_kmem.c,v 1.61 2015/07/27 09:24:28 maxv Exp $"); 104 105 #include <sys/param.h> 106 #include <sys/callback.h> 107 #include <sys/kmem.h> 108 #include <sys/pool.h> 109 #include <sys/debug.h> 110 #include <sys/lockdebug.h> 111 #include <sys/cpu.h> 112 113 #include <uvm/uvm_extern.h> 114 #include <uvm/uvm_map.h> 115 116 #include <lib/libkern/libkern.h> 117 118 struct kmem_cache_info { 119 size_t kc_size; 120 const char * kc_name; 121 }; 122 123 static const struct kmem_cache_info kmem_cache_sizes[] = { 124 { 8, "kmem-8" }, 125 { 16, "kmem-16" }, 126 { 24, "kmem-24" }, 127 { 32, "kmem-32" }, 128 { 40, "kmem-40" }, 129 { 48, "kmem-48" }, 130 { 56, "kmem-56" }, 131 { 64, "kmem-64" }, 132 { 80, "kmem-80" }, 133 { 96, "kmem-96" }, 134 { 112, "kmem-112" }, 135 { 128, "kmem-128" }, 136 { 160, "kmem-160" }, 137 { 192, "kmem-192" }, 138 { 224, "kmem-224" }, 139 { 256, "kmem-256" }, 140 { 320, "kmem-320" }, 141 { 384, "kmem-384" }, 142 { 448, "kmem-448" }, 143 { 512, "kmem-512" }, 144 { 768, "kmem-768" }, 145 { 1024, "kmem-1024" }, 146 { 0, NULL } 147 }; 148 149 static const struct kmem_cache_info kmem_cache_big_sizes[] = { 150 { 2048, "kmem-2048" }, 151 { 4096, "kmem-4096" }, 152 { 8192, "kmem-8192" }, 153 { 16384, "kmem-16384" }, 154 { 0, NULL } 155 }; 156 157 /* 158 * KMEM_ALIGN is the smallest guaranteed alignment and also the 159 * smallest allocateable quantum. 160 * Every cache size >= CACHE_LINE_SIZE gets CACHE_LINE_SIZE alignment. 161 */ 162 #define KMEM_ALIGN 8 163 #define KMEM_SHIFT 3 164 #define KMEM_MAXSIZE 1024 165 #define KMEM_CACHE_COUNT (KMEM_MAXSIZE >> KMEM_SHIFT) 166 167 static pool_cache_t kmem_cache[KMEM_CACHE_COUNT] __cacheline_aligned; 168 static size_t kmem_cache_maxidx __read_mostly; 169 170 #define KMEM_BIG_ALIGN 2048 171 #define KMEM_BIG_SHIFT 11 172 #define KMEM_BIG_MAXSIZE 16384 173 #define KMEM_CACHE_BIG_COUNT (KMEM_BIG_MAXSIZE >> KMEM_BIG_SHIFT) 174 175 static pool_cache_t kmem_cache_big[KMEM_CACHE_BIG_COUNT] __cacheline_aligned; 176 static size_t kmem_cache_big_maxidx __read_mostly; 177 178 #if defined(DIAGNOSTIC) && defined(_HARDKERNEL) 179 #define KMEM_SIZE 180 #define KMEM_REDZONE 181 #endif /* defined(DIAGNOSTIC) */ 182 183 #if defined(DEBUG) && defined(_HARDKERNEL) 184 #define KMEM_SIZE 185 #define KMEM_POISON 186 #define KMEM_GUARD 187 static void *kmem_freecheck; 188 #endif /* defined(DEBUG) */ 189 190 #if defined(KMEM_POISON) 191 static int kmem_poison_ctor(void *, void *, int); 192 static void kmem_poison_fill(void *, size_t); 193 static void kmem_poison_check(void *, size_t); 194 #else /* defined(KMEM_POISON) */ 195 #define kmem_poison_fill(p, sz) /* nothing */ 196 #define kmem_poison_check(p, sz) /* nothing */ 197 #endif /* defined(KMEM_POISON) */ 198 199 #if defined(KMEM_REDZONE) 200 #define REDZONE_SIZE 2 201 static void kmem_redzone_fill(void *, size_t); 202 static void kmem_redzone_check(void *, size_t); 203 #else /* defined(KMEM_REDZONE) */ 204 #define REDZONE_SIZE 0 205 #define kmem_redzone_fill(p, sz) /* nothing */ 206 #define kmem_redzone_check(p, sz) /* nothing */ 207 #endif /* defined(KMEM_REDZONE) */ 208 209 #if defined(KMEM_SIZE) 210 struct kmem_header { 211 size_t size; 212 } __aligned(KMEM_ALIGN); 213 #define SIZE_SIZE sizeof(struct kmem_header) 214 static void kmem_size_set(void *, size_t); 215 static void kmem_size_check(void *, size_t); 216 #else 217 #define SIZE_SIZE 0 218 #define kmem_size_set(p, sz) /* nothing */ 219 #define kmem_size_check(p, sz) /* nothing */ 220 #endif 221 222 #if defined(KMEM_GUARD) 223 #ifndef KMEM_GUARD_DEPTH 224 #define KMEM_GUARD_DEPTH 0 225 #endif 226 struct kmem_guard { 227 u_int kg_depth; 228 intptr_t * kg_fifo; 229 u_int kg_rotor; 230 vmem_t * kg_vmem; 231 }; 232 233 static bool kmem_guard_init(struct kmem_guard *, u_int, vmem_t *); 234 static void *kmem_guard_alloc(struct kmem_guard *, size_t, bool); 235 static void kmem_guard_free(struct kmem_guard *, size_t, void *); 236 237 int kmem_guard_depth = KMEM_GUARD_DEPTH; 238 static bool kmem_guard_enabled; 239 static struct kmem_guard kmem_guard; 240 #endif /* defined(KMEM_GUARD) */ 241 242 CTASSERT(KM_SLEEP == PR_WAITOK); 243 CTASSERT(KM_NOSLEEP == PR_NOWAIT); 244 245 /* 246 * kmem_intr_alloc: allocate wired memory. 247 */ 248 249 void * 250 kmem_intr_alloc(size_t requested_size, km_flag_t kmflags) 251 { 252 size_t allocsz, index; 253 size_t size; 254 pool_cache_t pc; 255 uint8_t *p; 256 257 KASSERT(requested_size > 0); 258 259 #ifdef KMEM_GUARD 260 if (kmem_guard_enabled) { 261 return kmem_guard_alloc(&kmem_guard, requested_size, 262 (kmflags & KM_SLEEP) != 0); 263 } 264 #endif 265 size = kmem_roundup_size(requested_size); 266 allocsz = size + SIZE_SIZE; 267 268 #ifdef KMEM_REDZONE 269 if (size - requested_size < REDZONE_SIZE) { 270 /* If there isn't enough space in the padding, allocate 271 * one more memory chunk for the red zone. */ 272 allocsz += kmem_roundup_size(REDZONE_SIZE); 273 } 274 #endif 275 276 if ((index = ((allocsz -1) >> KMEM_SHIFT)) 277 < kmem_cache_maxidx) { 278 pc = kmem_cache[index]; 279 } else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT)) 280 < kmem_cache_big_maxidx) { 281 pc = kmem_cache_big[index]; 282 } else { 283 int ret = uvm_km_kmem_alloc(kmem_va_arena, 284 (vsize_t)round_page(size), 285 ((kmflags & KM_SLEEP) ? VM_SLEEP : VM_NOSLEEP) 286 | VM_INSTANTFIT, (vmem_addr_t *)&p); 287 if (ret) { 288 return NULL; 289 } 290 FREECHECK_OUT(&kmem_freecheck, p); 291 return p; 292 } 293 294 p = pool_cache_get(pc, kmflags); 295 296 if (__predict_true(p != NULL)) { 297 kmem_poison_check(p, allocsz); 298 FREECHECK_OUT(&kmem_freecheck, p); 299 kmem_size_set(p, requested_size); 300 kmem_redzone_fill(p, requested_size + SIZE_SIZE); 301 302 return p + SIZE_SIZE; 303 } 304 return p; 305 } 306 307 /* 308 * kmem_intr_zalloc: allocate zeroed wired memory. 309 */ 310 311 void * 312 kmem_intr_zalloc(size_t size, km_flag_t kmflags) 313 { 314 void *p; 315 316 p = kmem_intr_alloc(size, kmflags); 317 if (p != NULL) { 318 memset(p, 0, size); 319 } 320 return p; 321 } 322 323 /* 324 * kmem_intr_free: free wired memory allocated by kmem_alloc. 325 */ 326 327 void 328 kmem_intr_free(void *p, size_t requested_size) 329 { 330 size_t allocsz, index; 331 size_t size; 332 pool_cache_t pc; 333 334 KASSERT(p != NULL); 335 KASSERT(requested_size > 0); 336 337 #ifdef KMEM_GUARD 338 if (kmem_guard_enabled) { 339 kmem_guard_free(&kmem_guard, requested_size, p); 340 return; 341 } 342 #endif 343 344 size = kmem_roundup_size(requested_size); 345 allocsz = size + SIZE_SIZE; 346 347 #ifdef KMEM_REDZONE 348 if (size - requested_size < REDZONE_SIZE) { 349 allocsz += kmem_roundup_size(REDZONE_SIZE); 350 } 351 #endif 352 353 if ((index = ((allocsz -1) >> KMEM_SHIFT)) 354 < kmem_cache_maxidx) { 355 pc = kmem_cache[index]; 356 } else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT)) 357 < kmem_cache_big_maxidx) { 358 pc = kmem_cache_big[index]; 359 } else { 360 FREECHECK_IN(&kmem_freecheck, p); 361 uvm_km_kmem_free(kmem_va_arena, (vaddr_t)p, 362 round_page(size)); 363 return; 364 } 365 366 p = (uint8_t *)p - SIZE_SIZE; 367 kmem_size_check(p, requested_size); 368 kmem_redzone_check(p, requested_size + SIZE_SIZE); 369 FREECHECK_IN(&kmem_freecheck, p); 370 LOCKDEBUG_MEM_CHECK(p, size); 371 kmem_poison_fill(p, allocsz); 372 373 pool_cache_put(pc, p); 374 } 375 376 /* ---- kmem API */ 377 378 /* 379 * kmem_alloc: allocate wired memory. 380 * => must not be called from interrupt context. 381 */ 382 383 void * 384 kmem_alloc(size_t size, km_flag_t kmflags) 385 { 386 KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()), 387 "kmem(9) should not be used from the interrupt context"); 388 return kmem_intr_alloc(size, kmflags); 389 } 390 391 /* 392 * kmem_zalloc: allocate zeroed wired memory. 393 * => must not be called from interrupt context. 394 */ 395 396 void * 397 kmem_zalloc(size_t size, km_flag_t kmflags) 398 { 399 KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()), 400 "kmem(9) should not be used from the interrupt context"); 401 return kmem_intr_zalloc(size, kmflags); 402 } 403 404 /* 405 * kmem_free: free wired memory allocated by kmem_alloc. 406 * => must not be called from interrupt context. 407 */ 408 409 void 410 kmem_free(void *p, size_t size) 411 { 412 KASSERT(!cpu_intr_p()); 413 KASSERT(!cpu_softintr_p()); 414 kmem_intr_free(p, size); 415 } 416 417 static size_t 418 kmem_create_caches(const struct kmem_cache_info *array, 419 pool_cache_t alloc_table[], size_t maxsize, int shift, int ipl) 420 { 421 size_t maxidx = 0; 422 size_t table_unit = (1 << shift); 423 size_t size = table_unit; 424 int i; 425 426 for (i = 0; array[i].kc_size != 0 ; i++) { 427 const char *name = array[i].kc_name; 428 size_t cache_size = array[i].kc_size; 429 struct pool_allocator *pa; 430 int flags = PR_NOALIGN; 431 pool_cache_t pc; 432 size_t align; 433 434 if ((cache_size & (CACHE_LINE_SIZE - 1)) == 0) 435 align = CACHE_LINE_SIZE; 436 else if ((cache_size & (PAGE_SIZE - 1)) == 0) 437 align = PAGE_SIZE; 438 else 439 align = KMEM_ALIGN; 440 441 if (cache_size < CACHE_LINE_SIZE) 442 flags |= PR_NOTOUCH; 443 444 /* check if we reached the requested size */ 445 if (cache_size > maxsize || cache_size > PAGE_SIZE) { 446 break; 447 } 448 if ((cache_size >> shift) > maxidx) { 449 maxidx = cache_size >> shift; 450 } 451 452 if ((cache_size >> shift) > maxidx) { 453 maxidx = cache_size >> shift; 454 } 455 456 pa = &pool_allocator_kmem; 457 #if defined(KMEM_POISON) 458 pc = pool_cache_init(cache_size, align, 0, flags, 459 name, pa, ipl, kmem_poison_ctor, 460 NULL, (void *)cache_size); 461 #else /* defined(KMEM_POISON) */ 462 pc = pool_cache_init(cache_size, align, 0, flags, 463 name, pa, ipl, NULL, NULL, NULL); 464 #endif /* defined(KMEM_POISON) */ 465 466 while (size <= cache_size) { 467 alloc_table[(size - 1) >> shift] = pc; 468 size += table_unit; 469 } 470 } 471 return maxidx; 472 } 473 474 void 475 kmem_init(void) 476 { 477 #ifdef KMEM_GUARD 478 kmem_guard_enabled = kmem_guard_init(&kmem_guard, kmem_guard_depth, 479 kmem_va_arena); 480 #endif 481 kmem_cache_maxidx = kmem_create_caches(kmem_cache_sizes, 482 kmem_cache, KMEM_MAXSIZE, KMEM_SHIFT, IPL_VM); 483 kmem_cache_big_maxidx = kmem_create_caches(kmem_cache_big_sizes, 484 kmem_cache_big, PAGE_SIZE, KMEM_BIG_SHIFT, IPL_VM); 485 } 486 487 size_t 488 kmem_roundup_size(size_t size) 489 { 490 return (size + (KMEM_ALIGN - 1)) & ~(KMEM_ALIGN - 1); 491 } 492 493 /* 494 * Used to dynamically allocate string with kmem accordingly to format. 495 */ 496 char * 497 kmem_asprintf(const char *fmt, ...) 498 { 499 int size __diagused, len; 500 va_list va; 501 char *str; 502 503 va_start(va, fmt); 504 len = vsnprintf(NULL, 0, fmt, va); 505 va_end(va); 506 507 str = kmem_alloc(len + 1, KM_SLEEP); 508 509 va_start(va, fmt); 510 size = vsnprintf(str, len + 1, fmt, va); 511 va_end(va); 512 513 KASSERT(size == len); 514 515 return str; 516 } 517 518 /* ------------------ DEBUG / DIAGNOSTIC ------------------ */ 519 520 #if defined(KMEM_POISON) || defined(KMEM_REDZONE) 521 #if defined(_LP64) 522 #define PRIME 0x9e37fffffffc0000UL 523 #else /* defined(_LP64) */ 524 #define PRIME 0x9e3779b1 525 #endif /* defined(_LP64) */ 526 527 static inline uint8_t 528 kmem_pattern_generate(const void *p) 529 { 530 return (uint8_t)(((uintptr_t)p) * PRIME 531 >> ((sizeof(uintptr_t) - sizeof(uint8_t))) * CHAR_BIT); 532 } 533 #endif /* defined(KMEM_POISON) || defined(KMEM_REDZONE) */ 534 535 #if defined(KMEM_POISON) 536 static int 537 kmem_poison_ctor(void *arg, void *obj, int flag) 538 { 539 size_t sz = (size_t)arg; 540 541 kmem_poison_fill(obj, sz); 542 543 return 0; 544 } 545 546 static void 547 kmem_poison_fill(void *p, size_t sz) 548 { 549 uint8_t *cp; 550 const uint8_t *ep; 551 552 cp = p; 553 ep = cp + sz; 554 while (cp < ep) { 555 *cp = kmem_pattern_generate(cp); 556 cp++; 557 } 558 } 559 560 static void 561 kmem_poison_check(void *p, size_t sz) 562 { 563 uint8_t *cp; 564 const uint8_t *ep; 565 566 cp = p; 567 ep = cp + sz; 568 while (cp < ep) { 569 const uint8_t expected = kmem_pattern_generate(cp); 570 571 if (*cp != expected) { 572 panic("%s: %p: 0x%02x != 0x%02x\n", 573 __func__, cp, *cp, expected); 574 } 575 cp++; 576 } 577 } 578 #endif /* defined(KMEM_POISON) */ 579 580 #if defined(KMEM_SIZE) 581 static void 582 kmem_size_set(void *p, size_t sz) 583 { 584 struct kmem_header *hd; 585 hd = (struct kmem_header *)p; 586 hd->size = sz; 587 } 588 589 static void 590 kmem_size_check(void *p, size_t sz) 591 { 592 struct kmem_header *hd; 593 size_t hsz; 594 595 hd = (struct kmem_header *)p; 596 hsz = hd->size; 597 598 if (hsz != sz) { 599 panic("kmem_free(%p, %zu) != allocated size %zu", 600 (const uint8_t *)p + SIZE_SIZE, sz, hsz); 601 } 602 } 603 #endif /* defined(KMEM_SIZE) */ 604 605 #if defined(KMEM_REDZONE) 606 #define STATIC_BYTE 0xFE 607 CTASSERT(REDZONE_SIZE > 1); 608 static void 609 kmem_redzone_fill(void *p, size_t sz) 610 { 611 uint8_t *cp, pat; 612 const uint8_t *ep; 613 614 cp = (uint8_t *)p + sz; 615 ep = cp + REDZONE_SIZE; 616 617 /* 618 * We really don't want the first byte of the red zone to be '\0'; 619 * an off-by-one in a string may not be properly detected. 620 */ 621 pat = kmem_pattern_generate(cp); 622 *cp = (pat == '\0') ? STATIC_BYTE: pat; 623 cp++; 624 625 while (cp < ep) { 626 *cp = kmem_pattern_generate(cp); 627 cp++; 628 } 629 } 630 631 static void 632 kmem_redzone_check(void *p, size_t sz) 633 { 634 uint8_t *cp, pat, expected; 635 const uint8_t *ep; 636 637 cp = (uint8_t *)p + sz; 638 ep = cp + REDZONE_SIZE; 639 640 pat = kmem_pattern_generate(cp); 641 expected = (pat == '\0') ? STATIC_BYTE: pat; 642 if (expected != *cp) { 643 panic("%s: %p: 0x%02x != 0x%02x\n", 644 __func__, cp, *cp, expected); 645 } 646 cp++; 647 648 while (cp < ep) { 649 expected = kmem_pattern_generate(cp); 650 if (*cp != expected) { 651 panic("%s: %p: 0x%02x != 0x%02x\n", 652 __func__, cp, *cp, expected); 653 } 654 cp++; 655 } 656 } 657 #endif /* defined(KMEM_REDZONE) */ 658 659 660 #if defined(KMEM_GUARD) 661 /* 662 * The ultimate memory allocator for debugging, baby. It tries to catch: 663 * 664 * 1. Overflow, in realtime. A guard page sits immediately after the 665 * requested area; a read/write overflow therefore triggers a page 666 * fault. 667 * 2. Invalid pointer/size passed, at free. A kmem_header structure sits 668 * just before the requested area, and holds the allocated size. Any 669 * difference with what is given at free triggers a panic. 670 * 3. Underflow, at free. If an underflow occurs, the kmem header will be 671 * modified, and 2. will trigger a panic. 672 * 4. Use-after-free. When freeing, the memory is unmapped, and depending 673 * on the value of kmem_guard_depth, the kernel will more or less delay 674 * the recycling of that memory. Which means that any ulterior read/write 675 * access to the memory will trigger a page fault, given it hasn't been 676 * recycled yet. 677 */ 678 679 #include <sys/atomic.h> 680 #include <uvm/uvm.h> 681 682 static bool 683 kmem_guard_init(struct kmem_guard *kg, u_int depth, vmem_t *vm) 684 { 685 vaddr_t va; 686 687 /* If not enabled, we have nothing to do. */ 688 if (depth == 0) { 689 return false; 690 } 691 depth = roundup(depth, PAGE_SIZE / sizeof(void *)); 692 KASSERT(depth != 0); 693 694 /* 695 * Allocate fifo. 696 */ 697 va = uvm_km_alloc(kernel_map, depth * sizeof(void *), PAGE_SIZE, 698 UVM_KMF_WIRED | UVM_KMF_ZERO); 699 if (va == 0) { 700 return false; 701 } 702 703 /* 704 * Init object. 705 */ 706 kg->kg_vmem = vm; 707 kg->kg_fifo = (void *)va; 708 kg->kg_depth = depth; 709 kg->kg_rotor = 0; 710 711 printf("kmem_guard(%p): depth %d\n", kg, depth); 712 return true; 713 } 714 715 static void * 716 kmem_guard_alloc(struct kmem_guard *kg, size_t requested_size, bool waitok) 717 { 718 struct vm_page *pg; 719 vm_flag_t flags; 720 vmem_addr_t va; 721 vaddr_t loopva; 722 vsize_t loopsize; 723 size_t size; 724 void **p; 725 726 /* 727 * Compute the size: take the kmem header into account, and add a guard 728 * page at the end. 729 */ 730 size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE; 731 732 /* Allocate pages of kernel VA, but do not map anything in yet. */ 733 flags = VM_BESTFIT | (waitok ? VM_SLEEP : VM_NOSLEEP); 734 if (vmem_alloc(kg->kg_vmem, size, flags, &va) != 0) { 735 return NULL; 736 } 737 738 loopva = va; 739 loopsize = size - PAGE_SIZE; 740 741 while (loopsize) { 742 pg = uvm_pagealloc(NULL, loopva, NULL, 0); 743 if (__predict_false(pg == NULL)) { 744 if (waitok) { 745 uvm_wait("kmem_guard"); 746 continue; 747 } else { 748 uvm_km_pgremove_intrsafe(kernel_map, va, 749 va + size); 750 vmem_free(kg->kg_vmem, va, size); 751 return NULL; 752 } 753 } 754 755 pg->flags &= ~PG_BUSY; /* new page */ 756 UVM_PAGE_OWN(pg, NULL); 757 pmap_kenter_pa(loopva, VM_PAGE_TO_PHYS(pg), 758 VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE); 759 760 loopva += PAGE_SIZE; 761 loopsize -= PAGE_SIZE; 762 } 763 764 pmap_update(pmap_kernel()); 765 766 /* 767 * Offset the returned pointer so that the unmapped guard page sits 768 * immediately after the returned object. 769 */ 770 p = (void **)((va + (size - PAGE_SIZE) - requested_size) & ~(uintptr_t)ALIGNBYTES); 771 kmem_size_set((uint8_t *)p - SIZE_SIZE, requested_size); 772 return (void *)p; 773 } 774 775 static void 776 kmem_guard_free(struct kmem_guard *kg, size_t requested_size, void *p) 777 { 778 vaddr_t va; 779 u_int rotor; 780 size_t size; 781 uint8_t *ptr; 782 783 ptr = (uint8_t *)p - SIZE_SIZE; 784 kmem_size_check(ptr, requested_size); 785 va = trunc_page((vaddr_t)ptr); 786 size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE; 787 788 KASSERT(pmap_extract(pmap_kernel(), va, NULL)); 789 KASSERT(!pmap_extract(pmap_kernel(), va + (size - PAGE_SIZE), NULL)); 790 791 /* 792 * Unmap and free the pages. The last one is never allocated. 793 */ 794 uvm_km_pgremove_intrsafe(kernel_map, va, va + size); 795 pmap_update(pmap_kernel()); 796 797 #if 0 798 /* 799 * XXX: Here, we need to atomically register the va and its size in the 800 * fifo. 801 */ 802 803 /* 804 * Put the VA allocation into the list and swap an old one out to free. 805 * This behaves mostly like a fifo. 806 */ 807 rotor = atomic_inc_uint_nv(&kg->kg_rotor) % kg->kg_depth; 808 va = (vaddr_t)atomic_swap_ptr(&kg->kg_fifo[rotor], (void *)va); 809 if (va != 0) { 810 vmem_free(kg->kg_vmem, va, size); 811 } 812 #else 813 (void)rotor; 814 vmem_free(kg->kg_vmem, va, size); 815 #endif 816 } 817 818 #endif /* defined(KMEM_GUARD) */ 819