xref: /freebsd/usr.sbin/bhyve/mem.c (revision 045c8f526484cb3b97f5fd693987f4376fa43c5f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012 NetApp, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following 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 NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 /*
32  * Memory ranges are represented with an RB tree. On insertion, the range
33  * is checked for overlaps. On lookup, the key has the same base and limit
34  * so it can be searched within the range.
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include <sys/types.h>
41 #include <sys/errno.h>
42 #include <sys/tree.h>
43 #include <machine/vmm.h>
44 #include <machine/vmm_instruction_emul.h>
45 
46 #include <assert.h>
47 #include <err.h>
48 #include <pthread.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 
52 #include "mem.h"
53 
54 struct mmio_rb_range {
55 	RB_ENTRY(mmio_rb_range)	mr_link;	/* RB tree links */
56 	struct mem_range	mr_param;
57 	uint64_t                mr_base;
58 	uint64_t                mr_end;
59 };
60 
61 struct mmio_rb_tree;
62 RB_PROTOTYPE(mmio_rb_tree, mmio_rb_range, mr_link, mmio_rb_range_compare);
63 
64 RB_HEAD(mmio_rb_tree, mmio_rb_range) mmio_rb_root, mmio_rb_fallback;
65 
66 /*
67  * Per-vCPU cache. Since most accesses from a vCPU will be to
68  * consecutive addresses in a range, it makes sense to cache the
69  * result of a lookup.
70  */
71 static struct mmio_rb_range	*mmio_hint[VM_MAXCPU];
72 
73 static pthread_rwlock_t mmio_rwlock;
74 
75 static int
76 mmio_rb_range_compare(struct mmio_rb_range *a, struct mmio_rb_range *b)
77 {
78 	if (a->mr_end < b->mr_base)
79 		return (-1);
80 	else if (a->mr_base > b->mr_end)
81 		return (1);
82 	return (0);
83 }
84 
85 static int
86 mmio_rb_lookup(struct mmio_rb_tree *rbt, uint64_t addr,
87     struct mmio_rb_range **entry)
88 {
89 	struct mmio_rb_range find, *res;
90 
91 	find.mr_base = find.mr_end = addr;
92 
93 	res = RB_FIND(mmio_rb_tree, rbt, &find);
94 
95 	if (res != NULL) {
96 		*entry = res;
97 		return (0);
98 	}
99 
100 	return (ENOENT);
101 }
102 
103 static int
104 mmio_rb_add(struct mmio_rb_tree *rbt, struct mmio_rb_range *new)
105 {
106 	struct mmio_rb_range *overlap;
107 
108 	overlap = RB_INSERT(mmio_rb_tree, rbt, new);
109 
110 	if (overlap != NULL) {
111 #ifdef RB_DEBUG
112 		printf("overlap detected: new %lx:%lx, tree %lx:%lx, '%s' "
113 		       "claims region already claimed for '%s'\n",
114 		       new->mr_base, new->mr_end,
115 		       overlap->mr_base, overlap->mr_end,
116 		       new->mr_param.name, overlap->mr_param.name);
117 #endif
118 
119 		return (EEXIST);
120 	}
121 
122 	return (0);
123 }
124 
125 #if 0
126 static void
127 mmio_rb_dump(struct mmio_rb_tree *rbt)
128 {
129 	int perror;
130 	struct mmio_rb_range *np;
131 
132 	pthread_rwlock_rdlock(&mmio_rwlock);
133 	RB_FOREACH(np, mmio_rb_tree, rbt) {
134 		printf(" %lx:%lx, %s\n", np->mr_base, np->mr_end,
135 		       np->mr_param.name);
136 	}
137 	perror = pthread_rwlock_unlock(&mmio_rwlock);
138 	assert(perror == 0);
139 }
140 #endif
141 
142 RB_GENERATE(mmio_rb_tree, mmio_rb_range, mr_link, mmio_rb_range_compare);
143 
144 typedef int (mem_cb_t)(struct vmctx *ctx, int vcpu, uint64_t gpa,
145     struct mem_range *mr, void *arg);
146 
147 static int
148 mem_read(void *ctx, int vcpu, uint64_t gpa, uint64_t *rval, int size, void *arg)
149 {
150 	int error;
151 	struct mem_range *mr = arg;
152 
153 	error = (*mr->handler)(ctx, vcpu, MEM_F_READ, gpa, size,
154 			       rval, mr->arg1, mr->arg2);
155 	return (error);
156 }
157 
158 static int
159 mem_write(void *ctx, int vcpu, uint64_t gpa, uint64_t wval, int size, void *arg)
160 {
161 	int error;
162 	struct mem_range *mr = arg;
163 
164 	error = (*mr->handler)(ctx, vcpu, MEM_F_WRITE, gpa, size,
165 			       &wval, mr->arg1, mr->arg2);
166 	return (error);
167 }
168 
169 static int
170 access_memory(struct vmctx *ctx, int vcpu, uint64_t paddr, mem_cb_t *cb,
171     void *arg)
172 {
173 	struct mmio_rb_range *entry;
174 	int err, perror, immutable;
175 
176 	pthread_rwlock_rdlock(&mmio_rwlock);
177 	/*
178 	 * First check the per-vCPU cache
179 	 */
180 	if (mmio_hint[vcpu] &&
181 	    paddr >= mmio_hint[vcpu]->mr_base &&
182 	    paddr <= mmio_hint[vcpu]->mr_end) {
183 		entry = mmio_hint[vcpu];
184 	} else
185 		entry = NULL;
186 
187 	if (entry == NULL) {
188 		if (mmio_rb_lookup(&mmio_rb_root, paddr, &entry) == 0) {
189 			/* Update the per-vCPU cache */
190 			mmio_hint[vcpu] = entry;
191 		} else if (mmio_rb_lookup(&mmio_rb_fallback, paddr, &entry)) {
192 			perror = pthread_rwlock_unlock(&mmio_rwlock);
193 			assert(perror == 0);
194 			return (ESRCH);
195 		}
196 	}
197 
198 	assert(entry != NULL);
199 
200 	/*
201 	 * An 'immutable' memory range is guaranteed to be never removed
202 	 * so there is no need to hold 'mmio_rwlock' while calling the
203 	 * handler.
204 	 *
205 	 * XXX writes to the PCIR_COMMAND register can cause register_mem()
206 	 * to be called. If the guest is using PCI extended config space
207 	 * to modify the PCIR_COMMAND register then register_mem() can
208 	 * deadlock on 'mmio_rwlock'. However by registering the extended
209 	 * config space window as 'immutable' the deadlock can be avoided.
210 	 */
211 	immutable = (entry->mr_param.flags & MEM_F_IMMUTABLE);
212 	if (immutable) {
213 		perror = pthread_rwlock_unlock(&mmio_rwlock);
214 		assert(perror == 0);
215 	}
216 
217 	err = cb(ctx, vcpu, paddr, &entry->mr_param, arg);
218 
219 	if (!immutable) {
220 		perror = pthread_rwlock_unlock(&mmio_rwlock);
221 		assert(perror == 0);
222 	}
223 
224 
225 	return (err);
226 }
227 
228 struct emulate_mem_args {
229 	struct vie *vie;
230 	struct vm_guest_paging *paging;
231 };
232 
233 static int
234 emulate_mem_cb(struct vmctx *ctx, int vcpu, uint64_t paddr, struct mem_range *mr,
235     void *arg)
236 {
237 	struct emulate_mem_args *ema;
238 
239 	ema = arg;
240 	return (vmm_emulate_instruction(ctx, vcpu, paddr, ema->vie, ema->paging,
241 	    mem_read, mem_write, mr));
242 }
243 
244 int
245 emulate_mem(struct vmctx *ctx, int vcpu, uint64_t paddr, struct vie *vie,
246     struct vm_guest_paging *paging)
247 
248 {
249 	struct emulate_mem_args ema;
250 
251 	ema.vie = vie;
252 	ema.paging = paging;
253 	return (access_memory(ctx, vcpu, paddr, emulate_mem_cb, &ema));
254 }
255 
256 struct rw_mem_args {
257 	uint64_t *val;
258 	int size;
259 	int operation;
260 };
261 
262 static int
263 rw_mem_cb(struct vmctx *ctx, int vcpu, uint64_t paddr, struct mem_range *mr,
264     void *arg)
265 {
266 	struct rw_mem_args *rma;
267 
268 	rma = arg;
269 	return (mr->handler(ctx, vcpu, rma->operation, paddr, rma->size,
270 	    rma->val, mr->arg1, mr->arg2));
271 }
272 
273 int
274 read_mem(struct vmctx *ctx, int vcpu, uint64_t gpa, uint64_t *rval, int size)
275 {
276 	struct rw_mem_args rma;
277 
278 	rma.val = rval;
279 	rma.size = size;
280 	rma.operation = MEM_F_READ;
281 	return (access_memory(ctx, vcpu, gpa, rw_mem_cb, &rma));
282 }
283 
284 int
285 write_mem(struct vmctx *ctx, int vcpu, uint64_t gpa, uint64_t wval, int size)
286 {
287 	struct rw_mem_args rma;
288 
289 	rma.val = &wval;
290 	rma.size = size;
291 	rma.operation = MEM_F_WRITE;
292 	return (access_memory(ctx, vcpu, gpa, rw_mem_cb, &rma));
293 }
294 
295 static int
296 register_mem_int(struct mmio_rb_tree *rbt, struct mem_range *memp)
297 {
298 	struct mmio_rb_range *entry, *mrp;
299 	int err, perror;
300 
301 	err = 0;
302 
303 	mrp = malloc(sizeof(struct mmio_rb_range));
304 	if (mrp == NULL) {
305 		warn("%s: couldn't allocate memory for mrp\n",
306 		     __func__);
307 		err = ENOMEM;
308 	} else {
309 		mrp->mr_param = *memp;
310 		mrp->mr_base = memp->base;
311 		mrp->mr_end = memp->base + memp->size - 1;
312 		pthread_rwlock_wrlock(&mmio_rwlock);
313 		if (mmio_rb_lookup(rbt, memp->base, &entry) != 0)
314 			err = mmio_rb_add(rbt, mrp);
315 		perror = pthread_rwlock_unlock(&mmio_rwlock);
316 		assert(perror == 0);
317 		if (err)
318 			free(mrp);
319 	}
320 
321 	return (err);
322 }
323 
324 int
325 register_mem(struct mem_range *memp)
326 {
327 
328 	return (register_mem_int(&mmio_rb_root, memp));
329 }
330 
331 int
332 register_mem_fallback(struct mem_range *memp)
333 {
334 
335 	return (register_mem_int(&mmio_rb_fallback, memp));
336 }
337 
338 int
339 unregister_mem(struct mem_range *memp)
340 {
341 	struct mem_range *mr;
342 	struct mmio_rb_range *entry = NULL;
343 	int err, perror, i;
344 
345 	pthread_rwlock_wrlock(&mmio_rwlock);
346 	err = mmio_rb_lookup(&mmio_rb_root, memp->base, &entry);
347 	if (err == 0) {
348 		mr = &entry->mr_param;
349 		assert(mr->name == memp->name);
350 		assert(mr->base == memp->base && mr->size == memp->size);
351 		assert((mr->flags & MEM_F_IMMUTABLE) == 0);
352 		RB_REMOVE(mmio_rb_tree, &mmio_rb_root, entry);
353 
354 		/* flush Per-vCPU cache */
355 		for (i=0; i < VM_MAXCPU; i++) {
356 			if (mmio_hint[i] == entry)
357 				mmio_hint[i] = NULL;
358 		}
359 	}
360 	perror = pthread_rwlock_unlock(&mmio_rwlock);
361 	assert(perror == 0);
362 
363 	if (entry)
364 		free(entry);
365 
366 	return (err);
367 }
368 
369 void
370 init_mem(void)
371 {
372 
373 	RB_INIT(&mmio_rb_root);
374 	RB_INIT(&mmio_rb_fallback);
375 	pthread_rwlock_init(&mmio_rwlock, NULL);
376 }
377