xref: /freebsd/sys/riscv/vmm/vmm.c (revision 1eb3f15c149b9a2e5b6f5e10aed454fc85945bbd)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2015 Mihai Carabas <mihai.carabas@gmail.com>
5  * Copyright (c) 2024 Ruslan Bukin <br@bsdpad.com>
6  *
7  * This software was developed by the University of Cambridge Computer
8  * Laboratory (Department of Computer Science and Technology) under Innovate
9  * UK project 105694, "Digital Security by Design (DSbD) Technology Platform
10  * Prototype".
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/cpuset.h>
37 #include <sys/kernel.h>
38 #include <sys/linker.h>
39 #include <sys/lock.h>
40 #include <sys/malloc.h>
41 #include <sys/module.h>
42 #include <sys/mutex.h>
43 #include <sys/pcpu.h>
44 #include <sys/proc.h>
45 #include <sys/queue.h>
46 #include <sys/rwlock.h>
47 #include <sys/sched.h>
48 #include <sys/smp.h>
49 #include <sys/sysctl.h>
50 
51 #include <vm/vm.h>
52 #include <vm/vm_object.h>
53 #include <vm/vm_page.h>
54 #include <vm/pmap.h>
55 #include <vm/vm_map.h>
56 #include <vm/vm_extern.h>
57 #include <vm/vm_param.h>
58 
59 #include <machine/riscvreg.h>
60 #include <machine/cpu.h>
61 #include <machine/fpe.h>
62 #include <machine/machdep.h>
63 #include <machine/pcb.h>
64 #include <machine/smp.h>
65 #include <machine/vm.h>
66 #include <machine/vmparam.h>
67 #include <machine/vmm.h>
68 #include <machine/vmm_instruction_emul.h>
69 
70 #include <dev/pci/pcireg.h>
71 
72 #include <dev/vmm/vmm_dev.h>
73 #include <dev/vmm/vmm_ktr.h>
74 
75 #include "vmm_stat.h"
76 #include "riscv.h"
77 
78 #include "vmm_aplic.h"
79 
80 struct vcpu {
81 	int		flags;
82 	enum vcpu_state	state;
83 	struct mtx	mtx;
84 	int		hostcpu;	/* host cpuid this vcpu last ran on */
85 	int		vcpuid;
86 	void		*stats;
87 	struct vm_exit	exitinfo;
88 	uint64_t	nextpc;		/* (x) next instruction to execute */
89 	struct vm	*vm;		/* (o) */
90 	void		*cookie;	/* (i) cpu-specific data */
91 	struct fpreg	*guestfpu;	/* (a,i) guest fpu state */
92 };
93 
94 #define	vcpu_lock_initialized(v) mtx_initialized(&((v)->mtx))
95 #define	vcpu_lock_init(v)	mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
96 #define	vcpu_lock_destroy(v)	mtx_destroy(&((v)->mtx))
97 #define	vcpu_lock(v)		mtx_lock_spin(&((v)->mtx))
98 #define	vcpu_unlock(v)		mtx_unlock_spin(&((v)->mtx))
99 #define	vcpu_assert_locked(v)	mtx_assert(&((v)->mtx), MA_OWNED)
100 
101 struct mem_seg {
102 	uint64_t	gpa;
103 	size_t		len;
104 	bool		wired;
105 	bool		sysmem;
106 	vm_object_t	object;
107 };
108 #define	VM_MAX_MEMSEGS	3
109 
110 struct mem_map {
111 	vm_paddr_t	gpa;
112 	size_t		len;
113 	vm_ooffset_t	segoff;
114 	int		segid;
115 	int		prot;
116 	int		flags;
117 };
118 #define	VM_MAX_MEMMAPS	4
119 
120 struct vmm_mmio_region {
121 	uint64_t start;
122 	uint64_t end;
123 	mem_region_read_t read;
124 	mem_region_write_t write;
125 };
126 #define	VM_MAX_MMIO_REGIONS	4
127 
128 /*
129  * Initialization:
130  * (o) initialized the first time the VM is created
131  * (i) initialized when VM is created and when it is reinitialized
132  * (x) initialized before use
133  */
134 struct vm {
135 	void		*cookie;		/* (i) cpu-specific data */
136 	volatile cpuset_t active_cpus;		/* (i) active vcpus */
137 	volatile cpuset_t debug_cpus;		/* (i) vcpus stopped for debug*/
138 	int		suspend;		/* (i) stop VM execution */
139 	bool		dying;			/* (o) is dying */
140 	volatile cpuset_t suspended_cpus; 	/* (i) suspended vcpus */
141 	volatile cpuset_t halted_cpus;		/* (x) cpus in a hard halt */
142 	struct mem_map	mem_maps[VM_MAX_MEMMAPS]; /* (i) guest address space */
143 	struct mem_seg	mem_segs[VM_MAX_MEMSEGS]; /* (o) guest memory regions */
144 	struct vmspace	*vmspace;		/* (o) guest's address space */
145 	char		name[VM_MAX_NAMELEN];	/* (o) virtual machine name */
146 	struct vcpu	**vcpu;			/* (i) guest vcpus */
147 	struct vmm_mmio_region mmio_region[VM_MAX_MMIO_REGIONS];
148 						/* (o) guest MMIO regions */
149 	/* The following describe the vm cpu topology */
150 	uint16_t	sockets;		/* (o) num of sockets */
151 	uint16_t	cores;			/* (o) num of cores/socket */
152 	uint16_t	threads;		/* (o) num of threads/core */
153 	uint16_t	maxcpus;		/* (o) max pluggable cpus */
154 	struct sx	mem_segs_lock;		/* (o) */
155 	struct sx	vcpus_init_lock;	/* (o) */
156 };
157 
158 static bool vmm_initialized = false;
159 
160 static MALLOC_DEFINE(M_VMM, "vmm", "vmm");
161 
162 /* statistics */
163 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
164 
165 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
166 
167 static int vmm_ipinum;
168 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
169     "IPI vector used for vcpu notifications");
170 
171 u_int vm_maxcpu;
172 SYSCTL_UINT(_hw_vmm, OID_AUTO, maxcpu, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
173     &vm_maxcpu, 0, "Maximum number of vCPUs");
174 
175 static void vm_free_memmap(struct vm *vm, int ident);
176 static bool sysmem_mapping(struct vm *vm, struct mem_map *mm);
177 static void vcpu_notify_event_locked(struct vcpu *vcpu);
178 
179 /*
180  * Upper limit on vm_maxcpu. We could increase this to 28 bits, but this
181  * is a safe value for now.
182  */
183 #define	VM_MAXCPU	MIN(0xffff - 1, CPU_SETSIZE)
184 
185 static void
186 vcpu_cleanup(struct vcpu *vcpu, bool destroy)
187 {
188 	vmmops_vcpu_cleanup(vcpu->cookie);
189 	vcpu->cookie = NULL;
190 	if (destroy) {
191 		vmm_stat_free(vcpu->stats);
192 		fpu_save_area_free(vcpu->guestfpu);
193 		vcpu_lock_destroy(vcpu);
194 	}
195 }
196 
197 static struct vcpu *
198 vcpu_alloc(struct vm *vm, int vcpu_id)
199 {
200 	struct vcpu *vcpu;
201 
202 	KASSERT(vcpu_id >= 0 && vcpu_id < vm->maxcpus,
203 	    ("vcpu_alloc: invalid vcpu %d", vcpu_id));
204 
205 	vcpu = malloc(sizeof(*vcpu), M_VMM, M_WAITOK | M_ZERO);
206 	vcpu_lock_init(vcpu);
207 	vcpu->state = VCPU_IDLE;
208 	vcpu->hostcpu = NOCPU;
209 	vcpu->vcpuid = vcpu_id;
210 	vcpu->vm = vm;
211 	vcpu->guestfpu = fpu_save_area_alloc();
212 	vcpu->stats = vmm_stat_alloc();
213 	return (vcpu);
214 }
215 
216 static void
217 vcpu_init(struct vcpu *vcpu)
218 {
219 	vcpu->cookie = vmmops_vcpu_init(vcpu->vm->cookie, vcpu, vcpu->vcpuid);
220 	MPASS(vcpu->cookie != NULL);
221 	fpu_save_area_reset(vcpu->guestfpu);
222 	vmm_stat_init(vcpu->stats);
223 }
224 
225 struct vm_exit *
226 vm_exitinfo(struct vcpu *vcpu)
227 {
228 	return (&vcpu->exitinfo);
229 }
230 
231 static int
232 vmm_init(void)
233 {
234 
235 	vm_maxcpu = mp_ncpus;
236 
237 	TUNABLE_INT_FETCH("hw.vmm.maxcpu", &vm_maxcpu);
238 
239 	if (vm_maxcpu > VM_MAXCPU) {
240 		printf("vmm: vm_maxcpu clamped to %u\n", VM_MAXCPU);
241 		vm_maxcpu = VM_MAXCPU;
242 	}
243 
244 	if (vm_maxcpu == 0)
245 		vm_maxcpu = 1;
246 
247 	return (vmmops_modinit());
248 }
249 
250 static int
251 vmm_handler(module_t mod, int what, void *arg)
252 {
253 	int error;
254 
255 	switch (what) {
256 	case MOD_LOAD:
257 		/* TODO: check if has_hyp here? */
258 		error = vmmdev_init();
259 		if (error != 0)
260 			break;
261 		error = vmm_init();
262 		if (error == 0)
263 			vmm_initialized = true;
264 		break;
265 	case MOD_UNLOAD:
266 		/* TODO: check if has_hyp here? */
267 		error = vmmdev_cleanup();
268 		if (error == 0 && vmm_initialized) {
269 			error = vmmops_modcleanup();
270 			if (error)
271 				vmm_initialized = false;
272 		}
273 		break;
274 	default:
275 		error = 0;
276 		break;
277 	}
278 	return (error);
279 }
280 
281 static moduledata_t vmm_kmod = {
282 	"vmm",
283 	vmm_handler,
284 	NULL
285 };
286 
287 /*
288  * vmm initialization has the following dependencies:
289  *
290  * - vmm device initialization requires an initialized devfs.
291  */
292 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_DEVFS + 1, SI_ORDER_ANY);
293 MODULE_VERSION(vmm, 1);
294 
295 static void
296 vm_init(struct vm *vm, bool create)
297 {
298 	int i;
299 
300 	vm->cookie = vmmops_init(vm, vmspace_pmap(vm->vmspace));
301 	MPASS(vm->cookie != NULL);
302 
303 	CPU_ZERO(&vm->active_cpus);
304 	CPU_ZERO(&vm->debug_cpus);
305 
306 	vm->suspend = 0;
307 	CPU_ZERO(&vm->suspended_cpus);
308 
309 	memset(vm->mmio_region, 0, sizeof(vm->mmio_region));
310 
311 	if (!create) {
312 		for (i = 0; i < vm->maxcpus; i++) {
313 			if (vm->vcpu[i] != NULL)
314 				vcpu_init(vm->vcpu[i]);
315 		}
316 	}
317 }
318 
319 void
320 vm_disable_vcpu_creation(struct vm *vm)
321 {
322 	sx_xlock(&vm->vcpus_init_lock);
323 	vm->dying = true;
324 	sx_xunlock(&vm->vcpus_init_lock);
325 }
326 
327 struct vcpu *
328 vm_alloc_vcpu(struct vm *vm, int vcpuid)
329 {
330 	struct vcpu *vcpu;
331 
332 	if (vcpuid < 0 || vcpuid >= vm_get_maxcpus(vm))
333 		return (NULL);
334 
335 	/* Some interrupt controllers may have a CPU limit */
336 	if (vcpuid >= aplic_max_cpu_count(vm->cookie))
337 		return (NULL);
338 
339 	vcpu = (struct vcpu *)
340 	    atomic_load_acq_ptr((uintptr_t *)&vm->vcpu[vcpuid]);
341 	if (__predict_true(vcpu != NULL))
342 		return (vcpu);
343 
344 	sx_xlock(&vm->vcpus_init_lock);
345 	vcpu = vm->vcpu[vcpuid];
346 	if (vcpu == NULL && !vm->dying) {
347 		vcpu = vcpu_alloc(vm, vcpuid);
348 		vcpu_init(vcpu);
349 
350 		/*
351 		 * Ensure vCPU is fully created before updating pointer
352 		 * to permit unlocked reads above.
353 		 */
354 		atomic_store_rel_ptr((uintptr_t *)&vm->vcpu[vcpuid],
355 		    (uintptr_t)vcpu);
356 	}
357 	sx_xunlock(&vm->vcpus_init_lock);
358 	return (vcpu);
359 }
360 
361 void
362 vm_slock_vcpus(struct vm *vm)
363 {
364 	sx_slock(&vm->vcpus_init_lock);
365 }
366 
367 void
368 vm_unlock_vcpus(struct vm *vm)
369 {
370 	sx_unlock(&vm->vcpus_init_lock);
371 }
372 
373 int
374 vm_create(const char *name, struct vm **retvm)
375 {
376 	struct vm *vm;
377 	struct vmspace *vmspace;
378 
379 	/*
380 	 * If vmm.ko could not be successfully initialized then don't attempt
381 	 * to create the virtual machine.
382 	 */
383 	if (!vmm_initialized)
384 		return (ENXIO);
385 
386 	if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
387 		return (EINVAL);
388 
389 	vmspace = vmmops_vmspace_alloc(0, 1ul << 39);
390 	if (vmspace == NULL)
391 		return (ENOMEM);
392 
393 	vm = malloc(sizeof(struct vm), M_VMM, M_WAITOK | M_ZERO);
394 	strcpy(vm->name, name);
395 	vm->vmspace = vmspace;
396 	sx_init(&vm->mem_segs_lock, "vm mem_segs");
397 	sx_init(&vm->vcpus_init_lock, "vm vcpus");
398 
399 	vm->sockets = 1;
400 	vm->cores = 1;			/* XXX backwards compatibility */
401 	vm->threads = 1;		/* XXX backwards compatibility */
402 	vm->maxcpus = vm_maxcpu;
403 
404 	vm->vcpu = malloc(sizeof(*vm->vcpu) * vm->maxcpus, M_VMM,
405 	    M_WAITOK | M_ZERO);
406 
407 	vm_init(vm, true);
408 
409 	*retvm = vm;
410 	return (0);
411 }
412 
413 void
414 vm_get_topology(struct vm *vm, uint16_t *sockets, uint16_t *cores,
415     uint16_t *threads, uint16_t *maxcpus)
416 {
417 	*sockets = vm->sockets;
418 	*cores = vm->cores;
419 	*threads = vm->threads;
420 	*maxcpus = vm->maxcpus;
421 }
422 
423 uint16_t
424 vm_get_maxcpus(struct vm *vm)
425 {
426 	return (vm->maxcpus);
427 }
428 
429 int
430 vm_set_topology(struct vm *vm, uint16_t sockets, uint16_t cores,
431     uint16_t threads, uint16_t maxcpus)
432 {
433 	/* Ignore maxcpus. */
434 	if ((sockets * cores * threads) > vm->maxcpus)
435 		return (EINVAL);
436 	vm->sockets = sockets;
437 	vm->cores = cores;
438 	vm->threads = threads;
439 	return(0);
440 }
441 
442 static void
443 vm_cleanup(struct vm *vm, bool destroy)
444 {
445 	struct mem_map *mm;
446 	int i;
447 
448 	aplic_detach_from_vm(vm->cookie);
449 
450 	for (i = 0; i < vm->maxcpus; i++) {
451 		if (vm->vcpu[i] != NULL)
452 			vcpu_cleanup(vm->vcpu[i], destroy);
453 	}
454 
455 	vmmops_cleanup(vm->cookie);
456 
457 	/*
458 	 * System memory is removed from the guest address space only when
459 	 * the VM is destroyed. This is because the mapping remains the same
460 	 * across VM reset.
461 	 *
462 	 * Device memory can be relocated by the guest (e.g. using PCI BARs)
463 	 * so those mappings are removed on a VM reset.
464 	 */
465 	if (!destroy) {
466 		for (i = 0; i < VM_MAX_MEMMAPS; i++) {
467 			mm = &vm->mem_maps[i];
468 			if (destroy || !sysmem_mapping(vm, mm))
469 				vm_free_memmap(vm, i);
470 		}
471 	}
472 
473 	if (destroy) {
474 		for (i = 0; i < VM_MAX_MEMSEGS; i++)
475 			vm_free_memseg(vm, i);
476 
477 		vmmops_vmspace_free(vm->vmspace);
478 		vm->vmspace = NULL;
479 
480 		for (i = 0; i < vm->maxcpus; i++)
481 			free(vm->vcpu[i], M_VMM);
482 		free(vm->vcpu, M_VMM);
483 		sx_destroy(&vm->vcpus_init_lock);
484 		sx_destroy(&vm->mem_segs_lock);
485 	}
486 }
487 
488 void
489 vm_destroy(struct vm *vm)
490 {
491 
492 	vm_cleanup(vm, true);
493 
494 	free(vm, M_VMM);
495 }
496 
497 int
498 vm_reinit(struct vm *vm)
499 {
500 	int error;
501 
502 	/*
503 	 * A virtual machine can be reset only if all vcpus are suspended.
504 	 */
505 	if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
506 		vm_cleanup(vm, false);
507 		vm_init(vm, false);
508 		error = 0;
509 	} else {
510 		error = EBUSY;
511 	}
512 
513 	return (error);
514 }
515 
516 const char *
517 vm_name(struct vm *vm)
518 {
519 	return (vm->name);
520 }
521 
522 void
523 vm_slock_memsegs(struct vm *vm)
524 {
525 	sx_slock(&vm->mem_segs_lock);
526 }
527 
528 void
529 vm_xlock_memsegs(struct vm *vm)
530 {
531 	sx_xlock(&vm->mem_segs_lock);
532 }
533 
534 void
535 vm_unlock_memsegs(struct vm *vm)
536 {
537 	sx_unlock(&vm->mem_segs_lock);
538 }
539 
540 /*
541  * Return 'true' if 'gpa' is allocated in the guest address space.
542  *
543  * This function is called in the context of a running vcpu which acts as
544  * an implicit lock on 'vm->mem_maps[]'.
545  */
546 bool
547 vm_mem_allocated(struct vcpu *vcpu, vm_paddr_t gpa)
548 {
549 	struct vm *vm = vcpu->vm;
550 	struct mem_map *mm;
551 	int i;
552 
553 #ifdef INVARIANTS
554 	int hostcpu, state;
555 	state = vcpu_get_state(vcpu, &hostcpu);
556 	KASSERT(state == VCPU_RUNNING && hostcpu == curcpu,
557 	    ("%s: invalid vcpu state %d/%d", __func__, state, hostcpu));
558 #endif
559 
560 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
561 		mm = &vm->mem_maps[i];
562 		if (mm->len != 0 && gpa >= mm->gpa && gpa < mm->gpa + mm->len)
563 			return (true);		/* 'gpa' is sysmem or devmem */
564 	}
565 
566 	return (false);
567 }
568 
569 int
570 vm_alloc_memseg(struct vm *vm, int ident, size_t len, bool sysmem)
571 {
572 	struct mem_seg *seg;
573 	vm_object_t obj;
574 
575 	sx_assert(&vm->mem_segs_lock, SX_XLOCKED);
576 
577 	if (ident < 0 || ident >= VM_MAX_MEMSEGS)
578 		return (EINVAL);
579 
580 	if (len == 0 || (len & PAGE_MASK))
581 		return (EINVAL);
582 
583 	seg = &vm->mem_segs[ident];
584 	if (seg->object != NULL) {
585 		if (seg->len == len && seg->sysmem == sysmem)
586 			return (EEXIST);
587 		else
588 			return (EINVAL);
589 	}
590 
591 	obj = vm_object_allocate(OBJT_DEFAULT, len >> PAGE_SHIFT);
592 	if (obj == NULL)
593 		return (ENOMEM);
594 
595 	seg->len = len;
596 	seg->object = obj;
597 	seg->sysmem = sysmem;
598 	return (0);
599 }
600 
601 int
602 vm_get_memseg(struct vm *vm, int ident, size_t *len, bool *sysmem,
603     vm_object_t *objptr)
604 {
605 	struct mem_seg *seg;
606 
607 	sx_assert(&vm->mem_segs_lock, SX_LOCKED);
608 
609 	if (ident < 0 || ident >= VM_MAX_MEMSEGS)
610 		return (EINVAL);
611 
612 	seg = &vm->mem_segs[ident];
613 	if (len)
614 		*len = seg->len;
615 	if (sysmem)
616 		*sysmem = seg->sysmem;
617 	if (objptr)
618 		*objptr = seg->object;
619 	return (0);
620 }
621 
622 void
623 vm_free_memseg(struct vm *vm, int ident)
624 {
625 	struct mem_seg *seg;
626 
627 	KASSERT(ident >= 0 && ident < VM_MAX_MEMSEGS,
628 	    ("%s: invalid memseg ident %d", __func__, ident));
629 
630 	seg = &vm->mem_segs[ident];
631 	if (seg->object != NULL) {
632 		vm_object_deallocate(seg->object);
633 		bzero(seg, sizeof(struct mem_seg));
634 	}
635 }
636 
637 int
638 vm_mmap_memseg(struct vm *vm, vm_paddr_t gpa, int segid, vm_ooffset_t first,
639     size_t len, int prot, int flags)
640 {
641 	struct mem_seg *seg;
642 	struct mem_map *m, *map;
643 	vm_ooffset_t last;
644 	int i, error;
645 
646 	dprintf("%s: gpa %lx first %lx len %lx\n", __func__, gpa, first, len);
647 
648 	if (prot == 0 || (prot & ~(VM_PROT_ALL)) != 0)
649 		return (EINVAL);
650 
651 	if (flags & ~VM_MEMMAP_F_WIRED)
652 		return (EINVAL);
653 
654 	if (segid < 0 || segid >= VM_MAX_MEMSEGS)
655 		return (EINVAL);
656 
657 	seg = &vm->mem_segs[segid];
658 	if (seg->object == NULL)
659 		return (EINVAL);
660 
661 	last = first + len;
662 	if (first < 0 || first >= last || last > seg->len)
663 		return (EINVAL);
664 
665 	if ((gpa | first | last) & PAGE_MASK)
666 		return (EINVAL);
667 
668 	map = NULL;
669 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
670 		m = &vm->mem_maps[i];
671 		if (m->len == 0) {
672 			map = m;
673 			break;
674 		}
675 	}
676 
677 	if (map == NULL)
678 		return (ENOSPC);
679 
680 	error = vm_map_find(&vm->vmspace->vm_map, seg->object, first, &gpa,
681 	    len, 0, VMFS_NO_SPACE, prot, prot, 0);
682 	if (error != KERN_SUCCESS)
683 		return (EFAULT);
684 
685 	vm_object_reference(seg->object);
686 
687 	if (flags & VM_MEMMAP_F_WIRED) {
688 		error = vm_map_wire(&vm->vmspace->vm_map, gpa, gpa + len,
689 		    VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
690 		if (error != KERN_SUCCESS) {
691 			vm_map_remove(&vm->vmspace->vm_map, gpa, gpa + len);
692 			return (error == KERN_RESOURCE_SHORTAGE ? ENOMEM :
693 			    EFAULT);
694 		}
695 	}
696 
697 	map->gpa = gpa;
698 	map->len = len;
699 	map->segoff = first;
700 	map->segid = segid;
701 	map->prot = prot;
702 	map->flags = flags;
703 	return (0);
704 }
705 
706 int
707 vm_munmap_memseg(struct vm *vm, vm_paddr_t gpa, size_t len)
708 {
709 	struct mem_map *m;
710 	int i;
711 
712 	dprintf("%s: gpa %lx len %lx\n", __func__, gpa, len);
713 
714 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
715 		m = &vm->mem_maps[i];
716 		if (m->gpa == gpa && m->len == len) {
717 			vm_free_memmap(vm, i);
718 			return (0);
719 		}
720 	}
721 
722 	return (EINVAL);
723 }
724 
725 int
726 vm_mmap_getnext(struct vm *vm, vm_paddr_t *gpa, int *segid,
727     vm_ooffset_t *segoff, size_t *len, int *prot, int *flags)
728 {
729 	struct mem_map *mm, *mmnext;
730 	int i;
731 
732 	mmnext = NULL;
733 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
734 		mm = &vm->mem_maps[i];
735 		if (mm->len == 0 || mm->gpa < *gpa)
736 			continue;
737 		if (mmnext == NULL || mm->gpa < mmnext->gpa)
738 			mmnext = mm;
739 	}
740 
741 	if (mmnext != NULL) {
742 		*gpa = mmnext->gpa;
743 		if (segid)
744 			*segid = mmnext->segid;
745 		if (segoff)
746 			*segoff = mmnext->segoff;
747 		if (len)
748 			*len = mmnext->len;
749 		if (prot)
750 			*prot = mmnext->prot;
751 		if (flags)
752 			*flags = mmnext->flags;
753 		return (0);
754 	} else {
755 		return (ENOENT);
756 	}
757 }
758 
759 static void
760 vm_free_memmap(struct vm *vm, int ident)
761 {
762 	struct mem_map *mm;
763 	int error __diagused;
764 
765 	mm = &vm->mem_maps[ident];
766 	if (mm->len) {
767 		error = vm_map_remove(&vm->vmspace->vm_map, mm->gpa,
768 		    mm->gpa + mm->len);
769 		KASSERT(error == KERN_SUCCESS, ("%s: vm_map_remove error %d",
770 		    __func__, error));
771 		bzero(mm, sizeof(struct mem_map));
772 	}
773 }
774 
775 static __inline bool
776 sysmem_mapping(struct vm *vm, struct mem_map *mm)
777 {
778 
779 	if (mm->len != 0 && vm->mem_segs[mm->segid].sysmem)
780 		return (true);
781 	else
782 		return (false);
783 }
784 
785 vm_paddr_t
786 vmm_sysmem_maxaddr(struct vm *vm)
787 {
788 	struct mem_map *mm;
789 	vm_paddr_t maxaddr;
790 	int i;
791 
792 	maxaddr = 0;
793 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
794 		mm = &vm->mem_maps[i];
795 		if (sysmem_mapping(vm, mm)) {
796 			if (maxaddr < mm->gpa + mm->len)
797 				maxaddr = mm->gpa + mm->len;
798 		}
799 	}
800 	return (maxaddr);
801 }
802 
803 int
804 vm_gla2gpa_nofault(struct vcpu *vcpu, struct vm_guest_paging *paging,
805     uint64_t gla, int prot, uint64_t *gpa, int *is_fault)
806 {
807 	int error;
808 
809 	error = vmmops_gla2gpa(vcpu->cookie, paging, gla, prot, gpa, is_fault);
810 
811 	return (error);
812 }
813 
814 void
815 vm_register_inst_handler(struct vm *vm, uint64_t start, uint64_t size,
816     mem_region_read_t mmio_read, mem_region_write_t mmio_write)
817 {
818 	int i;
819 
820 	for (i = 0; i < nitems(vm->mmio_region); i++) {
821 		if (vm->mmio_region[i].start == 0 &&
822 		    vm->mmio_region[i].end == 0) {
823 			vm->mmio_region[i].start = start;
824 			vm->mmio_region[i].end = start + size;
825 			vm->mmio_region[i].read = mmio_read;
826 			vm->mmio_region[i].write = mmio_write;
827 			return;
828 		}
829 	}
830 
831 	panic("%s: No free MMIO region", __func__);
832 }
833 
834 void
835 vm_deregister_inst_handler(struct vm *vm, uint64_t start, uint64_t size)
836 {
837 	int i;
838 
839 	for (i = 0; i < nitems(vm->mmio_region); i++) {
840 		if (vm->mmio_region[i].start == start &&
841 		    vm->mmio_region[i].end == start + size) {
842 			memset(&vm->mmio_region[i], 0,
843 			    sizeof(vm->mmio_region[i]));
844 			return;
845 		}
846 	}
847 
848 	panic("%s: Invalid MMIO region: %lx - %lx", __func__, start,
849 	    start + size);
850 }
851 
852 static int
853 vm_handle_inst_emul(struct vcpu *vcpu, bool *retu)
854 {
855 	struct vm *vm;
856 	struct vm_exit *vme;
857 	struct vie *vie;
858 	struct hyp *hyp;
859 	uint64_t fault_ipa;
860 	struct vm_guest_paging *paging;
861 	struct vmm_mmio_region *vmr;
862 	int error, i;
863 
864 	vm = vcpu->vm;
865 	hyp = vm->cookie;
866 	if (!hyp->aplic_attached)
867 		goto out_user;
868 
869 	vme = &vcpu->exitinfo;
870 	vie = &vme->u.inst_emul.vie;
871 	paging = &vme->u.inst_emul.paging;
872 
873 	fault_ipa = vme->u.inst_emul.gpa;
874 
875 	vmr = NULL;
876 	for (i = 0; i < nitems(vm->mmio_region); i++) {
877 		if (vm->mmio_region[i].start <= fault_ipa &&
878 		    vm->mmio_region[i].end > fault_ipa) {
879 			vmr = &vm->mmio_region[i];
880 			break;
881 		}
882 	}
883 	if (vmr == NULL)
884 		goto out_user;
885 
886 	error = vmm_emulate_instruction(vcpu, fault_ipa, vie, paging,
887 	    vmr->read, vmr->write, retu);
888 	return (error);
889 
890 out_user:
891 	*retu = true;
892 	return (0);
893 }
894 
895 int
896 vm_suspend(struct vm *vm, enum vm_suspend_how how)
897 {
898 	int i;
899 
900 	if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
901 		return (EINVAL);
902 
903 	if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
904 		VM_CTR2(vm, "virtual machine already suspended %d/%d",
905 		    vm->suspend, how);
906 		return (EALREADY);
907 	}
908 
909 	VM_CTR1(vm, "virtual machine successfully suspended %d", how);
910 
911 	/*
912 	 * Notify all active vcpus that they are now suspended.
913 	 */
914 	for (i = 0; i < vm->maxcpus; i++) {
915 		if (CPU_ISSET(i, &vm->active_cpus))
916 			vcpu_notify_event(vm_vcpu(vm, i));
917 	}
918 
919 	return (0);
920 }
921 
922 void
923 vm_exit_suspended(struct vcpu *vcpu, uint64_t pc)
924 {
925 	struct vm *vm = vcpu->vm;
926 	struct vm_exit *vmexit;
927 
928 	KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
929 	    ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
930 
931 	vmexit = vm_exitinfo(vcpu);
932 	vmexit->pc = pc;
933 	vmexit->inst_length = 4;
934 	vmexit->exitcode = VM_EXITCODE_SUSPENDED;
935 	vmexit->u.suspended.how = vm->suspend;
936 }
937 
938 void
939 vm_exit_debug(struct vcpu *vcpu, uint64_t pc)
940 {
941 	struct vm_exit *vmexit;
942 
943 	vmexit = vm_exitinfo(vcpu);
944 	vmexit->pc = pc;
945 	vmexit->inst_length = 4;
946 	vmexit->exitcode = VM_EXITCODE_DEBUG;
947 }
948 
949 int
950 vm_activate_cpu(struct vcpu *vcpu)
951 {
952 	struct vm *vm = vcpu->vm;
953 
954 	if (CPU_ISSET(vcpu->vcpuid, &vm->active_cpus))
955 		return (EBUSY);
956 
957 	CPU_SET_ATOMIC(vcpu->vcpuid, &vm->active_cpus);
958 	return (0);
959 
960 }
961 
962 int
963 vm_suspend_cpu(struct vm *vm, struct vcpu *vcpu)
964 {
965 	if (vcpu == NULL) {
966 		vm->debug_cpus = vm->active_cpus;
967 		for (int i = 0; i < vm->maxcpus; i++) {
968 			if (CPU_ISSET(i, &vm->active_cpus))
969 				vcpu_notify_event(vm_vcpu(vm, i));
970 		}
971 	} else {
972 		if (!CPU_ISSET(vcpu->vcpuid, &vm->active_cpus))
973 			return (EINVAL);
974 
975 		CPU_SET_ATOMIC(vcpu->vcpuid, &vm->debug_cpus);
976 		vcpu_notify_event(vcpu);
977 	}
978 	return (0);
979 }
980 
981 int
982 vm_resume_cpu(struct vm *vm, struct vcpu *vcpu)
983 {
984 
985 	if (vcpu == NULL) {
986 		CPU_ZERO(&vm->debug_cpus);
987 	} else {
988 		if (!CPU_ISSET(vcpu->vcpuid, &vm->debug_cpus))
989 			return (EINVAL);
990 
991 		CPU_CLR_ATOMIC(vcpu->vcpuid, &vm->debug_cpus);
992 	}
993 	return (0);
994 }
995 
996 int
997 vcpu_debugged(struct vcpu *vcpu)
998 {
999 
1000 	return (CPU_ISSET(vcpu->vcpuid, &vcpu->vm->debug_cpus));
1001 }
1002 
1003 cpuset_t
1004 vm_active_cpus(struct vm *vm)
1005 {
1006 
1007 	return (vm->active_cpus);
1008 }
1009 
1010 cpuset_t
1011 vm_debug_cpus(struct vm *vm)
1012 {
1013 
1014 	return (vm->debug_cpus);
1015 }
1016 
1017 cpuset_t
1018 vm_suspended_cpus(struct vm *vm)
1019 {
1020 
1021 	return (vm->suspended_cpus);
1022 }
1023 
1024 
1025 void *
1026 vcpu_stats(struct vcpu *vcpu)
1027 {
1028 
1029 	return (vcpu->stats);
1030 }
1031 
1032 /*
1033  * This function is called to ensure that a vcpu "sees" a pending event
1034  * as soon as possible:
1035  * - If the vcpu thread is sleeping then it is woken up.
1036  * - If the vcpu is running on a different host_cpu then an IPI will be directed
1037  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
1038  */
1039 static void
1040 vcpu_notify_event_locked(struct vcpu *vcpu)
1041 {
1042 	int hostcpu;
1043 
1044 	hostcpu = vcpu->hostcpu;
1045 	if (vcpu->state == VCPU_RUNNING) {
1046 		KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
1047 		if (hostcpu != curcpu) {
1048 			ipi_cpu(hostcpu, vmm_ipinum);
1049 		} else {
1050 			/*
1051 			 * If the 'vcpu' is running on 'curcpu' then it must
1052 			 * be sending a notification to itself (e.g. SELF_IPI).
1053 			 * The pending event will be picked up when the vcpu
1054 			 * transitions back to guest context.
1055 			 */
1056 		}
1057 	} else {
1058 		KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
1059 		    "with hostcpu %d", vcpu->state, hostcpu));
1060 		if (vcpu->state == VCPU_SLEEPING)
1061 			wakeup_one(vcpu);
1062 	}
1063 }
1064 
1065 void
1066 vcpu_notify_event(struct vcpu *vcpu)
1067 {
1068 	vcpu_lock(vcpu);
1069 	vcpu_notify_event_locked(vcpu);
1070 	vcpu_unlock(vcpu);
1071 }
1072 
1073 static void
1074 restore_guest_fpustate(struct vcpu *vcpu)
1075 {
1076 
1077 	/* Flush host state to the pcb. */
1078 	fpe_state_save(curthread);
1079 
1080 	/* Ensure the VFP state will be re-loaded when exiting the guest. */
1081 	PCPU_SET(fpcurthread, NULL);
1082 
1083 	/* restore guest FPU state */
1084 	fpe_enable();
1085 	fpe_restore(vcpu->guestfpu);
1086 
1087 	/*
1088 	 * The FPU is now "dirty" with the guest's state so turn on emulation
1089 	 * to trap any access to the FPU by the host.
1090 	 */
1091 	fpe_disable();
1092 }
1093 
1094 static void
1095 save_guest_fpustate(struct vcpu *vcpu)
1096 {
1097 
1098 	/* Save guest FPE state. */
1099 	fpe_enable();
1100 	fpe_store(vcpu->guestfpu);
1101 	fpe_disable();
1102 
1103 	KASSERT(PCPU_GET(fpcurthread) == NULL,
1104 	    ("%s: fpcurthread set with guest registers", __func__));
1105 }
1106 
1107 static int
1108 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
1109     bool from_idle)
1110 {
1111 	int error;
1112 
1113 	vcpu_assert_locked(vcpu);
1114 
1115 	/*
1116 	 * State transitions from the vmmdev_ioctl() must always begin from
1117 	 * the VCPU_IDLE state. This guarantees that there is only a single
1118 	 * ioctl() operating on a vcpu at any point.
1119 	 */
1120 	if (from_idle) {
1121 		while (vcpu->state != VCPU_IDLE) {
1122 			vcpu_notify_event_locked(vcpu);
1123 			msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat",
1124 			    hz / 1000);
1125 		}
1126 	} else {
1127 		KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
1128 		    "vcpu idle state"));
1129 	}
1130 
1131 	if (vcpu->state == VCPU_RUNNING) {
1132 		KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
1133 		    "mismatch for running vcpu", curcpu, vcpu->hostcpu));
1134 	} else {
1135 		KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
1136 		    "vcpu that is not running", vcpu->hostcpu));
1137 	}
1138 
1139 	/*
1140 	 * The following state transitions are allowed:
1141 	 * IDLE -> FROZEN -> IDLE
1142 	 * FROZEN -> RUNNING -> FROZEN
1143 	 * FROZEN -> SLEEPING -> FROZEN
1144 	 */
1145 	switch (vcpu->state) {
1146 	case VCPU_IDLE:
1147 	case VCPU_RUNNING:
1148 	case VCPU_SLEEPING:
1149 		error = (newstate != VCPU_FROZEN);
1150 		break;
1151 	case VCPU_FROZEN:
1152 		error = (newstate == VCPU_FROZEN);
1153 		break;
1154 	default:
1155 		error = 1;
1156 		break;
1157 	}
1158 
1159 	if (error)
1160 		return (EBUSY);
1161 
1162 	vcpu->state = newstate;
1163 	if (newstate == VCPU_RUNNING)
1164 		vcpu->hostcpu = curcpu;
1165 	else
1166 		vcpu->hostcpu = NOCPU;
1167 
1168 	if (newstate == VCPU_IDLE)
1169 		wakeup(&vcpu->state);
1170 
1171 	return (0);
1172 }
1173 
1174 static void
1175 vcpu_require_state(struct vcpu *vcpu, enum vcpu_state newstate)
1176 {
1177 	int error;
1178 
1179 	if ((error = vcpu_set_state(vcpu, newstate, false)) != 0)
1180 		panic("Error %d setting state to %d\n", error, newstate);
1181 }
1182 
1183 static void
1184 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
1185 {
1186 	int error;
1187 
1188 	if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
1189 		panic("Error %d setting state to %d", error, newstate);
1190 }
1191 
1192 int
1193 vm_get_capability(struct vcpu *vcpu, int type, int *retval)
1194 {
1195 
1196 	if (type < 0 || type >= VM_CAP_MAX)
1197 		return (EINVAL);
1198 
1199 	return (vmmops_getcap(vcpu->cookie, type, retval));
1200 }
1201 
1202 int
1203 vm_set_capability(struct vcpu *vcpu, int type, int val)
1204 {
1205 
1206 	if (type < 0 || type >= VM_CAP_MAX)
1207 		return (EINVAL);
1208 
1209 	return (vmmops_setcap(vcpu->cookie, type, val));
1210 }
1211 
1212 struct vm *
1213 vcpu_vm(struct vcpu *vcpu)
1214 {
1215 
1216 	return (vcpu->vm);
1217 }
1218 
1219 int
1220 vcpu_vcpuid(struct vcpu *vcpu)
1221 {
1222 
1223 	return (vcpu->vcpuid);
1224 }
1225 
1226 void *
1227 vcpu_get_cookie(struct vcpu *vcpu)
1228 {
1229 
1230 	return (vcpu->cookie);
1231 }
1232 
1233 struct vcpu *
1234 vm_vcpu(struct vm *vm, int vcpuid)
1235 {
1236 
1237 	return (vm->vcpu[vcpuid]);
1238 }
1239 
1240 int
1241 vcpu_set_state(struct vcpu *vcpu, enum vcpu_state newstate, bool from_idle)
1242 {
1243 	int error;
1244 
1245 	vcpu_lock(vcpu);
1246 	error = vcpu_set_state_locked(vcpu, newstate, from_idle);
1247 	vcpu_unlock(vcpu);
1248 
1249 	return (error);
1250 }
1251 
1252 enum vcpu_state
1253 vcpu_get_state(struct vcpu *vcpu, int *hostcpu)
1254 {
1255 	enum vcpu_state state;
1256 
1257 	vcpu_lock(vcpu);
1258 	state = vcpu->state;
1259 	if (hostcpu != NULL)
1260 		*hostcpu = vcpu->hostcpu;
1261 	vcpu_unlock(vcpu);
1262 
1263 	return (state);
1264 }
1265 
1266 static void *
1267 _vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
1268     void **cookie)
1269 {
1270 	int i, count, pageoff;
1271 	struct mem_map *mm;
1272 	vm_page_t m;
1273 
1274 	pageoff = gpa & PAGE_MASK;
1275 	if (len > PAGE_SIZE - pageoff)
1276 		panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
1277 
1278 	count = 0;
1279 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1280 		mm = &vm->mem_maps[i];
1281 		if (sysmem_mapping(vm, mm) && gpa >= mm->gpa &&
1282 		    gpa < mm->gpa + mm->len) {
1283 			count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
1284 			    trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
1285 			break;
1286 		}
1287 	}
1288 
1289 	if (count == 1) {
1290 		*cookie = m;
1291 		return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
1292 	} else {
1293 		*cookie = NULL;
1294 		return (NULL);
1295 	}
1296 }
1297 
1298 void *
1299 vm_gpa_hold(struct vcpu *vcpu, vm_paddr_t gpa, size_t len, int reqprot,
1300 	    void **cookie)
1301 {
1302 #ifdef INVARIANTS
1303 	/*
1304 	 * The current vcpu should be frozen to ensure 'vm_memmap[]'
1305 	 * stability.
1306 	 */
1307 	int state = vcpu_get_state(vcpu, NULL);
1308 	KASSERT(state == VCPU_FROZEN, ("%s: invalid vcpu state %d",
1309 	    __func__, state));
1310 #endif
1311 	return (_vm_gpa_hold(vcpu->vm, gpa, len, reqprot, cookie));
1312 }
1313 
1314 void *
1315 vm_gpa_hold_global(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
1316     void **cookie)
1317 {
1318 	sx_assert(&vm->mem_segs_lock, SX_LOCKED);
1319 	return (_vm_gpa_hold(vm, gpa, len, reqprot, cookie));
1320 }
1321 
1322 void
1323 vm_gpa_release(void *cookie)
1324 {
1325 	vm_page_t m = cookie;
1326 
1327 	vm_page_unwire(m, PQ_ACTIVE);
1328 }
1329 
1330 int
1331 vm_get_register(struct vcpu *vcpu, int reg, uint64_t *retval)
1332 {
1333 
1334 	if (reg >= VM_REG_LAST)
1335 		return (EINVAL);
1336 
1337 	return (vmmops_getreg(vcpu->cookie, reg, retval));
1338 }
1339 
1340 int
1341 vm_set_register(struct vcpu *vcpu, int reg, uint64_t val)
1342 {
1343 	int error;
1344 
1345 	if (reg >= VM_REG_LAST)
1346 		return (EINVAL);
1347 	error = vmmops_setreg(vcpu->cookie, reg, val);
1348 	if (error || reg != VM_REG_GUEST_SEPC)
1349 		return (error);
1350 
1351 	vcpu->nextpc = val;
1352 
1353 	return (0);
1354 }
1355 
1356 void *
1357 vm_get_cookie(struct vm *vm)
1358 {
1359 
1360 	return (vm->cookie);
1361 }
1362 
1363 int
1364 vm_inject_exception(struct vcpu *vcpu, uint64_t scause)
1365 {
1366 
1367 	return (vmmops_exception(vcpu->cookie, scause));
1368 }
1369 
1370 int
1371 vm_attach_aplic(struct vm *vm, struct vm_aplic_descr *descr)
1372 {
1373 
1374 	return (aplic_attach_to_vm(vm->cookie, descr));
1375 }
1376 
1377 int
1378 vm_assert_irq(struct vm *vm, uint32_t irq)
1379 {
1380 
1381 	return (aplic_inject_irq(vm->cookie, -1, irq, true));
1382 }
1383 
1384 int
1385 vm_deassert_irq(struct vm *vm, uint32_t irq)
1386 {
1387 
1388 	return (aplic_inject_irq(vm->cookie, -1, irq, false));
1389 }
1390 
1391 int
1392 vm_raise_msi(struct vm *vm, uint64_t msg, uint64_t addr, int bus, int slot,
1393     int func)
1394 {
1395 
1396 	return (aplic_inject_msi(vm->cookie, msg, addr));
1397 }
1398 
1399 static int
1400 vm_handle_wfi(struct vcpu *vcpu, struct vm_exit *vme, bool *retu)
1401 {
1402 
1403 	vcpu_lock(vcpu);
1404 
1405 	while (1) {
1406 		if (aplic_check_pending(vcpu->cookie))
1407 			break;
1408 
1409 		if (riscv_check_ipi(vcpu->cookie, false))
1410 			break;
1411 
1412 		if (vcpu_should_yield(vcpu))
1413 			break;
1414 
1415 		vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1416 		/*
1417 		 * XXX msleep_spin() cannot be interrupted by signals so
1418 		 * wake up periodically to check pending signals.
1419 		 */
1420 		msleep_spin(vcpu, &vcpu->mtx, "vmidle", hz / 1000);
1421 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1422 	}
1423 	vcpu_unlock(vcpu);
1424 
1425 	*retu = false;
1426 
1427 	return (0);
1428 }
1429 
1430 static int
1431 vm_handle_paging(struct vcpu *vcpu, bool *retu)
1432 {
1433 	struct vm *vm;
1434 	struct vm_exit *vme;
1435 	struct vm_map *map;
1436 	uint64_t addr;
1437 	pmap_t pmap;
1438 	int ftype, rv;
1439 
1440 	vm = vcpu->vm;
1441 	vme = &vcpu->exitinfo;
1442 
1443 	pmap = vmspace_pmap(vm->vmspace);
1444 	addr = (vme->htval << 2) & ~(PAGE_SIZE - 1);
1445 
1446 	dprintf("%s: %lx\n", __func__, addr);
1447 
1448 	switch (vme->scause) {
1449 	case SCAUSE_STORE_GUEST_PAGE_FAULT:
1450 		ftype = VM_PROT_WRITE;
1451 		break;
1452 	case SCAUSE_FETCH_GUEST_PAGE_FAULT:
1453 		ftype = VM_PROT_EXECUTE;
1454 		break;
1455 	case SCAUSE_LOAD_GUEST_PAGE_FAULT:
1456 		ftype = VM_PROT_READ;
1457 		break;
1458 	default:
1459 		panic("unknown page trap: %lu", vme->scause);
1460 	}
1461 
1462 	/* The page exists, but the page table needs to be updated. */
1463 	if (pmap_fault(pmap, addr, ftype))
1464 		return (0);
1465 
1466 	map = &vm->vmspace->vm_map;
1467 	rv = vm_fault(map, addr, ftype, VM_FAULT_NORMAL, NULL);
1468 	if (rv != KERN_SUCCESS) {
1469 		printf("%s: vm_fault failed, addr %lx, ftype %d, err %d\n",
1470 		    __func__, addr, ftype, rv);
1471 		return (EFAULT);
1472 	}
1473 
1474 	return (0);
1475 }
1476 
1477 static int
1478 vm_handle_suspend(struct vcpu *vcpu, bool *retu)
1479 {
1480 	struct vm *vm = vcpu->vm;
1481 	int error, i;
1482 	struct thread *td;
1483 
1484 	error = 0;
1485 	td = curthread;
1486 
1487 	CPU_SET_ATOMIC(vcpu->vcpuid, &vm->suspended_cpus);
1488 
1489 	/*
1490 	 * Wait until all 'active_cpus' have suspended themselves.
1491 	 *
1492 	 * Since a VM may be suspended at any time including when one or
1493 	 * more vcpus are doing a rendezvous we need to call the rendezvous
1494 	 * handler while we are waiting to prevent a deadlock.
1495 	 */
1496 	vcpu_lock(vcpu);
1497 	while (error == 0) {
1498 		if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0)
1499 			break;
1500 
1501 		vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1502 		msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1503 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1504 		if (td_ast_pending(td, TDA_SUSPEND)) {
1505 			vcpu_unlock(vcpu);
1506 			error = thread_check_susp(td, false);
1507 			vcpu_lock(vcpu);
1508 		}
1509 	}
1510 	vcpu_unlock(vcpu);
1511 
1512 	/*
1513 	 * Wakeup the other sleeping vcpus and return to userspace.
1514 	 */
1515 	for (i = 0; i < vm->maxcpus; i++) {
1516 		if (CPU_ISSET(i, &vm->suspended_cpus)) {
1517 			vcpu_notify_event(vm_vcpu(vm, i));
1518 		}
1519 	}
1520 
1521 	*retu = true;
1522 	return (error);
1523 }
1524 
1525 int
1526 vm_run(struct vcpu *vcpu)
1527 {
1528 	struct vm_eventinfo evinfo;
1529 	struct vm_exit *vme;
1530 	struct vm *vm;
1531 	pmap_t pmap;
1532 	int error;
1533 	int vcpuid;
1534 	bool retu;
1535 
1536 	vm = vcpu->vm;
1537 
1538 	dprintf("%s\n", __func__);
1539 
1540 	vcpuid = vcpu->vcpuid;
1541 
1542 	if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1543 		return (EINVAL);
1544 
1545 	if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1546 		return (EINVAL);
1547 
1548 	pmap = vmspace_pmap(vm->vmspace);
1549 	vme = &vcpu->exitinfo;
1550 	evinfo.rptr = NULL;
1551 	evinfo.sptr = &vm->suspend;
1552 	evinfo.iptr = NULL;
1553 restart:
1554 	critical_enter();
1555 
1556 	restore_guest_fpustate(vcpu);
1557 
1558 	vcpu_require_state(vcpu, VCPU_RUNNING);
1559 	error = vmmops_run(vcpu->cookie, vcpu->nextpc, pmap, &evinfo);
1560 	vcpu_require_state(vcpu, VCPU_FROZEN);
1561 
1562 	save_guest_fpustate(vcpu);
1563 
1564 	critical_exit();
1565 
1566 	if (error == 0) {
1567 		retu = false;
1568 		switch (vme->exitcode) {
1569 		case VM_EXITCODE_INST_EMUL:
1570 			vcpu->nextpc = vme->pc + vme->inst_length;
1571 			error = vm_handle_inst_emul(vcpu, &retu);
1572 			break;
1573 		case VM_EXITCODE_WFI:
1574 			vcpu->nextpc = vme->pc + vme->inst_length;
1575 			error = vm_handle_wfi(vcpu, vme, &retu);
1576 			break;
1577 		case VM_EXITCODE_ECALL:
1578 			/* Handle in userland. */
1579 			vcpu->nextpc = vme->pc + vme->inst_length;
1580 			retu = true;
1581 			break;
1582 		case VM_EXITCODE_PAGING:
1583 			vcpu->nextpc = vme->pc;
1584 			error = vm_handle_paging(vcpu, &retu);
1585 			break;
1586 		case VM_EXITCODE_BOGUS:
1587 			vcpu->nextpc = vme->pc;
1588 			retu = false;
1589 			error = 0;
1590 			break;
1591 		case VM_EXITCODE_SUSPENDED:
1592 			vcpu->nextpc = vme->pc;
1593 			error = vm_handle_suspend(vcpu, &retu);
1594 			break;
1595 		default:
1596 			/* Handle in userland. */
1597 			vcpu->nextpc = vme->pc;
1598 			retu = true;
1599 			break;
1600 		}
1601 	}
1602 
1603 	if (error == 0 && retu == false)
1604 		goto restart;
1605 
1606 	return (error);
1607 }
1608