1 /*- 2 * Copyright (c) 2005, Bosko Milekic <bmilekic@FreeBSD.org>. 3 * Copyright (c) 2010 Isilon Systems, Inc. (http://www.isilon.com/) 4 * All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice unmodified, this list of conditions, and the following 11 * 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 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 */ 27 28 #include <sys/cdefs.h> 29 __FBSDID("$FreeBSD$"); 30 31 /* 32 * MemGuard is a simple replacement allocator for debugging only 33 * which provides ElectricFence-style memory barrier protection on 34 * objects being allocated, and is used to detect tampering-after-free 35 * scenarios. 36 * 37 * See the memguard(9) man page for more information on using MemGuard. 38 */ 39 40 #include "opt_vm.h" 41 42 #include <sys/param.h> 43 #include <sys/systm.h> 44 #include <sys/kernel.h> 45 #include <sys/types.h> 46 #include <sys/queue.h> 47 #include <sys/lock.h> 48 #include <sys/mutex.h> 49 #include <sys/malloc.h> 50 #include <sys/sysctl.h> 51 #include <sys/vmem.h> 52 53 #include <vm/vm.h> 54 #include <vm/uma.h> 55 #include <vm/vm_param.h> 56 #include <vm/vm_page.h> 57 #include <vm/vm_map.h> 58 #include <vm/vm_object.h> 59 #include <vm/vm_kern.h> 60 #include <vm/vm_extern.h> 61 #include <vm/uma_int.h> 62 #include <vm/memguard.h> 63 64 static SYSCTL_NODE(_vm, OID_AUTO, memguard, CTLFLAG_RW, NULL, "MemGuard data"); 65 /* 66 * The vm_memguard_divisor variable controls how much of kmem_map should be 67 * reserved for MemGuard. 68 */ 69 static u_int vm_memguard_divisor; 70 SYSCTL_UINT(_vm_memguard, OID_AUTO, divisor, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, 71 &vm_memguard_divisor, 72 0, "(kmem_size/memguard_divisor) == memguard submap size"); 73 74 /* 75 * Short description (ks_shortdesc) of memory type to monitor. 76 */ 77 static char vm_memguard_desc[128] = ""; 78 static struct malloc_type *vm_memguard_mtype = NULL; 79 TUNABLE_STR("vm.memguard.desc", vm_memguard_desc, sizeof(vm_memguard_desc)); 80 static int 81 memguard_sysctl_desc(SYSCTL_HANDLER_ARGS) 82 { 83 char desc[sizeof(vm_memguard_desc)]; 84 int error; 85 86 strlcpy(desc, vm_memguard_desc, sizeof(desc)); 87 error = sysctl_handle_string(oidp, desc, sizeof(desc), req); 88 if (error != 0 || req->newptr == NULL) 89 return (error); 90 91 mtx_lock(&malloc_mtx); 92 /* If mtp is NULL, it will be initialized in memguard_cmp() */ 93 vm_memguard_mtype = malloc_desc2type(desc); 94 strlcpy(vm_memguard_desc, desc, sizeof(vm_memguard_desc)); 95 mtx_unlock(&malloc_mtx); 96 return (error); 97 } 98 SYSCTL_PROC(_vm_memguard, OID_AUTO, desc, 99 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0, 100 memguard_sysctl_desc, "A", "Short description of memory type to monitor"); 101 102 static vm_offset_t memguard_cursor; 103 static vm_offset_t memguard_base; 104 static vm_size_t memguard_mapsize; 105 static vm_size_t memguard_physlimit; 106 static u_long memguard_wasted; 107 static u_long memguard_wrap; 108 static u_long memguard_succ; 109 static u_long memguard_fail_kva; 110 static u_long memguard_fail_pgs; 111 112 SYSCTL_ULONG(_vm_memguard, OID_AUTO, cursor, CTLFLAG_RD, 113 &memguard_cursor, 0, "MemGuard cursor"); 114 SYSCTL_ULONG(_vm_memguard, OID_AUTO, mapsize, CTLFLAG_RD, 115 &memguard_mapsize, 0, "MemGuard private arena size"); 116 SYSCTL_ULONG(_vm_memguard, OID_AUTO, phys_limit, CTLFLAG_RD, 117 &memguard_physlimit, 0, "Limit on MemGuard memory consumption"); 118 SYSCTL_ULONG(_vm_memguard, OID_AUTO, wasted, CTLFLAG_RD, 119 &memguard_wasted, 0, "Excess memory used through page promotion"); 120 SYSCTL_ULONG(_vm_memguard, OID_AUTO, wrapcnt, CTLFLAG_RD, 121 &memguard_wrap, 0, "MemGuard cursor wrap count"); 122 SYSCTL_ULONG(_vm_memguard, OID_AUTO, numalloc, CTLFLAG_RD, 123 &memguard_succ, 0, "Count of successful MemGuard allocations"); 124 SYSCTL_ULONG(_vm_memguard, OID_AUTO, fail_kva, CTLFLAG_RD, 125 &memguard_fail_kva, 0, "MemGuard failures due to lack of KVA"); 126 SYSCTL_ULONG(_vm_memguard, OID_AUTO, fail_pgs, CTLFLAG_RD, 127 &memguard_fail_pgs, 0, "MemGuard failures due to lack of pages"); 128 129 #define MG_GUARD_AROUND 0x001 130 #define MG_GUARD_ALLLARGE 0x002 131 #define MG_GUARD_NOFREE 0x004 132 static int memguard_options = MG_GUARD_AROUND; 133 SYSCTL_INT(_vm_memguard, OID_AUTO, options, CTLFLAG_RWTUN, 134 &memguard_options, 0, 135 "MemGuard options:\n" 136 "\t0x001 - add guard pages around each allocation\n" 137 "\t0x002 - always use MemGuard for allocations over a page\n" 138 "\t0x004 - guard uma(9) zones with UMA_ZONE_NOFREE flag"); 139 140 static u_int memguard_minsize; 141 static u_long memguard_minsize_reject; 142 SYSCTL_UINT(_vm_memguard, OID_AUTO, minsize, CTLFLAG_RW, 143 &memguard_minsize, 0, "Minimum size for page promotion"); 144 SYSCTL_ULONG(_vm_memguard, OID_AUTO, minsize_reject, CTLFLAG_RD, 145 &memguard_minsize_reject, 0, "# times rejected for size"); 146 147 static u_int memguard_frequency; 148 static u_long memguard_frequency_hits; 149 SYSCTL_UINT(_vm_memguard, OID_AUTO, frequency, CTLFLAG_RWTUN, 150 &memguard_frequency, 0, "Times in 100000 that MemGuard will randomly run"); 151 SYSCTL_ULONG(_vm_memguard, OID_AUTO, frequency_hits, CTLFLAG_RD, 152 &memguard_frequency_hits, 0, "# times MemGuard randomly chose"); 153 154 155 /* 156 * Return a fudged value to be used for vm_kmem_size for allocating 157 * the kmem_map. The memguard memory will be a submap. 158 */ 159 unsigned long 160 memguard_fudge(unsigned long km_size, const struct vm_map *parent_map) 161 { 162 u_long mem_pgs, parent_size; 163 164 vm_memguard_divisor = 10; 165 TUNABLE_INT_FETCH("vm.memguard.divisor", &vm_memguard_divisor); 166 167 parent_size = vm_map_max(parent_map) - vm_map_min(parent_map) + 168 PAGE_SIZE; 169 /* Pick a conservative value if provided value sucks. */ 170 if ((vm_memguard_divisor <= 0) || 171 ((parent_size / vm_memguard_divisor) == 0)) 172 vm_memguard_divisor = 10; 173 /* 174 * Limit consumption of physical pages to 175 * 1/vm_memguard_divisor of system memory. If the KVA is 176 * smaller than this then the KVA limit comes into play first. 177 * This prevents memguard's page promotions from completely 178 * using up memory, since most malloc(9) calls are sub-page. 179 */ 180 mem_pgs = vm_cnt.v_page_count; 181 memguard_physlimit = (mem_pgs / vm_memguard_divisor) * PAGE_SIZE; 182 /* 183 * We want as much KVA as we can take safely. Use at most our 184 * allotted fraction of the parent map's size. Limit this to 185 * twice the physical memory to avoid using too much memory as 186 * pagetable pages (size must be multiple of PAGE_SIZE). 187 */ 188 memguard_mapsize = round_page(parent_size / vm_memguard_divisor); 189 if (memguard_mapsize / (2 * PAGE_SIZE) > mem_pgs) 190 memguard_mapsize = mem_pgs * 2 * PAGE_SIZE; 191 if (km_size + memguard_mapsize > parent_size) 192 memguard_mapsize = 0; 193 return (km_size + memguard_mapsize); 194 } 195 196 /* 197 * Initialize the MemGuard mock allocator. All objects from MemGuard come 198 * out of a single VM map (contiguous chunk of address space). 199 */ 200 void 201 memguard_init(vmem_t *parent) 202 { 203 vm_offset_t base; 204 205 vmem_alloc(parent, memguard_mapsize, M_BESTFIT | M_WAITOK, &base); 206 vmem_init(memguard_arena, "memguard arena", base, memguard_mapsize, 207 PAGE_SIZE, 0, M_WAITOK); 208 memguard_cursor = base; 209 memguard_base = base; 210 211 printf("MEMGUARD DEBUGGING ALLOCATOR INITIALIZED:\n"); 212 printf("\tMEMGUARD map base: 0x%lx\n", (u_long)base); 213 printf("\tMEMGUARD map size: %jd KBytes\n", 214 (uintmax_t)memguard_mapsize >> 10); 215 } 216 217 /* 218 * Run things that can't be done as early as memguard_init(). 219 */ 220 static void 221 memguard_sysinit(void) 222 { 223 struct sysctl_oid_list *parent; 224 225 parent = SYSCTL_STATIC_CHILDREN(_vm_memguard); 226 227 SYSCTL_ADD_UAUTO(NULL, parent, OID_AUTO, "mapstart", CTLFLAG_RD, 228 &memguard_base, "MemGuard KVA base"); 229 SYSCTL_ADD_UAUTO(NULL, parent, OID_AUTO, "maplimit", CTLFLAG_RD, 230 &memguard_mapsize, "MemGuard KVA size"); 231 #if 0 232 SYSCTL_ADD_ULONG(NULL, parent, OID_AUTO, "mapused", CTLFLAG_RD, 233 &memguard_map->size, "MemGuard KVA used"); 234 #endif 235 } 236 SYSINIT(memguard, SI_SUB_KLD, SI_ORDER_ANY, memguard_sysinit, NULL); 237 238 /* 239 * v2sizep() converts a virtual address of the first page allocated for 240 * an item to a pointer to u_long recording the size of the original 241 * allocation request. 242 * 243 * This routine is very similar to those defined by UMA in uma_int.h. 244 * The difference is that this routine stores the originally allocated 245 * size in one of the page's fields that is unused when the page is 246 * wired rather than the object field, which is used. 247 */ 248 static u_long * 249 v2sizep(vm_offset_t va) 250 { 251 vm_paddr_t pa; 252 struct vm_page *p; 253 254 pa = pmap_kextract(va); 255 if (pa == 0) 256 panic("MemGuard detected double-free of %p", (void *)va); 257 p = PHYS_TO_VM_PAGE(pa); 258 KASSERT(p->wire_count != 0 && p->queue == PQ_NONE, 259 ("MEMGUARD: Expected wired page %p in vtomgfifo!", p)); 260 return (&p->plinks.memguard.p); 261 } 262 263 static u_long * 264 v2sizev(vm_offset_t va) 265 { 266 vm_paddr_t pa; 267 struct vm_page *p; 268 269 pa = pmap_kextract(va); 270 if (pa == 0) 271 panic("MemGuard detected double-free of %p", (void *)va); 272 p = PHYS_TO_VM_PAGE(pa); 273 KASSERT(p->wire_count != 0 && p->queue == PQ_NONE, 274 ("MEMGUARD: Expected wired page %p in vtomgfifo!", p)); 275 return (&p->plinks.memguard.v); 276 } 277 278 /* 279 * Allocate a single object of specified size with specified flags 280 * (either M_WAITOK or M_NOWAIT). 281 */ 282 void * 283 memguard_alloc(unsigned long req_size, int flags) 284 { 285 vm_offset_t addr; 286 u_long size_p, size_v; 287 int do_guard, rv; 288 289 size_p = round_page(req_size); 290 if (size_p == 0) 291 return (NULL); 292 /* 293 * To ensure there are holes on both sides of the allocation, 294 * request 2 extra pages of KVA. We will only actually add a 295 * vm_map_entry and get pages for the original request. Save 296 * the value of memguard_options so we have a consistent 297 * value. 298 */ 299 size_v = size_p; 300 do_guard = (memguard_options & MG_GUARD_AROUND) != 0; 301 if (do_guard) 302 size_v += 2 * PAGE_SIZE; 303 304 /* 305 * When we pass our memory limit, reject sub-page allocations. 306 * Page-size and larger allocations will use the same amount 307 * of physical memory whether we allocate or hand off to 308 * uma_large_alloc(), so keep those. 309 */ 310 if (vmem_size(memguard_arena, VMEM_ALLOC) >= memguard_physlimit && 311 req_size < PAGE_SIZE) { 312 addr = (vm_offset_t)NULL; 313 memguard_fail_pgs++; 314 goto out; 315 } 316 /* 317 * Keep a moving cursor so we don't recycle KVA as long as 318 * possible. It's not perfect, since we don't know in what 319 * order previous allocations will be free'd, but it's simple 320 * and fast, and requires O(1) additional storage if guard 321 * pages are not used. 322 * 323 * XXX This scheme will lead to greater fragmentation of the 324 * map, unless vm_map_findspace() is tweaked. 325 */ 326 for (;;) { 327 if (vmem_xalloc(memguard_arena, size_v, 0, 0, 0, 328 memguard_cursor, VMEM_ADDR_MAX, 329 M_BESTFIT | M_NOWAIT, &addr) == 0) 330 break; 331 /* 332 * The map has no space. This may be due to 333 * fragmentation, or because the cursor is near the 334 * end of the map. 335 */ 336 if (memguard_cursor == memguard_base) { 337 memguard_fail_kva++; 338 addr = (vm_offset_t)NULL; 339 goto out; 340 } 341 memguard_wrap++; 342 memguard_cursor = memguard_base; 343 } 344 if (do_guard) 345 addr += PAGE_SIZE; 346 rv = kmem_back(kmem_object, addr, size_p, flags); 347 if (rv != KERN_SUCCESS) { 348 vmem_xfree(memguard_arena, addr, size_v); 349 memguard_fail_pgs++; 350 addr = (vm_offset_t)NULL; 351 goto out; 352 } 353 memguard_cursor = addr + size_v; 354 *v2sizep(trunc_page(addr)) = req_size; 355 *v2sizev(trunc_page(addr)) = size_v; 356 memguard_succ++; 357 if (req_size < PAGE_SIZE) { 358 memguard_wasted += (PAGE_SIZE - req_size); 359 if (do_guard) { 360 /* 361 * Align the request to 16 bytes, and return 362 * an address near the end of the page, to 363 * better detect array overrun. 364 */ 365 req_size = roundup2(req_size, 16); 366 addr += (PAGE_SIZE - req_size); 367 } 368 } 369 out: 370 return ((void *)addr); 371 } 372 373 int 374 is_memguard_addr(void *addr) 375 { 376 vm_offset_t a = (vm_offset_t)(uintptr_t)addr; 377 378 return (a >= memguard_base && a < memguard_base + memguard_mapsize); 379 } 380 381 /* 382 * Free specified single object. 383 */ 384 void 385 memguard_free(void *ptr) 386 { 387 vm_offset_t addr; 388 u_long req_size, size, sizev; 389 char *temp; 390 int i; 391 392 addr = trunc_page((uintptr_t)ptr); 393 req_size = *v2sizep(addr); 394 sizev = *v2sizev(addr); 395 size = round_page(req_size); 396 397 /* 398 * Page should not be guarded right now, so force a write. 399 * The purpose of this is to increase the likelihood of 400 * catching a double-free, but not necessarily a 401 * tamper-after-free (the second thread freeing might not 402 * write before freeing, so this forces it to and, 403 * subsequently, trigger a fault). 404 */ 405 temp = ptr; 406 for (i = 0; i < size; i += PAGE_SIZE) 407 temp[i] = 'M'; 408 409 /* 410 * This requires carnal knowledge of the implementation of 411 * kmem_free(), but since we've already replaced kmem_malloc() 412 * above, it's not really any worse. We want to use the 413 * vm_map lock to serialize updates to memguard_wasted, since 414 * we had the lock at increment. 415 */ 416 kmem_unback(kmem_object, addr, size); 417 if (sizev > size) 418 addr -= PAGE_SIZE; 419 vmem_xfree(memguard_arena, addr, sizev); 420 if (req_size < PAGE_SIZE) 421 memguard_wasted -= (PAGE_SIZE - req_size); 422 } 423 424 /* 425 * Re-allocate an allocation that was originally guarded. 426 */ 427 void * 428 memguard_realloc(void *addr, unsigned long size, struct malloc_type *mtp, 429 int flags) 430 { 431 void *newaddr; 432 u_long old_size; 433 434 /* 435 * Allocate the new block. Force the allocation to be guarded 436 * as the original may have been guarded through random 437 * chance, and that should be preserved. 438 */ 439 if ((newaddr = memguard_alloc(size, flags)) == NULL) 440 return (NULL); 441 442 /* Copy over original contents. */ 443 old_size = *v2sizep(trunc_page((uintptr_t)addr)); 444 bcopy(addr, newaddr, min(size, old_size)); 445 memguard_free(addr); 446 return (newaddr); 447 } 448 449 static int 450 memguard_cmp(unsigned long size) 451 { 452 453 if (size < memguard_minsize) { 454 memguard_minsize_reject++; 455 return (0); 456 } 457 if ((memguard_options & MG_GUARD_ALLLARGE) != 0 && size >= PAGE_SIZE) 458 return (1); 459 if (memguard_frequency > 0 && 460 (random() % 100000) < memguard_frequency) { 461 memguard_frequency_hits++; 462 return (1); 463 } 464 465 return (0); 466 } 467 468 int 469 memguard_cmp_mtp(struct malloc_type *mtp, unsigned long size) 470 { 471 472 if (memguard_cmp(size)) 473 return(1); 474 475 #if 1 476 /* 477 * The safest way of comparsion is to always compare short description 478 * string of memory type, but it is also the slowest way. 479 */ 480 return (strcmp(mtp->ks_shortdesc, vm_memguard_desc) == 0); 481 #else 482 /* 483 * If we compare pointers, there are two possible problems: 484 * 1. Memory type was unloaded and new memory type was allocated at the 485 * same address. 486 * 2. Memory type was unloaded and loaded again, but allocated at a 487 * different address. 488 */ 489 if (vm_memguard_mtype != NULL) 490 return (mtp == vm_memguard_mtype); 491 if (strcmp(mtp->ks_shortdesc, vm_memguard_desc) == 0) { 492 vm_memguard_mtype = mtp; 493 return (1); 494 } 495 return (0); 496 #endif 497 } 498 499 int 500 memguard_cmp_zone(uma_zone_t zone) 501 { 502 503 if ((memguard_options & MG_GUARD_NOFREE) == 0 && 504 zone->uz_flags & UMA_ZONE_NOFREE) 505 return (0); 506 507 if (memguard_cmp(zone->uz_size)) 508 return (1); 509 510 /* 511 * The safest way of comparsion is to always compare zone name, 512 * but it is also the slowest way. 513 */ 514 return (strcmp(zone->uz_name, vm_memguard_desc) == 0); 515 } 516