memguard.c revision 211194
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: head/sys/vm/memguard.c 211194 2010-08-11 22:10:37Z mdf $"); 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 <sys/param.h> 41#include <sys/systm.h> 42#include <sys/kernel.h> 43#include <sys/types.h> 44#include <sys/queue.h> 45#include <sys/lock.h> 46#include <sys/mutex.h> 47#include <sys/malloc.h> 48#include <sys/sysctl.h> 49 50#include <vm/vm.h> 51#include <vm/uma.h> 52#include <vm/vm_param.h> 53#include <vm/vm_page.h> 54#include <vm/vm_map.h> 55#include <vm/vm_object.h> 56#include <vm/vm_extern.h> 57#include <vm/memguard.h> 58 59SYSCTL_NODE(_vm, OID_AUTO, memguard, CTLFLAG_RW, NULL, "MemGuard data"); 60/* 61 * The vm_memguard_divisor variable controls how much of kmem_map should be 62 * reserved for MemGuard. 63 */ 64static u_int vm_memguard_divisor; 65SYSCTL_UINT(_vm_memguard, OID_AUTO, divisor, CTLFLAG_RDTUN, 66 &vm_memguard_divisor, 67 0, "(kmem_size/memguard_divisor) == memguard submap size"); 68 69/* 70 * Short description (ks_shortdesc) of memory type to monitor. 71 */ 72static char vm_memguard_desc[128] = ""; 73static struct malloc_type *vm_memguard_mtype = NULL; 74TUNABLE_STR("vm.memguard.desc", vm_memguard_desc, sizeof(vm_memguard_desc)); 75static int 76memguard_sysctl_desc(SYSCTL_HANDLER_ARGS) 77{ 78 char desc[sizeof(vm_memguard_desc)]; 79 int error; 80 81 strlcpy(desc, vm_memguard_desc, sizeof(desc)); 82 error = sysctl_handle_string(oidp, desc, sizeof(desc), req); 83 if (error != 0 || req->newptr == NULL) 84 return (error); 85 86 mtx_lock(&malloc_mtx); 87 /* 88 * If mtp is NULL, it will be initialized in memguard_cmp(). 89 */ 90 vm_memguard_mtype = malloc_desc2type(desc); 91 strlcpy(vm_memguard_desc, desc, sizeof(vm_memguard_desc)); 92 mtx_unlock(&malloc_mtx); 93 return (error); 94} 95SYSCTL_PROC(_vm_memguard, OID_AUTO, desc, 96 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0, 97 memguard_sysctl_desc, "A", "Short description of memory type to monitor"); 98 99static vm_map_t memguard_map = NULL; 100static vm_offset_t memguard_cursor; 101static vm_size_t memguard_mapsize; 102static vm_size_t memguard_physlimit; 103static u_long memguard_wasted; 104static u_long memguard_wrap; 105static u_long memguard_succ; 106static u_long memguard_fail_kva; 107static u_long memguard_fail_pgs; 108 109SYSCTL_ULONG(_vm_memguard, OID_AUTO, cursor, CTLFLAG_RD, 110 &memguard_cursor, 0, "MemGuard cursor"); 111SYSCTL_ULONG(_vm_memguard, OID_AUTO, mapsize, CTLFLAG_RD, 112 &memguard_mapsize, 0, "MemGuard private vm_map size"); 113SYSCTL_ULONG(_vm_memguard, OID_AUTO, phys_limit, CTLFLAG_RD, 114 &memguard_physlimit, 0, "Limit on MemGuard memory consumption"); 115SYSCTL_ULONG(_vm_memguard, OID_AUTO, wasted, CTLFLAG_RD, 116 &memguard_wasted, 0, "Excess memory used through page promotion"); 117SYSCTL_ULONG(_vm_memguard, OID_AUTO, wrapcnt, CTLFLAG_RD, 118 &memguard_wrap, 0, "MemGuard cursor wrap count"); 119SYSCTL_ULONG(_vm_memguard, OID_AUTO, numalloc, CTLFLAG_RD, 120 &memguard_succ, 0, "Count of successful MemGuard allocations"); 121SYSCTL_ULONG(_vm_memguard, OID_AUTO, fail_kva, CTLFLAG_RD, 122 &memguard_fail_kva, 0, "MemGuard failures due to lack of KVA"); 123SYSCTL_ULONG(_vm_memguard, OID_AUTO, fail_pgs, CTLFLAG_RD, 124 &memguard_fail_pgs, 0, "MemGuard failures due to lack of pages"); 125 126#define MG_GUARD 0x001 127#define MG_ALLLARGE 0x002 128static int memguard_options = MG_GUARD; 129TUNABLE_INT("vm.memguard.options", &memguard_options); 130SYSCTL_INT(_vm_memguard, OID_AUTO, options, CTLFLAG_RW, 131 &memguard_options, 0, 132 "MemGuard options:\n" 133 "\t0x001 - add guard pages around each allocation\n" 134 "\t0x002 - always use MemGuard for allocations over a page"); 135 136static u_int memguard_minsize; 137static u_long memguard_minsize_reject; 138SYSCTL_UINT(_vm_memguard, OID_AUTO, minsize, CTLFLAG_RW, 139 &memguard_minsize, 0, "Minimum size for page promotion"); 140SYSCTL_ULONG(_vm_memguard, OID_AUTO, minsize_reject, CTLFLAG_RD, 141 &memguard_minsize_reject, 0, "# times rejected for size"); 142 143static u_int memguard_frequency; 144static u_long memguard_frequency_hits; 145TUNABLE_INT("vm.memguard.frequency", &memguard_frequency); 146SYSCTL_UINT(_vm_memguard, OID_AUTO, frequency, CTLFLAG_RW, 147 &memguard_frequency, 0, "Times in 100000 that MemGuard will randomly run"); 148SYSCTL_ULONG(_vm_memguard, OID_AUTO, frequency_hits, CTLFLAG_RD, 149 &memguard_frequency_hits, 0, "# times MemGuard randomly chose"); 150 151 152/* 153 * Return a fudged value to be used for vm_kmem_size for allocating 154 * the kmem_map. The memguard memory will be a submap. 155 */ 156unsigned long 157memguard_fudge(unsigned long km_size, unsigned long km_max) 158{ 159 u_long mem_pgs = cnt.v_page_count; 160 161 vm_memguard_divisor = 10; 162 TUNABLE_INT_FETCH("vm.memguard.divisor", &vm_memguard_divisor); 163 164 /* Pick a conservative value if provided value sucks. */ 165 if ((vm_memguard_divisor <= 0) || 166 ((km_size / vm_memguard_divisor) == 0)) 167 vm_memguard_divisor = 10; 168 /* 169 * Limit consumption of physical pages to 170 * 1/vm_memguard_divisor of system memory. If the KVA is 171 * smaller than this then the KVA limit comes into play first. 172 * This prevents memguard's page promotions from completely 173 * using up memory, since most malloc(9) calls are sub-page. 174 */ 175 memguard_physlimit = (mem_pgs / vm_memguard_divisor) * PAGE_SIZE; 176 /* 177 * We want as much KVA as we can take safely. Use at most our 178 * allotted fraction of kmem_max. Limit this to twice the 179 * physical memory to avoid using too much memory as pagetable 180 * pages. 181 */ 182 memguard_mapsize = km_max / vm_memguard_divisor; 183 /* size must be multiple of PAGE_SIZE */ 184 memguard_mapsize = round_page(memguard_mapsize); 185 if (memguard_mapsize / (2 * PAGE_SIZE) > mem_pgs) 186 memguard_mapsize = mem_pgs * 2 * PAGE_SIZE; 187 if (km_size + memguard_mapsize > km_max) 188 return (km_max); 189 return (km_size + memguard_mapsize); 190} 191 192/* 193 * Initialize the MemGuard mock allocator. All objects from MemGuard come 194 * out of a single VM map (contiguous chunk of address space). 195 */ 196void 197memguard_init(vm_map_t parent_map) 198{ 199 vm_offset_t base, limit; 200 201 memguard_map = kmem_suballoc(parent_map, &base, &limit, 202 memguard_mapsize, FALSE); 203 memguard_map->system_map = 1; 204 KASSERT(memguard_mapsize == limit - base, 205 ("Expected %lu, got %lu", (u_long)memguard_mapsize, 206 (u_long)(limit - base))); 207 memguard_cursor = base; 208 209 printf("MEMGUARD DEBUGGING ALLOCATOR INITIALIZED:\n"); 210 printf("\tMEMGUARD map base: 0x%lx\n", (u_long)base); 211 printf("\tMEMGUARD map limit: 0x%lx\n", (u_long)limit); 212 printf("\tMEMGUARD map size: %jd KBytes\n", 213 (uintmax_t)memguard_mapsize >> 10); 214} 215 216/* 217 * Run things that can't be done as early as memguard_init(). 218 */ 219static void 220memguard_sysinit(void) 221{ 222 struct sysctl_oid_list *parent; 223 224 parent = SYSCTL_STATIC_CHILDREN(_vm_memguard); 225 226 SYSCTL_ADD_ULONG(NULL, parent, OID_AUTO, "mapstart", CTLFLAG_RD, 227 &memguard_map->min_offset, "MemGuard KVA base"); 228 SYSCTL_ADD_ULONG(NULL, parent, OID_AUTO, "maplimit", CTLFLAG_RD, 229 &memguard_map->max_offset, "MemGuard KVA end"); 230 SYSCTL_ADD_ULONG(NULL, parent, OID_AUTO, "mapused", CTLFLAG_RD, 231 &memguard_map->size, "MemGuard KVA used"); 232} 233SYSINIT(memguard, SI_SUB_KLD, SI_ORDER_ANY, memguard_sysinit, NULL); 234 235/* 236 * v2sizep() converts a virtual address of the first page allocated for 237 * an item to a pointer to u_long recording the size of the original 238 * allocation request. 239 * 240 * This routine is very similar to those defined by UMA in uma_int.h. 241 * The difference is that this routine stores the originally allocated 242 * size in one of the page's fields that is unused when the page is 243 * wired rather than the object field, which is used. 244 */ 245static u_long * 246v2sizep(vm_offset_t va) 247{ 248 struct vm_page *p; 249 250 p = PHYS_TO_VM_PAGE(pmap_kextract(va)); 251 KASSERT(p->wire_count != 0 && p->queue == PQ_NONE, 252 ("MEMGUARD: Expected wired page %p in vtomgfifo!", p)); 253 return ((u_long *)&p->pageq.tqe_next); 254} 255 256/* 257 * Allocate a single object of specified size with specified flags 258 * (either M_WAITOK or M_NOWAIT). 259 */ 260void * 261memguard_alloc(unsigned long req_size, int flags) 262{ 263 vm_offset_t addr; 264 u_long size_p, size_v; 265 int do_guard, rv; 266 267 size_p = round_page(req_size); 268 if (size_p == 0) 269 return (NULL); 270 /* 271 * To ensure there are holes on both sides of the allocation, 272 * request 2 extra pages of KVA. We will only actually add a 273 * vm_map_entry and get pages for the original request. Save 274 * the value of memguard_options so we have a consistent 275 * value. 276 */ 277 size_v = size_p; 278 do_guard = (memguard_options & MG_GUARD) != 0; 279 if (do_guard) 280 size_v += 2 * PAGE_SIZE; 281 282 vm_map_lock(memguard_map); 283 /* 284 * When we pass our memory limit, reject sub-page allocations. 285 * Page-size and larger allocations will use the same amount 286 * of physical memory whether we allocate or hand off to 287 * uma_large_alloc(), so keep those. 288 */ 289 if (memguard_map->size >= memguard_physlimit && 290 req_size < PAGE_SIZE) { 291 addr = (vm_offset_t)NULL; 292 memguard_fail_pgs++; 293 goto out; 294 } 295 /* 296 * Keep a moving cursor so we don't recycle KVA as long as 297 * possible. It's not perfect, since we don't know in what 298 * order previous allocations will be free'd, but it's simple 299 * and fast, and requires O(1) additional storage if guard 300 * pages are not used. 301 * 302 * XXX This scheme will lead to greater fragmentation of the 303 * map, unless vm_map_findspace() is tweaked. 304 */ 305 for (;;) { 306 rv = vm_map_findspace(memguard_map, memguard_cursor, 307 size_v, &addr); 308 if (rv == KERN_SUCCESS) 309 break; 310 /* 311 * The map has no space. This may be due to 312 * fragmentation, or because the cursor is near the 313 * end of the map. 314 */ 315 if (memguard_cursor == vm_map_min(memguard_map)) { 316 memguard_fail_kva++; 317 addr = (vm_offset_t)NULL; 318 goto out; 319 } 320 memguard_wrap++; 321 memguard_cursor = vm_map_min(memguard_map); 322 } 323 if (do_guard) 324 addr += PAGE_SIZE; 325 rv = kmem_back(memguard_map, addr, size_p, flags); 326 if (rv != KERN_SUCCESS) { 327 memguard_fail_pgs++; 328 addr = (vm_offset_t)NULL; 329 goto out; 330 } 331 memguard_cursor = addr + size_p; 332 *v2sizep(trunc_page(addr)) = req_size; 333 memguard_succ++; 334 if (req_size < PAGE_SIZE) { 335 memguard_wasted += (PAGE_SIZE - req_size); 336 if (do_guard) { 337 /* 338 * Align the request to 16 bytes, and return 339 * an address near the end of the page, to 340 * better detect array overrun. 341 */ 342 req_size = roundup2(req_size, 16); 343 addr += (PAGE_SIZE - req_size); 344 } 345 } 346out: 347 vm_map_unlock(memguard_map); 348 return ((void *)addr); 349} 350 351int 352is_memguard_addr(void *addr) 353{ 354 vm_offset_t a = (vm_offset_t)(uintptr_t)addr; 355 356 return (a >= memguard_map->min_offset && a < memguard_map->max_offset); 357} 358 359/* 360 * Free specified single object. 361 */ 362void 363memguard_free(void *ptr) 364{ 365 vm_offset_t addr; 366 u_long req_size, size; 367 char *temp; 368 int i; 369 370 addr = trunc_page((uintptr_t)ptr); 371 req_size = *v2sizep(addr); 372 size = round_page(req_size); 373 374 /* 375 * Page should not be guarded right now, so force a write. 376 * The purpose of this is to increase the likelihood of 377 * catching a double-free, but not necessarily a 378 * tamper-after-free (the second thread freeing might not 379 * write before freeing, so this forces it to and, 380 * subsequently, trigger a fault). 381 */ 382 temp = ptr; 383 for (i = 0; i < size; i += PAGE_SIZE) 384 temp[i] = 'M'; 385 386 /* 387 * This requires carnal knowledge of the implementation of 388 * kmem_free(), but since we've already replaced kmem_malloc() 389 * above, it's not really any worse. We want to use the 390 * vm_map lock to serialize updates to memguard_wasted, since 391 * we had the lock at increment. 392 */ 393 vm_map_lock(memguard_map); 394 if (req_size < PAGE_SIZE) 395 memguard_wasted -= (PAGE_SIZE - req_size); 396 (void)vm_map_delete(memguard_map, addr, addr + size); 397 vm_map_unlock(memguard_map); 398} 399 400int 401memguard_cmp(struct malloc_type *mtp, unsigned long size) 402{ 403 404 if (size < memguard_minsize) { 405 memguard_minsize_reject++; 406 return (0); 407 } 408 if ((memguard_options & MG_ALLLARGE) != 0 && size >= PAGE_SIZE) 409 return (1); 410 if (memguard_frequency > 0 && 411 (random() % 100000) < memguard_frequency) { 412 memguard_frequency_hits++; 413 return (1); 414 } 415#if 1 416 /* 417 * The safest way of comparsion is to always compare short description 418 * string of memory type, but it is also the slowest way. 419 */ 420 return (strcmp(mtp->ks_shortdesc, vm_memguard_desc) == 0); 421#else 422 /* 423 * If we compare pointers, there are two possible problems: 424 * 1. Memory type was unloaded and new memory type was allocated at the 425 * same address. 426 * 2. Memory type was unloaded and loaded again, but allocated at a 427 * different address. 428 */ 429 if (vm_memguard_mtype != NULL) 430 return (mtp == vm_memguard_mtype); 431 if (strcmp(mtp->ks_shortdesc, vm_memguard_desc) == 0) { 432 vm_memguard_mtype = mtp; 433 return (1); 434 } 435 return (0); 436#endif 437} 438