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