2 * Copyright (c) 2005, Bosko Milekic <bmilekic@FreeBSD.org>.
3 * Copyright (c) 2010 Isilon Systems, Inc. (http://www.isilon.com/)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice unmodified, this list of conditions, and the following
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.
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.
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
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
37 * See the memguard(9) man page for more information on using MemGuard.
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>
48 #include <sys/mutex.h>
49 #include <sys/malloc.h>
50 #include <sys/sysctl.h>
54 #include <vm/vm_param.h>
55 #include <vm/vm_page.h>
56 #include <vm/vm_map.h>
57 #include <vm/vm_object.h>
58 #include <vm/vm_extern.h>
59 #include <vm/uma_int.h>
60 #include <vm/memguard.h>
62 static SYSCTL_NODE(_vm, OID_AUTO, memguard, CTLFLAG_RW, NULL, "MemGuard data");
64 * The vm_memguard_divisor variable controls how much of kmem_map should be
65 * reserved for MemGuard.
67 static u_int vm_memguard_divisor;
68 SYSCTL_UINT(_vm_memguard, OID_AUTO, divisor, CTLFLAG_RDTUN,
70 0, "(kmem_size/memguard_divisor) == memguard submap size");
73 * Short description (ks_shortdesc) of memory type to monitor.
75 static char vm_memguard_desc[128] = "";
76 static struct malloc_type *vm_memguard_mtype = NULL;
77 TUNABLE_STR("vm.memguard.desc", vm_memguard_desc, sizeof(vm_memguard_desc));
79 memguard_sysctl_desc(SYSCTL_HANDLER_ARGS)
81 char desc[sizeof(vm_memguard_desc)];
84 strlcpy(desc, vm_memguard_desc, sizeof(desc));
85 error = sysctl_handle_string(oidp, desc, sizeof(desc), req);
86 if (error != 0 || req->newptr == NULL)
89 mtx_lock(&malloc_mtx);
91 * 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);
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");
102 static vm_map_t memguard_map = NULL;
103 static vm_offset_t memguard_cursor;
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;
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 vm_map 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");
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 TUNABLE_INT("vm.memguard.options", &memguard_options);
134 SYSCTL_INT(_vm_memguard, OID_AUTO, options, CTLFLAG_RW,
135 &memguard_options, 0,
136 "MemGuard options:\n"
137 "\t0x001 - add guard pages around each allocation\n"
138 "\t0x002 - always use MemGuard for allocations over a page\n"
139 "\t0x004 - guard uma(9) zones with UMA_ZONE_NOFREE flag");
141 static u_int memguard_minsize;
142 static u_long memguard_minsize_reject;
143 SYSCTL_UINT(_vm_memguard, OID_AUTO, minsize, CTLFLAG_RW,
144 &memguard_minsize, 0, "Minimum size for page promotion");
145 SYSCTL_ULONG(_vm_memguard, OID_AUTO, minsize_reject, CTLFLAG_RD,
146 &memguard_minsize_reject, 0, "# times rejected for size");
148 static u_int memguard_frequency;
149 static u_long memguard_frequency_hits;
150 TUNABLE_INT("vm.memguard.frequency", &memguard_frequency);
151 SYSCTL_UINT(_vm_memguard, OID_AUTO, frequency, CTLFLAG_RW,
152 &memguard_frequency, 0, "Times in 100000 that MemGuard will randomly run");
153 SYSCTL_ULONG(_vm_memguard, OID_AUTO, frequency_hits, CTLFLAG_RD,
154 &memguard_frequency_hits, 0, "# times MemGuard randomly chose");
158 * Return a fudged value to be used for vm_kmem_size for allocating
159 * the kmem_map. The memguard memory will be a submap.
162 memguard_fudge(unsigned long km_size, unsigned long km_max)
164 u_long mem_pgs = cnt.v_page_count;
166 vm_memguard_divisor = 10;
167 TUNABLE_INT_FETCH("vm.memguard.divisor", &vm_memguard_divisor);
169 /* Pick a conservative value if provided value sucks. */
170 if ((vm_memguard_divisor <= 0) ||
171 ((km_size / vm_memguard_divisor) == 0))
172 vm_memguard_divisor = 10;
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.
180 memguard_physlimit = (mem_pgs / vm_memguard_divisor) * PAGE_SIZE;
182 * We want as much KVA as we can take safely. Use at most our
183 * allotted fraction of kmem_max. Limit this to twice the
184 * physical memory to avoid using too much memory as pagetable
187 memguard_mapsize = km_max / vm_memguard_divisor;
188 /* size must be multiple of PAGE_SIZE */
189 memguard_mapsize = round_page(memguard_mapsize);
190 if (memguard_mapsize == 0 ||
191 memguard_mapsize / (2 * PAGE_SIZE) > mem_pgs)
192 memguard_mapsize = mem_pgs * 2 * PAGE_SIZE;
193 if (km_max > 0 && km_size + memguard_mapsize > km_max)
195 return (km_size + memguard_mapsize);
199 * Initialize the MemGuard mock allocator. All objects from MemGuard come
200 * out of a single VM map (contiguous chunk of address space).
203 memguard_init(vm_map_t parent_map)
205 vm_offset_t base, limit;
207 memguard_map = kmem_suballoc(parent_map, &base, &limit,
208 memguard_mapsize, FALSE);
209 memguard_map->system_map = 1;
210 KASSERT(memguard_mapsize == limit - base,
211 ("Expected %lu, got %lu", (u_long)memguard_mapsize,
212 (u_long)(limit - base)));
213 memguard_cursor = base;
215 printf("MEMGUARD DEBUGGING ALLOCATOR INITIALIZED:\n");
216 printf("\tMEMGUARD map base: 0x%lx\n", (u_long)base);
217 printf("\tMEMGUARD map limit: 0x%lx\n", (u_long)limit);
218 printf("\tMEMGUARD map size: %jd KBytes\n",
219 (uintmax_t)memguard_mapsize >> 10);
223 * Run things that can't be done as early as memguard_init().
226 memguard_sysinit(void)
228 struct sysctl_oid_list *parent;
230 parent = SYSCTL_STATIC_CHILDREN(_vm_memguard);
232 SYSCTL_ADD_ULONG(NULL, parent, OID_AUTO, "mapstart", CTLFLAG_RD,
233 &memguard_map->min_offset, "MemGuard KVA base");
234 SYSCTL_ADD_ULONG(NULL, parent, OID_AUTO, "maplimit", CTLFLAG_RD,
235 &memguard_map->max_offset, "MemGuard KVA end");
236 SYSCTL_ADD_ULONG(NULL, parent, OID_AUTO, "mapused", CTLFLAG_RD,
237 &memguard_map->size, "MemGuard KVA used");
239 SYSINIT(memguard, SI_SUB_KLD, SI_ORDER_ANY, memguard_sysinit, NULL);
242 * v2sizep() converts a virtual address of the first page allocated for
243 * an item to a pointer to u_long recording the size of the original
244 * allocation request.
246 * This routine is very similar to those defined by UMA in uma_int.h.
247 * The difference is that this routine stores the originally allocated
248 * size in one of the page's fields that is unused when the page is
249 * wired rather than the object field, which is used.
252 v2sizep(vm_offset_t va)
257 pa = pmap_kextract(va);
259 panic("MemGuard detected double-free of %p", (void *)va);
260 p = PHYS_TO_VM_PAGE(pa);
261 KASSERT(p->wire_count != 0 && p->queue == PQ_NONE,
262 ("MEMGUARD: Expected wired page %p in vtomgfifo!", p));
263 return ((u_long *)&p->pageq.tqe_next);
267 * Allocate a single object of specified size with specified flags
268 * (either M_WAITOK or M_NOWAIT).
271 memguard_alloc(unsigned long req_size, int flags)
274 u_long size_p, size_v;
277 size_p = round_page(req_size);
281 * To ensure there are holes on both sides of the allocation,
282 * request 2 extra pages of KVA. We will only actually add a
283 * vm_map_entry and get pages for the original request. Save
284 * the value of memguard_options so we have a consistent
288 do_guard = (memguard_options & MG_GUARD_AROUND) != 0;
290 size_v += 2 * PAGE_SIZE;
292 vm_map_lock(memguard_map);
294 * When we pass our memory limit, reject sub-page allocations.
295 * Page-size and larger allocations will use the same amount
296 * of physical memory whether we allocate or hand off to
297 * uma_large_alloc(), so keep those.
299 if (memguard_map->size >= memguard_physlimit &&
300 req_size < PAGE_SIZE) {
301 addr = (vm_offset_t)NULL;
306 * Keep a moving cursor so we don't recycle KVA as long as
307 * possible. It's not perfect, since we don't know in what
308 * order previous allocations will be free'd, but it's simple
309 * and fast, and requires O(1) additional storage if guard
310 * pages are not used.
312 * XXX This scheme will lead to greater fragmentation of the
313 * map, unless vm_map_findspace() is tweaked.
316 rv = vm_map_findspace(memguard_map, memguard_cursor,
318 if (rv == KERN_SUCCESS)
321 * The map has no space. This may be due to
322 * fragmentation, or because the cursor is near the
325 if (memguard_cursor == vm_map_min(memguard_map)) {
327 addr = (vm_offset_t)NULL;
331 memguard_cursor = vm_map_min(memguard_map);
335 rv = kmem_back(memguard_map, addr, size_p, flags);
336 if (rv != KERN_SUCCESS) {
338 addr = (vm_offset_t)NULL;
341 memguard_cursor = addr + size_p;
342 *v2sizep(trunc_page(addr)) = req_size;
344 if (req_size < PAGE_SIZE) {
345 memguard_wasted += (PAGE_SIZE - req_size);
348 * Align the request to 16 bytes, and return
349 * an address near the end of the page, to
350 * better detect array overrun.
352 req_size = roundup2(req_size, 16);
353 addr += (PAGE_SIZE - req_size);
357 vm_map_unlock(memguard_map);
358 return ((void *)addr);
362 is_memguard_addr(void *addr)
364 vm_offset_t a = (vm_offset_t)(uintptr_t)addr;
366 return (a >= memguard_map->min_offset && a < memguard_map->max_offset);
370 * Free specified single object.
373 memguard_free(void *ptr)
376 u_long req_size, size;
380 addr = trunc_page((uintptr_t)ptr);
381 req_size = *v2sizep(addr);
382 size = round_page(req_size);
385 * Page should not be guarded right now, so force a write.
386 * The purpose of this is to increase the likelihood of
387 * catching a double-free, but not necessarily a
388 * tamper-after-free (the second thread freeing might not
389 * write before freeing, so this forces it to and,
390 * subsequently, trigger a fault).
393 for (i = 0; i < size; i += PAGE_SIZE)
397 * This requires carnal knowledge of the implementation of
398 * kmem_free(), but since we've already replaced kmem_malloc()
399 * above, it's not really any worse. We want to use the
400 * vm_map lock to serialize updates to memguard_wasted, since
401 * we had the lock at increment.
403 vm_map_lock(memguard_map);
404 if (req_size < PAGE_SIZE)
405 memguard_wasted -= (PAGE_SIZE - req_size);
406 (void)vm_map_delete(memguard_map, addr, addr + size);
407 vm_map_unlock(memguard_map);
411 * Re-allocate an allocation that was originally guarded.
414 memguard_realloc(void *addr, unsigned long size, struct malloc_type *mtp,
421 * Allocate the new block. Force the allocation to be guarded
422 * as the original may have been guarded through random
423 * chance, and that should be preserved.
425 if ((newaddr = memguard_alloc(size, flags)) == NULL)
428 /* Copy over original contents. */
429 old_size = *v2sizep(trunc_page((uintptr_t)addr));
430 bcopy(addr, newaddr, min(size, old_size));
436 memguard_cmp(unsigned long size)
439 if (size < memguard_minsize) {
440 memguard_minsize_reject++;
443 if ((memguard_options & MG_GUARD_ALLLARGE) != 0 && size >= PAGE_SIZE)
445 if (memguard_frequency > 0 &&
446 (random() % 100000) < memguard_frequency) {
447 memguard_frequency_hits++;
455 memguard_cmp_mtp(struct malloc_type *mtp, unsigned long size)
458 if (memguard_cmp(size))
463 * The safest way of comparsion is to always compare short description
464 * string of memory type, but it is also the slowest way.
466 return (strcmp(mtp->ks_shortdesc, vm_memguard_desc) == 0);
469 * If we compare pointers, there are two possible problems:
470 * 1. Memory type was unloaded and new memory type was allocated at the
472 * 2. Memory type was unloaded and loaded again, but allocated at a
475 if (vm_memguard_mtype != NULL)
476 return (mtp == vm_memguard_mtype);
477 if (strcmp(mtp->ks_shortdesc, vm_memguard_desc) == 0) {
478 vm_memguard_mtype = mtp;
486 memguard_cmp_zone(uma_zone_t zone)
489 if ((memguard_options & MG_GUARD_NOFREE) == 0 &&
490 zone->uz_flags & UMA_ZONE_NOFREE)
493 if (memguard_cmp(zone->uz_size))
497 * The safest way of comparsion is to always compare zone name,
498 * but it is also the slowest way.
500 return (strcmp(zone->uz_name, vm_memguard_desc) == 0);