xref: /freebsd/sys/amd64/vmm/vmm.c (revision 9ecd54f24fe9fa373e07c9fd7c052deb2188f545)
1 /*-
2  * Copyright (c) 2011 NetApp, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/module.h>
36 #include <sys/sysctl.h>
37 #include <sys/malloc.h>
38 #include <sys/pcpu.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/proc.h>
42 #include <sys/rwlock.h>
43 #include <sys/sched.h>
44 #include <sys/smp.h>
45 #include <sys/systm.h>
46 
47 #include <vm/vm.h>
48 #include <vm/vm_object.h>
49 #include <vm/vm_page.h>
50 #include <vm/pmap.h>
51 #include <vm/vm_map.h>
52 #include <vm/vm_extern.h>
53 #include <vm/vm_param.h>
54 
55 #include <machine/cpu.h>
56 #include <machine/vm.h>
57 #include <machine/pcb.h>
58 #include <machine/smp.h>
59 #include <x86/psl.h>
60 #include <x86/apicreg.h>
61 #include <machine/vmparam.h>
62 
63 #include <machine/vmm.h>
64 #include <machine/vmm_dev.h>
65 
66 #include "vmm_ktr.h"
67 #include "vmm_host.h"
68 #include "vmm_mem.h"
69 #include "vmm_util.h"
70 #include "vatpic.h"
71 #include "vatpit.h"
72 #include "vhpet.h"
73 #include "vioapic.h"
74 #include "vlapic.h"
75 #include "vmm_msr.h"
76 #include "vmm_ipi.h"
77 #include "vmm_stat.h"
78 #include "vmm_lapic.h"
79 
80 #include "io/ppt.h"
81 #include "io/iommu.h"
82 
83 struct vlapic;
84 
85 struct vcpu {
86 	int		flags;
87 	enum vcpu_state	state;
88 	struct mtx	mtx;
89 	int		hostcpu;	/* host cpuid this vcpu last ran on */
90 	uint64_t	guest_msrs[VMM_MSR_NUM];
91 	struct vlapic	*vlapic;
92 	int		 vcpuid;
93 	struct savefpu	*guestfpu;	/* guest fpu state */
94 	uint64_t	guest_xcr0;
95 	void		*stats;
96 	struct vm_exit	exitinfo;
97 	enum x2apic_state x2apic_state;
98 	int		nmi_pending;
99 	int		extint_pending;
100 	struct vm_exception exception;
101 	int		exception_pending;
102 };
103 
104 #define	vcpu_lock_init(v)	mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
105 #define	vcpu_lock(v)		mtx_lock_spin(&((v)->mtx))
106 #define	vcpu_unlock(v)		mtx_unlock_spin(&((v)->mtx))
107 #define	vcpu_assert_locked(v)	mtx_assert(&((v)->mtx), MA_OWNED)
108 
109 struct mem_seg {
110 	vm_paddr_t	gpa;
111 	size_t		len;
112 	boolean_t	wired;
113 	vm_object_t	object;
114 };
115 #define	VM_MAX_MEMORY_SEGMENTS	2
116 
117 struct vm {
118 	void		*cookie;	/* processor-specific data */
119 	void		*iommu;		/* iommu-specific data */
120 	struct vhpet	*vhpet;		/* virtual HPET */
121 	struct vioapic	*vioapic;	/* virtual ioapic */
122 	struct vatpic	*vatpic;	/* virtual atpic */
123 	struct vatpit	*vatpit;	/* virtual atpit */
124 	struct vmspace	*vmspace;	/* guest's address space */
125 	struct vcpu	vcpu[VM_MAXCPU];
126 	int		num_mem_segs;
127 	struct mem_seg	mem_segs[VM_MAX_MEMORY_SEGMENTS];
128 	char		name[VM_MAX_NAMELEN];
129 
130 	/*
131 	 * Set of active vcpus.
132 	 * An active vcpu is one that has been started implicitly (BSP) or
133 	 * explicitly (AP) by sending it a startup ipi.
134 	 */
135 	volatile cpuset_t active_cpus;
136 
137 	struct mtx	rendezvous_mtx;
138 	cpuset_t	rendezvous_req_cpus;
139 	cpuset_t	rendezvous_done_cpus;
140 	void		*rendezvous_arg;
141 	vm_rendezvous_func_t rendezvous_func;
142 
143 	int		suspend;
144 	volatile cpuset_t suspended_cpus;
145 };
146 
147 static int vmm_initialized;
148 
149 static struct vmm_ops *ops;
150 #define	VMM_INIT(num)	(ops != NULL ? (*ops->init)(num) : 0)
151 #define	VMM_CLEANUP()	(ops != NULL ? (*ops->cleanup)() : 0)
152 #define	VMM_RESUME()	(ops != NULL ? (*ops->resume)() : 0)
153 
154 #define	VMINIT(vm, pmap) (ops != NULL ? (*ops->vminit)(vm, pmap): NULL)
155 #define	VMRUN(vmi, vcpu, rip, pmap, rptr, sptr) \
156 	(ops != NULL ? (*ops->vmrun)(vmi, vcpu, rip, pmap, rptr, sptr) : ENXIO)
157 #define	VMCLEANUP(vmi)	(ops != NULL ? (*ops->vmcleanup)(vmi) : NULL)
158 #define	VMSPACE_ALLOC(min, max) \
159 	(ops != NULL ? (*ops->vmspace_alloc)(min, max) : NULL)
160 #define	VMSPACE_FREE(vmspace) \
161 	(ops != NULL ? (*ops->vmspace_free)(vmspace) : ENXIO)
162 #define	VMGETREG(vmi, vcpu, num, retval)		\
163 	(ops != NULL ? (*ops->vmgetreg)(vmi, vcpu, num, retval) : ENXIO)
164 #define	VMSETREG(vmi, vcpu, num, val)		\
165 	(ops != NULL ? (*ops->vmsetreg)(vmi, vcpu, num, val) : ENXIO)
166 #define	VMGETDESC(vmi, vcpu, num, desc)		\
167 	(ops != NULL ? (*ops->vmgetdesc)(vmi, vcpu, num, desc) : ENXIO)
168 #define	VMSETDESC(vmi, vcpu, num, desc)		\
169 	(ops != NULL ? (*ops->vmsetdesc)(vmi, vcpu, num, desc) : ENXIO)
170 #define	VMGETCAP(vmi, vcpu, num, retval)	\
171 	(ops != NULL ? (*ops->vmgetcap)(vmi, vcpu, num, retval) : ENXIO)
172 #define	VMSETCAP(vmi, vcpu, num, val)		\
173 	(ops != NULL ? (*ops->vmsetcap)(vmi, vcpu, num, val) : ENXIO)
174 #define	VLAPIC_INIT(vmi, vcpu)			\
175 	(ops != NULL ? (*ops->vlapic_init)(vmi, vcpu) : NULL)
176 #define	VLAPIC_CLEANUP(vmi, vlapic)		\
177 	(ops != NULL ? (*ops->vlapic_cleanup)(vmi, vlapic) : NULL)
178 
179 #define	fpu_start_emulating()	load_cr0(rcr0() | CR0_TS)
180 #define	fpu_stop_emulating()	clts()
181 
182 static MALLOC_DEFINE(M_VM, "vm", "vm");
183 CTASSERT(VMM_MSR_NUM <= 64);	/* msr_mask can keep track of up to 64 msrs */
184 
185 /* statistics */
186 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
187 
188 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
189 
190 static int vmm_ipinum;
191 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
192     "IPI vector used for vcpu notifications");
193 
194 static void vm_deactivate_cpu(struct vm *vm, int vcpuid);
195 
196 static void
197 vcpu_cleanup(struct vm *vm, int i)
198 {
199 	struct vcpu *vcpu = &vm->vcpu[i];
200 
201 	VLAPIC_CLEANUP(vm->cookie, vcpu->vlapic);
202 	vmm_stat_free(vcpu->stats);
203 	fpu_save_area_free(vcpu->guestfpu);
204 }
205 
206 static void
207 vcpu_init(struct vm *vm, uint32_t vcpu_id)
208 {
209 	struct vcpu *vcpu;
210 
211 	vcpu = &vm->vcpu[vcpu_id];
212 
213 	vcpu_lock_init(vcpu);
214 	vcpu->hostcpu = NOCPU;
215 	vcpu->vcpuid = vcpu_id;
216 	vcpu->vlapic = VLAPIC_INIT(vm->cookie, vcpu_id);
217 	vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
218 	vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
219 	vcpu->guestfpu = fpu_save_area_alloc();
220 	fpu_save_area_reset(vcpu->guestfpu);
221 	vcpu->stats = vmm_stat_alloc();
222 }
223 
224 struct vm_exit *
225 vm_exitinfo(struct vm *vm, int cpuid)
226 {
227 	struct vcpu *vcpu;
228 
229 	if (cpuid < 0 || cpuid >= VM_MAXCPU)
230 		panic("vm_exitinfo: invalid cpuid %d", cpuid);
231 
232 	vcpu = &vm->vcpu[cpuid];
233 
234 	return (&vcpu->exitinfo);
235 }
236 
237 static void
238 vmm_resume(void)
239 {
240 	VMM_RESUME();
241 }
242 
243 static int
244 vmm_init(void)
245 {
246 	int error;
247 
248 	vmm_host_state_init();
249 
250 	vmm_ipinum = vmm_ipi_alloc();
251 	if (vmm_ipinum == 0)
252 		vmm_ipinum = IPI_AST;
253 
254 	error = vmm_mem_init();
255 	if (error)
256 		return (error);
257 
258 	if (vmm_is_intel())
259 		ops = &vmm_ops_intel;
260 	else if (vmm_is_amd())
261 		ops = &vmm_ops_amd;
262 	else
263 		return (ENXIO);
264 
265 	vmm_msr_init();
266 	vmm_resume_p = vmm_resume;
267 
268 	return (VMM_INIT(vmm_ipinum));
269 }
270 
271 static int
272 vmm_handler(module_t mod, int what, void *arg)
273 {
274 	int error;
275 
276 	switch (what) {
277 	case MOD_LOAD:
278 		vmmdev_init();
279 		if (ppt_avail_devices() > 0)
280 			iommu_init();
281 		error = vmm_init();
282 		if (error == 0)
283 			vmm_initialized = 1;
284 		break;
285 	case MOD_UNLOAD:
286 		error = vmmdev_cleanup();
287 		if (error == 0) {
288 			vmm_resume_p = NULL;
289 			iommu_cleanup();
290 			if (vmm_ipinum != IPI_AST)
291 				vmm_ipi_free(vmm_ipinum);
292 			error = VMM_CLEANUP();
293 			/*
294 			 * Something bad happened - prevent new
295 			 * VMs from being created
296 			 */
297 			if (error)
298 				vmm_initialized = 0;
299 		}
300 		break;
301 	default:
302 		error = 0;
303 		break;
304 	}
305 	return (error);
306 }
307 
308 static moduledata_t vmm_kmod = {
309 	"vmm",
310 	vmm_handler,
311 	NULL
312 };
313 
314 /*
315  * vmm initialization has the following dependencies:
316  *
317  * - iommu initialization must happen after the pci passthru driver has had
318  *   a chance to attach to any passthru devices (after SI_SUB_CONFIGURE).
319  *
320  * - VT-x initialization requires smp_rendezvous() and therefore must happen
321  *   after SMP is fully functional (after SI_SUB_SMP).
322  */
323 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
324 MODULE_VERSION(vmm, 1);
325 
326 int
327 vm_create(const char *name, struct vm **retvm)
328 {
329 	int i;
330 	struct vm *vm;
331 	struct vmspace *vmspace;
332 
333 	const int BSP = 0;
334 
335 	/*
336 	 * If vmm.ko could not be successfully initialized then don't attempt
337 	 * to create the virtual machine.
338 	 */
339 	if (!vmm_initialized)
340 		return (ENXIO);
341 
342 	if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
343 		return (EINVAL);
344 
345 	vmspace = VMSPACE_ALLOC(VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS);
346 	if (vmspace == NULL)
347 		return (ENOMEM);
348 
349 	vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
350 	strcpy(vm->name, name);
351 	vm->vmspace = vmspace;
352 	mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
353 	vm->cookie = VMINIT(vm, vmspace_pmap(vmspace));
354 	vm->vioapic = vioapic_init(vm);
355 	vm->vhpet = vhpet_init(vm);
356 	vm->vatpic = vatpic_init(vm);
357 	vm->vatpit = vatpit_init(vm);
358 
359 	for (i = 0; i < VM_MAXCPU; i++) {
360 		vcpu_init(vm, i);
361 		guest_msrs_init(vm, i);
362 	}
363 
364 	vm_activate_cpu(vm, BSP);
365 
366 	*retvm = vm;
367 	return (0);
368 }
369 
370 static void
371 vm_free_mem_seg(struct vm *vm, struct mem_seg *seg)
372 {
373 
374 	if (seg->object != NULL)
375 		vmm_mem_free(vm->vmspace, seg->gpa, seg->len);
376 
377 	bzero(seg, sizeof(*seg));
378 }
379 
380 void
381 vm_destroy(struct vm *vm)
382 {
383 	int i;
384 
385 	ppt_unassign_all(vm);
386 
387 	if (vm->iommu != NULL)
388 		iommu_destroy_domain(vm->iommu);
389 
390 	vatpit_cleanup(vm->vatpit);
391 	vhpet_cleanup(vm->vhpet);
392 	vatpic_cleanup(vm->vatpic);
393 	vioapic_cleanup(vm->vioapic);
394 
395 	for (i = 0; i < vm->num_mem_segs; i++)
396 		vm_free_mem_seg(vm, &vm->mem_segs[i]);
397 
398 	vm->num_mem_segs = 0;
399 
400 	for (i = 0; i < VM_MAXCPU; i++)
401 		vcpu_cleanup(vm, i);
402 
403 	VMSPACE_FREE(vm->vmspace);
404 
405 	VMCLEANUP(vm->cookie);
406 
407 	free(vm, M_VM);
408 }
409 
410 const char *
411 vm_name(struct vm *vm)
412 {
413 	return (vm->name);
414 }
415 
416 int
417 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
418 {
419 	vm_object_t obj;
420 
421 	if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
422 		return (ENOMEM);
423 	else
424 		return (0);
425 }
426 
427 int
428 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
429 {
430 
431 	vmm_mmio_free(vm->vmspace, gpa, len);
432 	return (0);
433 }
434 
435 boolean_t
436 vm_mem_allocated(struct vm *vm, vm_paddr_t gpa)
437 {
438 	int i;
439 	vm_paddr_t gpabase, gpalimit;
440 
441 	for (i = 0; i < vm->num_mem_segs; i++) {
442 		gpabase = vm->mem_segs[i].gpa;
443 		gpalimit = gpabase + vm->mem_segs[i].len;
444 		if (gpa >= gpabase && gpa < gpalimit)
445 			return (TRUE);		/* 'gpa' is regular memory */
446 	}
447 
448 	if (ppt_is_mmio(vm, gpa))
449 		return (TRUE);			/* 'gpa' is pci passthru mmio */
450 
451 	return (FALSE);
452 }
453 
454 int
455 vm_malloc(struct vm *vm, vm_paddr_t gpa, size_t len)
456 {
457 	int available, allocated;
458 	struct mem_seg *seg;
459 	vm_object_t object;
460 	vm_paddr_t g;
461 
462 	if ((gpa & PAGE_MASK) || (len & PAGE_MASK) || len == 0)
463 		return (EINVAL);
464 
465 	available = allocated = 0;
466 	g = gpa;
467 	while (g < gpa + len) {
468 		if (vm_mem_allocated(vm, g))
469 			allocated++;
470 		else
471 			available++;
472 
473 		g += PAGE_SIZE;
474 	}
475 
476 	/*
477 	 * If there are some allocated and some available pages in the address
478 	 * range then it is an error.
479 	 */
480 	if (allocated && available)
481 		return (EINVAL);
482 
483 	/*
484 	 * If the entire address range being requested has already been
485 	 * allocated then there isn't anything more to do.
486 	 */
487 	if (allocated && available == 0)
488 		return (0);
489 
490 	if (vm->num_mem_segs >= VM_MAX_MEMORY_SEGMENTS)
491 		return (E2BIG);
492 
493 	seg = &vm->mem_segs[vm->num_mem_segs];
494 
495 	if ((object = vmm_mem_alloc(vm->vmspace, gpa, len)) == NULL)
496 		return (ENOMEM);
497 
498 	seg->gpa = gpa;
499 	seg->len = len;
500 	seg->object = object;
501 	seg->wired = FALSE;
502 
503 	vm->num_mem_segs++;
504 
505 	return (0);
506 }
507 
508 static void
509 vm_gpa_unwire(struct vm *vm)
510 {
511 	int i, rv;
512 	struct mem_seg *seg;
513 
514 	for (i = 0; i < vm->num_mem_segs; i++) {
515 		seg = &vm->mem_segs[i];
516 		if (!seg->wired)
517 			continue;
518 
519 		rv = vm_map_unwire(&vm->vmspace->vm_map,
520 				   seg->gpa, seg->gpa + seg->len,
521 				   VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
522 		KASSERT(rv == KERN_SUCCESS, ("vm(%s) memory segment "
523 		    "%#lx/%ld could not be unwired: %d",
524 		    vm_name(vm), seg->gpa, seg->len, rv));
525 
526 		seg->wired = FALSE;
527 	}
528 }
529 
530 static int
531 vm_gpa_wire(struct vm *vm)
532 {
533 	int i, rv;
534 	struct mem_seg *seg;
535 
536 	for (i = 0; i < vm->num_mem_segs; i++) {
537 		seg = &vm->mem_segs[i];
538 		if (seg->wired)
539 			continue;
540 
541 		/* XXX rlimits? */
542 		rv = vm_map_wire(&vm->vmspace->vm_map,
543 				 seg->gpa, seg->gpa + seg->len,
544 				 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
545 		if (rv != KERN_SUCCESS)
546 			break;
547 
548 		seg->wired = TRUE;
549 	}
550 
551 	if (i < vm->num_mem_segs) {
552 		/*
553 		 * Undo the wiring before returning an error.
554 		 */
555 		vm_gpa_unwire(vm);
556 		return (EAGAIN);
557 	}
558 
559 	return (0);
560 }
561 
562 static void
563 vm_iommu_modify(struct vm *vm, boolean_t map)
564 {
565 	int i, sz;
566 	vm_paddr_t gpa, hpa;
567 	struct mem_seg *seg;
568 	void *vp, *cookie, *host_domain;
569 
570 	sz = PAGE_SIZE;
571 	host_domain = iommu_host_domain();
572 
573 	for (i = 0; i < vm->num_mem_segs; i++) {
574 		seg = &vm->mem_segs[i];
575 		KASSERT(seg->wired, ("vm(%s) memory segment %#lx/%ld not wired",
576 		    vm_name(vm), seg->gpa, seg->len));
577 
578 		gpa = seg->gpa;
579 		while (gpa < seg->gpa + seg->len) {
580 			vp = vm_gpa_hold(vm, gpa, PAGE_SIZE, VM_PROT_WRITE,
581 					 &cookie);
582 			KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
583 			    vm_name(vm), gpa));
584 
585 			vm_gpa_release(cookie);
586 
587 			hpa = DMAP_TO_PHYS((uintptr_t)vp);
588 			if (map) {
589 				iommu_create_mapping(vm->iommu, gpa, hpa, sz);
590 				iommu_remove_mapping(host_domain, hpa, sz);
591 			} else {
592 				iommu_remove_mapping(vm->iommu, gpa, sz);
593 				iommu_create_mapping(host_domain, hpa, hpa, sz);
594 			}
595 
596 			gpa += PAGE_SIZE;
597 		}
598 	}
599 
600 	/*
601 	 * Invalidate the cached translations associated with the domain
602 	 * from which pages were removed.
603 	 */
604 	if (map)
605 		iommu_invalidate_tlb(host_domain);
606 	else
607 		iommu_invalidate_tlb(vm->iommu);
608 }
609 
610 #define	vm_iommu_unmap(vm)	vm_iommu_modify((vm), FALSE)
611 #define	vm_iommu_map(vm)	vm_iommu_modify((vm), TRUE)
612 
613 int
614 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
615 {
616 	int error;
617 
618 	error = ppt_unassign_device(vm, bus, slot, func);
619 	if (error)
620 		return (error);
621 
622 	if (ppt_assigned_devices(vm) == 0) {
623 		vm_iommu_unmap(vm);
624 		vm_gpa_unwire(vm);
625 	}
626 	return (0);
627 }
628 
629 int
630 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
631 {
632 	int error;
633 	vm_paddr_t maxaddr;
634 
635 	/*
636 	 * Virtual machines with pci passthru devices get special treatment:
637 	 * - the guest physical memory is wired
638 	 * - the iommu is programmed to do the 'gpa' to 'hpa' translation
639 	 *
640 	 * We need to do this before the first pci passthru device is attached.
641 	 */
642 	if (ppt_assigned_devices(vm) == 0) {
643 		KASSERT(vm->iommu == NULL,
644 		    ("vm_assign_pptdev: iommu must be NULL"));
645 		maxaddr = vmm_mem_maxaddr();
646 		vm->iommu = iommu_create_domain(maxaddr);
647 
648 		error = vm_gpa_wire(vm);
649 		if (error)
650 			return (error);
651 
652 		vm_iommu_map(vm);
653 	}
654 
655 	error = ppt_assign_device(vm, bus, slot, func);
656 	return (error);
657 }
658 
659 void *
660 vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
661 	    void **cookie)
662 {
663 	int count, pageoff;
664 	vm_page_t m;
665 
666 	pageoff = gpa & PAGE_MASK;
667 	if (len > PAGE_SIZE - pageoff)
668 		panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
669 
670 	count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
671 	    trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
672 
673 	if (count == 1) {
674 		*cookie = m;
675 		return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
676 	} else {
677 		*cookie = NULL;
678 		return (NULL);
679 	}
680 }
681 
682 void
683 vm_gpa_release(void *cookie)
684 {
685 	vm_page_t m = cookie;
686 
687 	vm_page_lock(m);
688 	vm_page_unhold(m);
689 	vm_page_unlock(m);
690 }
691 
692 int
693 vm_gpabase2memseg(struct vm *vm, vm_paddr_t gpabase,
694 		  struct vm_memory_segment *seg)
695 {
696 	int i;
697 
698 	for (i = 0; i < vm->num_mem_segs; i++) {
699 		if (gpabase == vm->mem_segs[i].gpa) {
700 			seg->gpa = vm->mem_segs[i].gpa;
701 			seg->len = vm->mem_segs[i].len;
702 			seg->wired = vm->mem_segs[i].wired;
703 			return (0);
704 		}
705 	}
706 	return (-1);
707 }
708 
709 int
710 vm_get_memobj(struct vm *vm, vm_paddr_t gpa, size_t len,
711 	      vm_offset_t *offset, struct vm_object **object)
712 {
713 	int i;
714 	size_t seg_len;
715 	vm_paddr_t seg_gpa;
716 	vm_object_t seg_obj;
717 
718 	for (i = 0; i < vm->num_mem_segs; i++) {
719 		if ((seg_obj = vm->mem_segs[i].object) == NULL)
720 			continue;
721 
722 		seg_gpa = vm->mem_segs[i].gpa;
723 		seg_len = vm->mem_segs[i].len;
724 
725 		if (gpa >= seg_gpa && gpa < seg_gpa + seg_len) {
726 			*offset = gpa - seg_gpa;
727 			*object = seg_obj;
728 			vm_object_reference(seg_obj);
729 			return (0);
730 		}
731 	}
732 
733 	return (EINVAL);
734 }
735 
736 int
737 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
738 {
739 
740 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
741 		return (EINVAL);
742 
743 	if (reg >= VM_REG_LAST)
744 		return (EINVAL);
745 
746 	return (VMGETREG(vm->cookie, vcpu, reg, retval));
747 }
748 
749 int
750 vm_set_register(struct vm *vm, int vcpu, int reg, uint64_t val)
751 {
752 
753 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
754 		return (EINVAL);
755 
756 	if (reg >= VM_REG_LAST)
757 		return (EINVAL);
758 
759 	return (VMSETREG(vm->cookie, vcpu, reg, val));
760 }
761 
762 static boolean_t
763 is_descriptor_table(int reg)
764 {
765 
766 	switch (reg) {
767 	case VM_REG_GUEST_IDTR:
768 	case VM_REG_GUEST_GDTR:
769 		return (TRUE);
770 	default:
771 		return (FALSE);
772 	}
773 }
774 
775 static boolean_t
776 is_segment_register(int reg)
777 {
778 
779 	switch (reg) {
780 	case VM_REG_GUEST_ES:
781 	case VM_REG_GUEST_CS:
782 	case VM_REG_GUEST_SS:
783 	case VM_REG_GUEST_DS:
784 	case VM_REG_GUEST_FS:
785 	case VM_REG_GUEST_GS:
786 	case VM_REG_GUEST_TR:
787 	case VM_REG_GUEST_LDTR:
788 		return (TRUE);
789 	default:
790 		return (FALSE);
791 	}
792 }
793 
794 int
795 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
796 		struct seg_desc *desc)
797 {
798 
799 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
800 		return (EINVAL);
801 
802 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
803 		return (EINVAL);
804 
805 	return (VMGETDESC(vm->cookie, vcpu, reg, desc));
806 }
807 
808 int
809 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
810 		struct seg_desc *desc)
811 {
812 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
813 		return (EINVAL);
814 
815 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
816 		return (EINVAL);
817 
818 	return (VMSETDESC(vm->cookie, vcpu, reg, desc));
819 }
820 
821 static void
822 restore_guest_fpustate(struct vcpu *vcpu)
823 {
824 
825 	/* flush host state to the pcb */
826 	fpuexit(curthread);
827 
828 	/* restore guest FPU state */
829 	fpu_stop_emulating();
830 	fpurestore(vcpu->guestfpu);
831 
832 	/* restore guest XCR0 if XSAVE is enabled in the host */
833 	if (rcr4() & CR4_XSAVE)
834 		load_xcr(0, vcpu->guest_xcr0);
835 
836 	/*
837 	 * The FPU is now "dirty" with the guest's state so turn on emulation
838 	 * to trap any access to the FPU by the host.
839 	 */
840 	fpu_start_emulating();
841 }
842 
843 static void
844 save_guest_fpustate(struct vcpu *vcpu)
845 {
846 
847 	if ((rcr0() & CR0_TS) == 0)
848 		panic("fpu emulation not enabled in host!");
849 
850 	/* save guest XCR0 and restore host XCR0 */
851 	if (rcr4() & CR4_XSAVE) {
852 		vcpu->guest_xcr0 = rxcr(0);
853 		load_xcr(0, vmm_get_host_xcr0());
854 	}
855 
856 	/* save guest FPU state */
857 	fpu_stop_emulating();
858 	fpusave(vcpu->guestfpu);
859 	fpu_start_emulating();
860 }
861 
862 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
863 
864 static int
865 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
866     bool from_idle)
867 {
868 	int error;
869 
870 	vcpu_assert_locked(vcpu);
871 
872 	/*
873 	 * State transitions from the vmmdev_ioctl() must always begin from
874 	 * the VCPU_IDLE state. This guarantees that there is only a single
875 	 * ioctl() operating on a vcpu at any point.
876 	 */
877 	if (from_idle) {
878 		while (vcpu->state != VCPU_IDLE)
879 			msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
880 	} else {
881 		KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
882 		    "vcpu idle state"));
883 	}
884 
885 	if (vcpu->state == VCPU_RUNNING) {
886 		KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
887 		    "mismatch for running vcpu", curcpu, vcpu->hostcpu));
888 	} else {
889 		KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
890 		    "vcpu that is not running", vcpu->hostcpu));
891 	}
892 
893 	/*
894 	 * The following state transitions are allowed:
895 	 * IDLE -> FROZEN -> IDLE
896 	 * FROZEN -> RUNNING -> FROZEN
897 	 * FROZEN -> SLEEPING -> FROZEN
898 	 */
899 	switch (vcpu->state) {
900 	case VCPU_IDLE:
901 	case VCPU_RUNNING:
902 	case VCPU_SLEEPING:
903 		error = (newstate != VCPU_FROZEN);
904 		break;
905 	case VCPU_FROZEN:
906 		error = (newstate == VCPU_FROZEN);
907 		break;
908 	default:
909 		error = 1;
910 		break;
911 	}
912 
913 	if (error)
914 		return (EBUSY);
915 
916 	vcpu->state = newstate;
917 	if (newstate == VCPU_RUNNING)
918 		vcpu->hostcpu = curcpu;
919 	else
920 		vcpu->hostcpu = NOCPU;
921 
922 	if (newstate == VCPU_IDLE)
923 		wakeup(&vcpu->state);
924 
925 	return (0);
926 }
927 
928 static void
929 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
930 {
931 	int error;
932 
933 	if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
934 		panic("Error %d setting state to %d\n", error, newstate);
935 }
936 
937 static void
938 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
939 {
940 	int error;
941 
942 	if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
943 		panic("Error %d setting state to %d", error, newstate);
944 }
945 
946 static void
947 vm_set_rendezvous_func(struct vm *vm, vm_rendezvous_func_t func)
948 {
949 
950 	KASSERT(mtx_owned(&vm->rendezvous_mtx), ("rendezvous_mtx not locked"));
951 
952 	/*
953 	 * Update 'rendezvous_func' and execute a write memory barrier to
954 	 * ensure that it is visible across all host cpus. This is not needed
955 	 * for correctness but it does ensure that all the vcpus will notice
956 	 * that the rendezvous is requested immediately.
957 	 */
958 	vm->rendezvous_func = func;
959 	wmb();
960 }
961 
962 #define	RENDEZVOUS_CTR0(vm, vcpuid, fmt)				\
963 	do {								\
964 		if (vcpuid >= 0)					\
965 			VCPU_CTR0(vm, vcpuid, fmt);			\
966 		else							\
967 			VM_CTR0(vm, fmt);				\
968 	} while (0)
969 
970 static void
971 vm_handle_rendezvous(struct vm *vm, int vcpuid)
972 {
973 
974 	KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
975 	    ("vm_handle_rendezvous: invalid vcpuid %d", vcpuid));
976 
977 	mtx_lock(&vm->rendezvous_mtx);
978 	while (vm->rendezvous_func != NULL) {
979 		/* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
980 		CPU_AND(&vm->rendezvous_req_cpus, &vm->active_cpus);
981 
982 		if (vcpuid != -1 &&
983 		    CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
984 		    !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
985 			VCPU_CTR0(vm, vcpuid, "Calling rendezvous func");
986 			(*vm->rendezvous_func)(vm, vcpuid, vm->rendezvous_arg);
987 			CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
988 		}
989 		if (CPU_CMP(&vm->rendezvous_req_cpus,
990 		    &vm->rendezvous_done_cpus) == 0) {
991 			VCPU_CTR0(vm, vcpuid, "Rendezvous completed");
992 			vm_set_rendezvous_func(vm, NULL);
993 			wakeup(&vm->rendezvous_func);
994 			break;
995 		}
996 		RENDEZVOUS_CTR0(vm, vcpuid, "Wait for rendezvous completion");
997 		mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
998 		    "vmrndv", 0);
999 	}
1000 	mtx_unlock(&vm->rendezvous_mtx);
1001 }
1002 
1003 /*
1004  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1005  */
1006 static int
1007 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled, bool *retu)
1008 {
1009 	struct vm_exit *vmexit;
1010 	struct vcpu *vcpu;
1011 	int t, timo, spindown;
1012 
1013 	vcpu = &vm->vcpu[vcpuid];
1014 	spindown = 0;
1015 
1016 	vcpu_lock(vcpu);
1017 
1018 	/*
1019 	 * Do a final check for pending NMI or interrupts before
1020 	 * really putting this thread to sleep.
1021 	 *
1022 	 * These interrupts could have happened any time after we
1023 	 * returned from VMRUN() and before we grabbed the vcpu lock.
1024 	 */
1025 	if (vm->rendezvous_func == NULL &&
1026 	    !vm_nmi_pending(vm, vcpuid) &&
1027 	    (intr_disabled || !vlapic_pending_intr(vcpu->vlapic, NULL))) {
1028 		t = ticks;
1029 		vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1030 		if (vlapic_enabled(vcpu->vlapic)) {
1031 			/*
1032 			 * XXX msleep_spin() is not interruptible so use the
1033 			 * 'timo' to put an upper bound on the sleep time.
1034 			 */
1035 			timo = hz;
1036 			msleep_spin(vcpu, &vcpu->mtx, "vmidle", timo);
1037 		} else {
1038 			/*
1039 			 * Spindown the vcpu if the APIC is disabled and it
1040 			 * had entered the halted state, but never spin
1041 			 * down the BSP.
1042 			 */
1043 			if (vcpuid != 0)
1044 				spindown = 1;
1045 		}
1046 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1047 		vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1048 	}
1049 	vcpu_unlock(vcpu);
1050 
1051 	/*
1052 	 * Since 'vm_deactivate_cpu()' grabs a sleep mutex we must call it
1053 	 * outside the confines of the vcpu spinlock.
1054 	 */
1055 	if (spindown) {
1056 		*retu = true;
1057 		vmexit = vm_exitinfo(vm, vcpuid);
1058 		vmexit->exitcode = VM_EXITCODE_SPINDOWN_CPU;
1059 		vm_deactivate_cpu(vm, vcpuid);
1060 		VCPU_CTR0(vm, vcpuid, "spinning down cpu");
1061 	}
1062 
1063 	return (0);
1064 }
1065 
1066 static int
1067 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1068 {
1069 	int rv, ftype;
1070 	struct vm_map *map;
1071 	struct vcpu *vcpu;
1072 	struct vm_exit *vme;
1073 
1074 	vcpu = &vm->vcpu[vcpuid];
1075 	vme = &vcpu->exitinfo;
1076 
1077 	ftype = vme->u.paging.fault_type;
1078 	KASSERT(ftype == VM_PROT_READ ||
1079 	    ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1080 	    ("vm_handle_paging: invalid fault_type %d", ftype));
1081 
1082 	if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1083 		rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1084 		    vme->u.paging.gpa, ftype);
1085 		if (rv == 0)
1086 			goto done;
1087 	}
1088 
1089 	map = &vm->vmspace->vm_map;
1090 	rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
1091 
1092 	VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1093 	    "ftype = %d", rv, vme->u.paging.gpa, ftype);
1094 
1095 	if (rv != KERN_SUCCESS)
1096 		return (EFAULT);
1097 done:
1098 	/* restart execution at the faulting instruction */
1099 	vme->inst_length = 0;
1100 
1101 	return (0);
1102 }
1103 
1104 static int
1105 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1106 {
1107 	struct vie *vie;
1108 	struct vcpu *vcpu;
1109 	struct vm_exit *vme;
1110 	int error, inst_length;
1111 	uint64_t rip, gla, gpa, cr3;
1112 	enum vie_cpu_mode cpu_mode;
1113 	enum vie_paging_mode paging_mode;
1114 	mem_region_read_t mread;
1115 	mem_region_write_t mwrite;
1116 
1117 	vcpu = &vm->vcpu[vcpuid];
1118 	vme = &vcpu->exitinfo;
1119 
1120 	rip = vme->rip;
1121 	inst_length = vme->inst_length;
1122 
1123 	gla = vme->u.inst_emul.gla;
1124 	gpa = vme->u.inst_emul.gpa;
1125 	cr3 = vme->u.inst_emul.cr3;
1126 	cpu_mode = vme->u.inst_emul.cpu_mode;
1127 	paging_mode = vme->u.inst_emul.paging_mode;
1128 	vie = &vme->u.inst_emul.vie;
1129 
1130 	vie_init(vie);
1131 
1132 	/* Fetch, decode and emulate the faulting instruction */
1133 	if (vmm_fetch_instruction(vm, vcpuid, rip, inst_length, cr3,
1134 	    paging_mode, vie) != 0)
1135 		return (EFAULT);
1136 
1137 	if (vmm_decode_instruction(vm, vcpuid, gla, cpu_mode, vie) != 0)
1138 		return (EFAULT);
1139 
1140 	/* return to userland unless this is an in-kernel emulated device */
1141 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1142 		mread = lapic_mmio_read;
1143 		mwrite = lapic_mmio_write;
1144 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1145 		mread = vioapic_mmio_read;
1146 		mwrite = vioapic_mmio_write;
1147 	} else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1148 		mread = vhpet_mmio_read;
1149 		mwrite = vhpet_mmio_write;
1150 	} else {
1151 		*retu = true;
1152 		return (0);
1153 	}
1154 
1155 	error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, mread, mwrite,
1156 	    retu);
1157 
1158 	return (error);
1159 }
1160 
1161 static int
1162 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1163 {
1164 	int i, done;
1165 	struct vcpu *vcpu;
1166 
1167 	done = 0;
1168 	vcpu = &vm->vcpu[vcpuid];
1169 
1170 	CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1171 
1172 	/*
1173 	 * Wait until all 'active_cpus' have suspended themselves.
1174 	 *
1175 	 * Since a VM may be suspended at any time including when one or
1176 	 * more vcpus are doing a rendezvous we need to call the rendezvous
1177 	 * handler while we are waiting to prevent a deadlock.
1178 	 */
1179 	vcpu_lock(vcpu);
1180 	while (1) {
1181 		if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1182 			VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1183 			break;
1184 		}
1185 
1186 		if (vm->rendezvous_func == NULL) {
1187 			VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1188 			vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1189 			msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1190 			vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1191 		} else {
1192 			VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1193 			vcpu_unlock(vcpu);
1194 			vm_handle_rendezvous(vm, vcpuid);
1195 			vcpu_lock(vcpu);
1196 		}
1197 	}
1198 	vcpu_unlock(vcpu);
1199 
1200 	/*
1201 	 * Wakeup the other sleeping vcpus and return to userspace.
1202 	 */
1203 	for (i = 0; i < VM_MAXCPU; i++) {
1204 		if (CPU_ISSET(i, &vm->suspended_cpus)) {
1205 			vcpu_notify_event(vm, i, false);
1206 		}
1207 	}
1208 
1209 	*retu = true;
1210 	return (0);
1211 }
1212 
1213 int
1214 vm_suspend(struct vm *vm)
1215 {
1216 
1217 	if (atomic_cmpset_int(&vm->suspend, 0, 1)) {
1218 		VM_CTR0(vm, "virtual machine suspended");
1219 		return (0);
1220 	} else {
1221 		VM_CTR0(vm, "virtual machine already suspended");
1222 		return (EALREADY);
1223 	}
1224 }
1225 
1226 int
1227 vm_run(struct vm *vm, struct vm_run *vmrun)
1228 {
1229 	int error, vcpuid;
1230 	struct vcpu *vcpu;
1231 	struct pcb *pcb;
1232 	uint64_t tscval, rip;
1233 	struct vm_exit *vme;
1234 	bool retu, intr_disabled;
1235 	pmap_t pmap;
1236 	void *rptr, *sptr;
1237 
1238 	vcpuid = vmrun->cpuid;
1239 
1240 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1241 		return (EINVAL);
1242 
1243 	rptr = &vm->rendezvous_func;
1244 	sptr = &vm->suspend;
1245 	pmap = vmspace_pmap(vm->vmspace);
1246 	vcpu = &vm->vcpu[vcpuid];
1247 	vme = &vcpu->exitinfo;
1248 	rip = vmrun->rip;
1249 restart:
1250 	critical_enter();
1251 
1252 	KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1253 	    ("vm_run: absurd pm_active"));
1254 
1255 	tscval = rdtsc();
1256 
1257 	pcb = PCPU_GET(curpcb);
1258 	set_pcb_flags(pcb, PCB_FULL_IRET);
1259 
1260 	restore_guest_msrs(vm, vcpuid);
1261 	restore_guest_fpustate(vcpu);
1262 
1263 	vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1264 	error = VMRUN(vm->cookie, vcpuid, rip, pmap, rptr, sptr);
1265 	vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1266 
1267 	save_guest_fpustate(vcpu);
1268 	restore_host_msrs(vm, vcpuid);
1269 
1270 	vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1271 
1272 	critical_exit();
1273 
1274 	if (error == 0) {
1275 		retu = false;
1276 		switch (vme->exitcode) {
1277 		case VM_EXITCODE_SUSPENDED:
1278 			error = vm_handle_suspend(vm, vcpuid, &retu);
1279 			break;
1280 		case VM_EXITCODE_IOAPIC_EOI:
1281 			vioapic_process_eoi(vm, vcpuid,
1282 			    vme->u.ioapic_eoi.vector);
1283 			break;
1284 		case VM_EXITCODE_RENDEZVOUS:
1285 			vm_handle_rendezvous(vm, vcpuid);
1286 			error = 0;
1287 			break;
1288 		case VM_EXITCODE_HLT:
1289 			intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1290 			error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1291 			break;
1292 		case VM_EXITCODE_PAGING:
1293 			error = vm_handle_paging(vm, vcpuid, &retu);
1294 			break;
1295 		case VM_EXITCODE_INST_EMUL:
1296 			error = vm_handle_inst_emul(vm, vcpuid, &retu);
1297 			break;
1298 		default:
1299 			retu = true;	/* handled in userland */
1300 			break;
1301 		}
1302 	}
1303 
1304 	if (error == 0 && retu == false) {
1305 		rip = vme->rip + vme->inst_length;
1306 		goto restart;
1307 	}
1308 
1309 	/* copy the exit information */
1310 	bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1311 	return (error);
1312 }
1313 
1314 int
1315 vm_inject_exception(struct vm *vm, int vcpuid, struct vm_exception *exception)
1316 {
1317 	struct vcpu *vcpu;
1318 
1319 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1320 		return (EINVAL);
1321 
1322 	if (exception->vector < 0 || exception->vector >= 32)
1323 		return (EINVAL);
1324 
1325 	vcpu = &vm->vcpu[vcpuid];
1326 
1327 	if (vcpu->exception_pending) {
1328 		VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
1329 		    "pending exception %d", exception->vector,
1330 		    vcpu->exception.vector);
1331 		return (EBUSY);
1332 	}
1333 
1334 	vcpu->exception_pending = 1;
1335 	vcpu->exception = *exception;
1336 	VCPU_CTR1(vm, vcpuid, "Exception %d pending", exception->vector);
1337 	return (0);
1338 }
1339 
1340 int
1341 vm_exception_pending(struct vm *vm, int vcpuid, struct vm_exception *exception)
1342 {
1343 	struct vcpu *vcpu;
1344 	int pending;
1345 
1346 	KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU, ("invalid vcpu %d", vcpuid));
1347 
1348 	vcpu = &vm->vcpu[vcpuid];
1349 	pending = vcpu->exception_pending;
1350 	if (pending) {
1351 		vcpu->exception_pending = 0;
1352 		*exception = vcpu->exception;
1353 		VCPU_CTR1(vm, vcpuid, "Exception %d delivered",
1354 		    exception->vector);
1355 	}
1356 	return (pending);
1357 }
1358 
1359 static void
1360 vm_inject_fault(struct vm *vm, int vcpuid, struct vm_exception *exception)
1361 {
1362 	struct vm_exit *vmexit;
1363 	int error;
1364 
1365 	error = vm_inject_exception(vm, vcpuid, exception);
1366 	KASSERT(error == 0, ("vm_inject_exception error %d", error));
1367 
1368 	/*
1369 	 * A fault-like exception allows the instruction to be restarted
1370 	 * after the exception handler returns.
1371 	 *
1372 	 * By setting the inst_length to 0 we ensure that the instruction
1373 	 * pointer remains at the faulting instruction.
1374 	 */
1375 	vmexit = vm_exitinfo(vm, vcpuid);
1376 	vmexit->inst_length = 0;
1377 }
1378 
1379 void
1380 vm_inject_gp(struct vm *vm, int vcpuid)
1381 {
1382 	struct vm_exception gpf = {
1383 		.vector = IDT_GP,
1384 		.error_code_valid = 1,
1385 		.error_code = 0
1386 	};
1387 
1388 	vm_inject_fault(vm, vcpuid, &gpf);
1389 }
1390 
1391 void
1392 vm_inject_ud(struct vm *vm, int vcpuid)
1393 {
1394 	struct vm_exception udf = {
1395 		.vector = IDT_UD,
1396 		.error_code_valid = 0
1397 	};
1398 
1399 	vm_inject_fault(vm, vcpuid, &udf);
1400 }
1401 
1402 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1403 
1404 int
1405 vm_inject_nmi(struct vm *vm, int vcpuid)
1406 {
1407 	struct vcpu *vcpu;
1408 
1409 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1410 		return (EINVAL);
1411 
1412 	vcpu = &vm->vcpu[vcpuid];
1413 
1414 	vcpu->nmi_pending = 1;
1415 	vcpu_notify_event(vm, vcpuid, false);
1416 	return (0);
1417 }
1418 
1419 int
1420 vm_nmi_pending(struct vm *vm, int vcpuid)
1421 {
1422 	struct vcpu *vcpu;
1423 
1424 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1425 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1426 
1427 	vcpu = &vm->vcpu[vcpuid];
1428 
1429 	return (vcpu->nmi_pending);
1430 }
1431 
1432 void
1433 vm_nmi_clear(struct vm *vm, int vcpuid)
1434 {
1435 	struct vcpu *vcpu;
1436 
1437 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1438 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1439 
1440 	vcpu = &vm->vcpu[vcpuid];
1441 
1442 	if (vcpu->nmi_pending == 0)
1443 		panic("vm_nmi_clear: inconsistent nmi_pending state");
1444 
1445 	vcpu->nmi_pending = 0;
1446 	vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1447 }
1448 
1449 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
1450 
1451 int
1452 vm_inject_extint(struct vm *vm, int vcpuid)
1453 {
1454 	struct vcpu *vcpu;
1455 
1456 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1457 		return (EINVAL);
1458 
1459 	vcpu = &vm->vcpu[vcpuid];
1460 
1461 	vcpu->extint_pending = 1;
1462 	vcpu_notify_event(vm, vcpuid, false);
1463 	return (0);
1464 }
1465 
1466 int
1467 vm_extint_pending(struct vm *vm, int vcpuid)
1468 {
1469 	struct vcpu *vcpu;
1470 
1471 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1472 		panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1473 
1474 	vcpu = &vm->vcpu[vcpuid];
1475 
1476 	return (vcpu->extint_pending);
1477 }
1478 
1479 void
1480 vm_extint_clear(struct vm *vm, int vcpuid)
1481 {
1482 	struct vcpu *vcpu;
1483 
1484 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1485 		panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1486 
1487 	vcpu = &vm->vcpu[vcpuid];
1488 
1489 	if (vcpu->extint_pending == 0)
1490 		panic("vm_extint_clear: inconsistent extint_pending state");
1491 
1492 	vcpu->extint_pending = 0;
1493 	vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
1494 }
1495 
1496 int
1497 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
1498 {
1499 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1500 		return (EINVAL);
1501 
1502 	if (type < 0 || type >= VM_CAP_MAX)
1503 		return (EINVAL);
1504 
1505 	return (VMGETCAP(vm->cookie, vcpu, type, retval));
1506 }
1507 
1508 int
1509 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
1510 {
1511 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1512 		return (EINVAL);
1513 
1514 	if (type < 0 || type >= VM_CAP_MAX)
1515 		return (EINVAL);
1516 
1517 	return (VMSETCAP(vm->cookie, vcpu, type, val));
1518 }
1519 
1520 uint64_t *
1521 vm_guest_msrs(struct vm *vm, int cpu)
1522 {
1523 	return (vm->vcpu[cpu].guest_msrs);
1524 }
1525 
1526 struct vlapic *
1527 vm_lapic(struct vm *vm, int cpu)
1528 {
1529 	return (vm->vcpu[cpu].vlapic);
1530 }
1531 
1532 struct vioapic *
1533 vm_ioapic(struct vm *vm)
1534 {
1535 
1536 	return (vm->vioapic);
1537 }
1538 
1539 struct vhpet *
1540 vm_hpet(struct vm *vm)
1541 {
1542 
1543 	return (vm->vhpet);
1544 }
1545 
1546 boolean_t
1547 vmm_is_pptdev(int bus, int slot, int func)
1548 {
1549 	int found, i, n;
1550 	int b, s, f;
1551 	char *val, *cp, *cp2;
1552 
1553 	/*
1554 	 * XXX
1555 	 * The length of an environment variable is limited to 128 bytes which
1556 	 * puts an upper limit on the number of passthru devices that may be
1557 	 * specified using a single environment variable.
1558 	 *
1559 	 * Work around this by scanning multiple environment variable
1560 	 * names instead of a single one - yuck!
1561 	 */
1562 	const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
1563 
1564 	/* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
1565 	found = 0;
1566 	for (i = 0; names[i] != NULL && !found; i++) {
1567 		cp = val = getenv(names[i]);
1568 		while (cp != NULL && *cp != '\0') {
1569 			if ((cp2 = strchr(cp, ' ')) != NULL)
1570 				*cp2 = '\0';
1571 
1572 			n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
1573 			if (n == 3 && bus == b && slot == s && func == f) {
1574 				found = 1;
1575 				break;
1576 			}
1577 
1578 			if (cp2 != NULL)
1579 				*cp2++ = ' ';
1580 
1581 			cp = cp2;
1582 		}
1583 		freeenv(val);
1584 	}
1585 	return (found);
1586 }
1587 
1588 void *
1589 vm_iommu_domain(struct vm *vm)
1590 {
1591 
1592 	return (vm->iommu);
1593 }
1594 
1595 int
1596 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
1597     bool from_idle)
1598 {
1599 	int error;
1600 	struct vcpu *vcpu;
1601 
1602 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1603 		panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
1604 
1605 	vcpu = &vm->vcpu[vcpuid];
1606 
1607 	vcpu_lock(vcpu);
1608 	error = vcpu_set_state_locked(vcpu, newstate, from_idle);
1609 	vcpu_unlock(vcpu);
1610 
1611 	return (error);
1612 }
1613 
1614 enum vcpu_state
1615 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
1616 {
1617 	struct vcpu *vcpu;
1618 	enum vcpu_state state;
1619 
1620 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1621 		panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
1622 
1623 	vcpu = &vm->vcpu[vcpuid];
1624 
1625 	vcpu_lock(vcpu);
1626 	state = vcpu->state;
1627 	if (hostcpu != NULL)
1628 		*hostcpu = vcpu->hostcpu;
1629 	vcpu_unlock(vcpu);
1630 
1631 	return (state);
1632 }
1633 
1634 void
1635 vm_activate_cpu(struct vm *vm, int vcpuid)
1636 {
1637 
1638 	KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU,
1639 	    ("vm_activate_cpu: invalid vcpuid %d", vcpuid));
1640 	KASSERT(!CPU_ISSET(vcpuid, &vm->active_cpus),
1641 	    ("vm_activate_cpu: vcpuid %d is already active", vcpuid));
1642 
1643 	VCPU_CTR0(vm, vcpuid, "activated");
1644 	CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
1645 }
1646 
1647 static void
1648 vm_deactivate_cpu(struct vm *vm, int vcpuid)
1649 {
1650 
1651 	KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU,
1652 	    ("vm_deactivate_cpu: invalid vcpuid %d", vcpuid));
1653 	KASSERT(CPU_ISSET(vcpuid, &vm->active_cpus),
1654 	    ("vm_deactivate_cpu: vcpuid %d is not active", vcpuid));
1655 
1656 	VCPU_CTR0(vm, vcpuid, "deactivated");
1657 	CPU_CLR_ATOMIC(vcpuid, &vm->active_cpus);
1658 
1659 	/*
1660 	 * If a vcpu rendezvous is in progress then it could be blocked
1661 	 * on 'vcpuid' - unblock it before disappearing forever.
1662 	 */
1663 	mtx_lock(&vm->rendezvous_mtx);
1664 	if (vm->rendezvous_func != NULL) {
1665 		VCPU_CTR0(vm, vcpuid, "unblock rendezvous after deactivation");
1666 		wakeup(&vm->rendezvous_func);
1667 	}
1668 	mtx_unlock(&vm->rendezvous_mtx);
1669 }
1670 
1671 cpuset_t
1672 vm_active_cpus(struct vm *vm)
1673 {
1674 
1675 	return (vm->active_cpus);
1676 }
1677 
1678 void *
1679 vcpu_stats(struct vm *vm, int vcpuid)
1680 {
1681 
1682 	return (vm->vcpu[vcpuid].stats);
1683 }
1684 
1685 int
1686 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
1687 {
1688 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1689 		return (EINVAL);
1690 
1691 	*state = vm->vcpu[vcpuid].x2apic_state;
1692 
1693 	return (0);
1694 }
1695 
1696 int
1697 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
1698 {
1699 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1700 		return (EINVAL);
1701 
1702 	if (state >= X2APIC_STATE_LAST)
1703 		return (EINVAL);
1704 
1705 	vm->vcpu[vcpuid].x2apic_state = state;
1706 
1707 	vlapic_set_x2apic_state(vm, vcpuid, state);
1708 
1709 	return (0);
1710 }
1711 
1712 /*
1713  * This function is called to ensure that a vcpu "sees" a pending event
1714  * as soon as possible:
1715  * - If the vcpu thread is sleeping then it is woken up.
1716  * - If the vcpu is running on a different host_cpu then an IPI will be directed
1717  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
1718  */
1719 void
1720 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
1721 {
1722 	int hostcpu;
1723 	struct vcpu *vcpu;
1724 
1725 	vcpu = &vm->vcpu[vcpuid];
1726 
1727 	vcpu_lock(vcpu);
1728 	hostcpu = vcpu->hostcpu;
1729 	if (vcpu->state == VCPU_RUNNING) {
1730 		KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
1731 		if (hostcpu != curcpu) {
1732 			if (lapic_intr) {
1733 				vlapic_post_intr(vcpu->vlapic, hostcpu,
1734 				    vmm_ipinum);
1735 			} else {
1736 				ipi_cpu(hostcpu, vmm_ipinum);
1737 			}
1738 		} else {
1739 			/*
1740 			 * If the 'vcpu' is running on 'curcpu' then it must
1741 			 * be sending a notification to itself (e.g. SELF_IPI).
1742 			 * The pending event will be picked up when the vcpu
1743 			 * transitions back to guest context.
1744 			 */
1745 		}
1746 	} else {
1747 		KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
1748 		    "with hostcpu %d", vcpu->state, hostcpu));
1749 		if (vcpu->state == VCPU_SLEEPING)
1750 			wakeup_one(vcpu);
1751 	}
1752 	vcpu_unlock(vcpu);
1753 }
1754 
1755 struct vmspace *
1756 vm_get_vmspace(struct vm *vm)
1757 {
1758 
1759 	return (vm->vmspace);
1760 }
1761 
1762 int
1763 vm_apicid2vcpuid(struct vm *vm, int apicid)
1764 {
1765 	/*
1766 	 * XXX apic id is assumed to be numerically identical to vcpu id
1767 	 */
1768 	return (apicid);
1769 }
1770 
1771 void
1772 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
1773     vm_rendezvous_func_t func, void *arg)
1774 {
1775 	int i;
1776 
1777 	/*
1778 	 * Enforce that this function is called without any locks
1779 	 */
1780 	WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
1781 	KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
1782 	    ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
1783 
1784 restart:
1785 	mtx_lock(&vm->rendezvous_mtx);
1786 	if (vm->rendezvous_func != NULL) {
1787 		/*
1788 		 * If a rendezvous is already in progress then we need to
1789 		 * call the rendezvous handler in case this 'vcpuid' is one
1790 		 * of the targets of the rendezvous.
1791 		 */
1792 		RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
1793 		mtx_unlock(&vm->rendezvous_mtx);
1794 		vm_handle_rendezvous(vm, vcpuid);
1795 		goto restart;
1796 	}
1797 	KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
1798 	    "rendezvous is still in progress"));
1799 
1800 	RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
1801 	vm->rendezvous_req_cpus = dest;
1802 	CPU_ZERO(&vm->rendezvous_done_cpus);
1803 	vm->rendezvous_arg = arg;
1804 	vm_set_rendezvous_func(vm, func);
1805 	mtx_unlock(&vm->rendezvous_mtx);
1806 
1807 	/*
1808 	 * Wake up any sleeping vcpus and trigger a VM-exit in any running
1809 	 * vcpus so they handle the rendezvous as soon as possible.
1810 	 */
1811 	for (i = 0; i < VM_MAXCPU; i++) {
1812 		if (CPU_ISSET(i, &dest))
1813 			vcpu_notify_event(vm, i, false);
1814 	}
1815 
1816 	vm_handle_rendezvous(vm, vcpuid);
1817 }
1818 
1819 struct vatpic *
1820 vm_atpic(struct vm *vm)
1821 {
1822 	return (vm->vatpic);
1823 }
1824 
1825 struct vatpit *
1826 vm_atpit(struct vm *vm)
1827 {
1828 	return (vm->vatpit);
1829 }
1830