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