xref: /freebsd/sys/amd64/vmm/vmm.c (revision 3ae0125a99dc29a8f8ca9ba933825e2447b54c6b)
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.
1041 			 */
1042 			spindown = 1;
1043 		}
1044 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1045 		vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1046 	}
1047 	vcpu_unlock(vcpu);
1048 
1049 	/*
1050 	 * Since 'vm_deactivate_cpu()' grabs a sleep mutex we must call it
1051 	 * outside the confines of the vcpu spinlock.
1052 	 */
1053 	if (spindown) {
1054 		*retu = true;
1055 		vmexit = vm_exitinfo(vm, vcpuid);
1056 		vmexit->exitcode = VM_EXITCODE_SPINDOWN_CPU;
1057 		vm_deactivate_cpu(vm, vcpuid);
1058 		VCPU_CTR0(vm, vcpuid, "spinning down cpu");
1059 	}
1060 
1061 	return (0);
1062 }
1063 
1064 static int
1065 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1066 {
1067 	int rv, ftype;
1068 	struct vm_map *map;
1069 	struct vcpu *vcpu;
1070 	struct vm_exit *vme;
1071 
1072 	vcpu = &vm->vcpu[vcpuid];
1073 	vme = &vcpu->exitinfo;
1074 
1075 	ftype = vme->u.paging.fault_type;
1076 	KASSERT(ftype == VM_PROT_READ ||
1077 	    ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1078 	    ("vm_handle_paging: invalid fault_type %d", ftype));
1079 
1080 	if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1081 		rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1082 		    vme->u.paging.gpa, ftype);
1083 		if (rv == 0)
1084 			goto done;
1085 	}
1086 
1087 	map = &vm->vmspace->vm_map;
1088 	rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
1089 
1090 	VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1091 	    "ftype = %d", rv, vme->u.paging.gpa, ftype);
1092 
1093 	if (rv != KERN_SUCCESS)
1094 		return (EFAULT);
1095 done:
1096 	/* restart execution at the faulting instruction */
1097 	vme->inst_length = 0;
1098 
1099 	return (0);
1100 }
1101 
1102 static int
1103 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1104 {
1105 	struct vie *vie;
1106 	struct vcpu *vcpu;
1107 	struct vm_exit *vme;
1108 	int error, inst_length;
1109 	uint64_t rip, gla, gpa, cr3;
1110 	enum vie_cpu_mode cpu_mode;
1111 	enum vie_paging_mode paging_mode;
1112 	mem_region_read_t mread;
1113 	mem_region_write_t mwrite;
1114 
1115 	vcpu = &vm->vcpu[vcpuid];
1116 	vme = &vcpu->exitinfo;
1117 
1118 	rip = vme->rip;
1119 	inst_length = vme->inst_length;
1120 
1121 	gla = vme->u.inst_emul.gla;
1122 	gpa = vme->u.inst_emul.gpa;
1123 	cr3 = vme->u.inst_emul.cr3;
1124 	cpu_mode = vme->u.inst_emul.cpu_mode;
1125 	paging_mode = vme->u.inst_emul.paging_mode;
1126 	vie = &vme->u.inst_emul.vie;
1127 
1128 	vie_init(vie);
1129 
1130 	/* Fetch, decode and emulate the faulting instruction */
1131 	if (vmm_fetch_instruction(vm, vcpuid, rip, inst_length, cr3,
1132 	    paging_mode, vie) != 0)
1133 		return (EFAULT);
1134 
1135 	if (vmm_decode_instruction(vm, vcpuid, gla, cpu_mode, vie) != 0)
1136 		return (EFAULT);
1137 
1138 	/* return to userland unless this is an in-kernel emulated device */
1139 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1140 		mread = lapic_mmio_read;
1141 		mwrite = lapic_mmio_write;
1142 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1143 		mread = vioapic_mmio_read;
1144 		mwrite = vioapic_mmio_write;
1145 	} else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1146 		mread = vhpet_mmio_read;
1147 		mwrite = vhpet_mmio_write;
1148 	} else {
1149 		*retu = true;
1150 		return (0);
1151 	}
1152 
1153 	error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, mread, mwrite,
1154 	    retu);
1155 
1156 	return (error);
1157 }
1158 
1159 static int
1160 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1161 {
1162 	int i, done;
1163 	struct vcpu *vcpu;
1164 
1165 	done = 0;
1166 	vcpu = &vm->vcpu[vcpuid];
1167 
1168 	CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1169 
1170 	/*
1171 	 * Wait until all 'active_cpus' have suspended themselves.
1172 	 *
1173 	 * Since a VM may be suspended at any time including when one or
1174 	 * more vcpus are doing a rendezvous we need to call the rendezvous
1175 	 * handler while we are waiting to prevent a deadlock.
1176 	 */
1177 	vcpu_lock(vcpu);
1178 	while (1) {
1179 		if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1180 			VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1181 			break;
1182 		}
1183 
1184 		if (vm->rendezvous_func == NULL) {
1185 			VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1186 			vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1187 			msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1188 			vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1189 		} else {
1190 			VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1191 			vcpu_unlock(vcpu);
1192 			vm_handle_rendezvous(vm, vcpuid);
1193 			vcpu_lock(vcpu);
1194 		}
1195 	}
1196 	vcpu_unlock(vcpu);
1197 
1198 	/*
1199 	 * Wakeup the other sleeping vcpus and return to userspace.
1200 	 */
1201 	for (i = 0; i < VM_MAXCPU; i++) {
1202 		if (CPU_ISSET(i, &vm->suspended_cpus)) {
1203 			vcpu_notify_event(vm, i, false);
1204 		}
1205 	}
1206 
1207 	*retu = true;
1208 	return (0);
1209 }
1210 
1211 int
1212 vm_suspend(struct vm *vm)
1213 {
1214 
1215 	if (atomic_cmpset_int(&vm->suspend, 0, 1)) {
1216 		VM_CTR0(vm, "virtual machine suspended");
1217 		return (0);
1218 	} else {
1219 		VM_CTR0(vm, "virtual machine already suspended");
1220 		return (EALREADY);
1221 	}
1222 }
1223 
1224 int
1225 vm_run(struct vm *vm, struct vm_run *vmrun)
1226 {
1227 	int error, vcpuid;
1228 	struct vcpu *vcpu;
1229 	struct pcb *pcb;
1230 	uint64_t tscval, rip;
1231 	struct vm_exit *vme;
1232 	bool retu, intr_disabled;
1233 	pmap_t pmap;
1234 	void *rptr, *sptr;
1235 
1236 	vcpuid = vmrun->cpuid;
1237 
1238 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1239 		return (EINVAL);
1240 
1241 	rptr = &vm->rendezvous_func;
1242 	sptr = &vm->suspend;
1243 	pmap = vmspace_pmap(vm->vmspace);
1244 	vcpu = &vm->vcpu[vcpuid];
1245 	vme = &vcpu->exitinfo;
1246 	rip = vmrun->rip;
1247 restart:
1248 	critical_enter();
1249 
1250 	KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1251 	    ("vm_run: absurd pm_active"));
1252 
1253 	tscval = rdtsc();
1254 
1255 	pcb = PCPU_GET(curpcb);
1256 	set_pcb_flags(pcb, PCB_FULL_IRET);
1257 
1258 	restore_guest_msrs(vm, vcpuid);
1259 	restore_guest_fpustate(vcpu);
1260 
1261 	vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1262 	error = VMRUN(vm->cookie, vcpuid, rip, pmap, rptr, sptr);
1263 	vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1264 
1265 	save_guest_fpustate(vcpu);
1266 	restore_host_msrs(vm, vcpuid);
1267 
1268 	vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1269 
1270 	critical_exit();
1271 
1272 	if (error == 0) {
1273 		retu = false;
1274 		switch (vme->exitcode) {
1275 		case VM_EXITCODE_SUSPENDED:
1276 			error = vm_handle_suspend(vm, vcpuid, &retu);
1277 			break;
1278 		case VM_EXITCODE_IOAPIC_EOI:
1279 			vioapic_process_eoi(vm, vcpuid,
1280 			    vme->u.ioapic_eoi.vector);
1281 			break;
1282 		case VM_EXITCODE_RENDEZVOUS:
1283 			vm_handle_rendezvous(vm, vcpuid);
1284 			error = 0;
1285 			break;
1286 		case VM_EXITCODE_HLT:
1287 			intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1288 			error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1289 			break;
1290 		case VM_EXITCODE_PAGING:
1291 			error = vm_handle_paging(vm, vcpuid, &retu);
1292 			break;
1293 		case VM_EXITCODE_INST_EMUL:
1294 			error = vm_handle_inst_emul(vm, vcpuid, &retu);
1295 			break;
1296 		default:
1297 			retu = true;	/* handled in userland */
1298 			break;
1299 		}
1300 	}
1301 
1302 	if (error == 0 && retu == false) {
1303 		rip = vme->rip + vme->inst_length;
1304 		goto restart;
1305 	}
1306 
1307 	/* copy the exit information */
1308 	bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1309 	return (error);
1310 }
1311 
1312 int
1313 vm_inject_exception(struct vm *vm, int vcpuid, struct vm_exception *exception)
1314 {
1315 	struct vcpu *vcpu;
1316 
1317 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1318 		return (EINVAL);
1319 
1320 	if (exception->vector < 0 || exception->vector >= 32)
1321 		return (EINVAL);
1322 
1323 	vcpu = &vm->vcpu[vcpuid];
1324 
1325 	if (vcpu->exception_pending) {
1326 		VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
1327 		    "pending exception %d", exception->vector,
1328 		    vcpu->exception.vector);
1329 		return (EBUSY);
1330 	}
1331 
1332 	vcpu->exception_pending = 1;
1333 	vcpu->exception = *exception;
1334 	VCPU_CTR1(vm, vcpuid, "Exception %d pending", exception->vector);
1335 	return (0);
1336 }
1337 
1338 int
1339 vm_exception_pending(struct vm *vm, int vcpuid, struct vm_exception *exception)
1340 {
1341 	struct vcpu *vcpu;
1342 	int pending;
1343 
1344 	KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU, ("invalid vcpu %d", vcpuid));
1345 
1346 	vcpu = &vm->vcpu[vcpuid];
1347 	pending = vcpu->exception_pending;
1348 	if (pending) {
1349 		vcpu->exception_pending = 0;
1350 		*exception = vcpu->exception;
1351 		VCPU_CTR1(vm, vcpuid, "Exception %d delivered",
1352 		    exception->vector);
1353 	}
1354 	return (pending);
1355 }
1356 
1357 static void
1358 vm_inject_fault(struct vm *vm, int vcpuid, struct vm_exception *exception)
1359 {
1360 	struct vm_exit *vmexit;
1361 	int error;
1362 
1363 	error = vm_inject_exception(vm, vcpuid, exception);
1364 	KASSERT(error == 0, ("vm_inject_exception error %d", error));
1365 
1366 	/*
1367 	 * A fault-like exception allows the instruction to be restarted
1368 	 * after the exception handler returns.
1369 	 *
1370 	 * By setting the inst_length to 0 we ensure that the instruction
1371 	 * pointer remains at the faulting instruction.
1372 	 */
1373 	vmexit = vm_exitinfo(vm, vcpuid);
1374 	vmexit->inst_length = 0;
1375 }
1376 
1377 void
1378 vm_inject_gp(struct vm *vm, int vcpuid)
1379 {
1380 	struct vm_exception gpf = {
1381 		.vector = IDT_GP,
1382 		.error_code_valid = 1,
1383 		.error_code = 0
1384 	};
1385 
1386 	vm_inject_fault(vm, vcpuid, &gpf);
1387 }
1388 
1389 void
1390 vm_inject_ud(struct vm *vm, int vcpuid)
1391 {
1392 	struct vm_exception udf = {
1393 		.vector = IDT_UD,
1394 		.error_code_valid = 0
1395 	};
1396 
1397 	vm_inject_fault(vm, vcpuid, &udf);
1398 }
1399 
1400 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1401 
1402 int
1403 vm_inject_nmi(struct vm *vm, int vcpuid)
1404 {
1405 	struct vcpu *vcpu;
1406 
1407 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1408 		return (EINVAL);
1409 
1410 	vcpu = &vm->vcpu[vcpuid];
1411 
1412 	vcpu->nmi_pending = 1;
1413 	vcpu_notify_event(vm, vcpuid, false);
1414 	return (0);
1415 }
1416 
1417 int
1418 vm_nmi_pending(struct vm *vm, int vcpuid)
1419 {
1420 	struct vcpu *vcpu;
1421 
1422 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1423 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1424 
1425 	vcpu = &vm->vcpu[vcpuid];
1426 
1427 	return (vcpu->nmi_pending);
1428 }
1429 
1430 void
1431 vm_nmi_clear(struct vm *vm, int vcpuid)
1432 {
1433 	struct vcpu *vcpu;
1434 
1435 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1436 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1437 
1438 	vcpu = &vm->vcpu[vcpuid];
1439 
1440 	if (vcpu->nmi_pending == 0)
1441 		panic("vm_nmi_clear: inconsistent nmi_pending state");
1442 
1443 	vcpu->nmi_pending = 0;
1444 	vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1445 }
1446 
1447 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
1448 
1449 int
1450 vm_inject_extint(struct vm *vm, int vcpuid)
1451 {
1452 	struct vcpu *vcpu;
1453 
1454 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1455 		return (EINVAL);
1456 
1457 	vcpu = &vm->vcpu[vcpuid];
1458 
1459 	vcpu->extint_pending = 1;
1460 	vcpu_notify_event(vm, vcpuid, false);
1461 	return (0);
1462 }
1463 
1464 int
1465 vm_extint_pending(struct vm *vm, int vcpuid)
1466 {
1467 	struct vcpu *vcpu;
1468 
1469 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1470 		panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1471 
1472 	vcpu = &vm->vcpu[vcpuid];
1473 
1474 	return (vcpu->extint_pending);
1475 }
1476 
1477 void
1478 vm_extint_clear(struct vm *vm, int vcpuid)
1479 {
1480 	struct vcpu *vcpu;
1481 
1482 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1483 		panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1484 
1485 	vcpu = &vm->vcpu[vcpuid];
1486 
1487 	if (vcpu->extint_pending == 0)
1488 		panic("vm_extint_clear: inconsistent extint_pending state");
1489 
1490 	vcpu->extint_pending = 0;
1491 	vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
1492 }
1493 
1494 int
1495 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
1496 {
1497 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1498 		return (EINVAL);
1499 
1500 	if (type < 0 || type >= VM_CAP_MAX)
1501 		return (EINVAL);
1502 
1503 	return (VMGETCAP(vm->cookie, vcpu, type, retval));
1504 }
1505 
1506 int
1507 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
1508 {
1509 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1510 		return (EINVAL);
1511 
1512 	if (type < 0 || type >= VM_CAP_MAX)
1513 		return (EINVAL);
1514 
1515 	return (VMSETCAP(vm->cookie, vcpu, type, val));
1516 }
1517 
1518 uint64_t *
1519 vm_guest_msrs(struct vm *vm, int cpu)
1520 {
1521 	return (vm->vcpu[cpu].guest_msrs);
1522 }
1523 
1524 struct vlapic *
1525 vm_lapic(struct vm *vm, int cpu)
1526 {
1527 	return (vm->vcpu[cpu].vlapic);
1528 }
1529 
1530 struct vioapic *
1531 vm_ioapic(struct vm *vm)
1532 {
1533 
1534 	return (vm->vioapic);
1535 }
1536 
1537 struct vhpet *
1538 vm_hpet(struct vm *vm)
1539 {
1540 
1541 	return (vm->vhpet);
1542 }
1543 
1544 boolean_t
1545 vmm_is_pptdev(int bus, int slot, int func)
1546 {
1547 	int found, i, n;
1548 	int b, s, f;
1549 	char *val, *cp, *cp2;
1550 
1551 	/*
1552 	 * XXX
1553 	 * The length of an environment variable is limited to 128 bytes which
1554 	 * puts an upper limit on the number of passthru devices that may be
1555 	 * specified using a single environment variable.
1556 	 *
1557 	 * Work around this by scanning multiple environment variable
1558 	 * names instead of a single one - yuck!
1559 	 */
1560 	const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
1561 
1562 	/* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
1563 	found = 0;
1564 	for (i = 0; names[i] != NULL && !found; i++) {
1565 		cp = val = getenv(names[i]);
1566 		while (cp != NULL && *cp != '\0') {
1567 			if ((cp2 = strchr(cp, ' ')) != NULL)
1568 				*cp2 = '\0';
1569 
1570 			n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
1571 			if (n == 3 && bus == b && slot == s && func == f) {
1572 				found = 1;
1573 				break;
1574 			}
1575 
1576 			if (cp2 != NULL)
1577 				*cp2++ = ' ';
1578 
1579 			cp = cp2;
1580 		}
1581 		freeenv(val);
1582 	}
1583 	return (found);
1584 }
1585 
1586 void *
1587 vm_iommu_domain(struct vm *vm)
1588 {
1589 
1590 	return (vm->iommu);
1591 }
1592 
1593 int
1594 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
1595     bool from_idle)
1596 {
1597 	int error;
1598 	struct vcpu *vcpu;
1599 
1600 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1601 		panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
1602 
1603 	vcpu = &vm->vcpu[vcpuid];
1604 
1605 	vcpu_lock(vcpu);
1606 	error = vcpu_set_state_locked(vcpu, newstate, from_idle);
1607 	vcpu_unlock(vcpu);
1608 
1609 	return (error);
1610 }
1611 
1612 enum vcpu_state
1613 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
1614 {
1615 	struct vcpu *vcpu;
1616 	enum vcpu_state state;
1617 
1618 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1619 		panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
1620 
1621 	vcpu = &vm->vcpu[vcpuid];
1622 
1623 	vcpu_lock(vcpu);
1624 	state = vcpu->state;
1625 	if (hostcpu != NULL)
1626 		*hostcpu = vcpu->hostcpu;
1627 	vcpu_unlock(vcpu);
1628 
1629 	return (state);
1630 }
1631 
1632 void
1633 vm_activate_cpu(struct vm *vm, int vcpuid)
1634 {
1635 
1636 	KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU,
1637 	    ("vm_activate_cpu: invalid vcpuid %d", vcpuid));
1638 	KASSERT(!CPU_ISSET(vcpuid, &vm->active_cpus),
1639 	    ("vm_activate_cpu: vcpuid %d is already active", vcpuid));
1640 
1641 	VCPU_CTR0(vm, vcpuid, "activated");
1642 	CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
1643 }
1644 
1645 static void
1646 vm_deactivate_cpu(struct vm *vm, int vcpuid)
1647 {
1648 
1649 	KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU,
1650 	    ("vm_deactivate_cpu: invalid vcpuid %d", vcpuid));
1651 	KASSERT(CPU_ISSET(vcpuid, &vm->active_cpus),
1652 	    ("vm_deactivate_cpu: vcpuid %d is not active", vcpuid));
1653 
1654 	VCPU_CTR0(vm, vcpuid, "deactivated");
1655 	CPU_CLR_ATOMIC(vcpuid, &vm->active_cpus);
1656 
1657 	/*
1658 	 * If a vcpu rendezvous is in progress then it could be blocked
1659 	 * on 'vcpuid' - unblock it before disappearing forever.
1660 	 */
1661 	mtx_lock(&vm->rendezvous_mtx);
1662 	if (vm->rendezvous_func != NULL) {
1663 		VCPU_CTR0(vm, vcpuid, "unblock rendezvous after deactivation");
1664 		wakeup(&vm->rendezvous_func);
1665 	}
1666 	mtx_unlock(&vm->rendezvous_mtx);
1667 }
1668 
1669 cpuset_t
1670 vm_active_cpus(struct vm *vm)
1671 {
1672 
1673 	return (vm->active_cpus);
1674 }
1675 
1676 void *
1677 vcpu_stats(struct vm *vm, int vcpuid)
1678 {
1679 
1680 	return (vm->vcpu[vcpuid].stats);
1681 }
1682 
1683 int
1684 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
1685 {
1686 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1687 		return (EINVAL);
1688 
1689 	*state = vm->vcpu[vcpuid].x2apic_state;
1690 
1691 	return (0);
1692 }
1693 
1694 int
1695 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
1696 {
1697 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1698 		return (EINVAL);
1699 
1700 	if (state >= X2APIC_STATE_LAST)
1701 		return (EINVAL);
1702 
1703 	vm->vcpu[vcpuid].x2apic_state = state;
1704 
1705 	vlapic_set_x2apic_state(vm, vcpuid, state);
1706 
1707 	return (0);
1708 }
1709 
1710 /*
1711  * This function is called to ensure that a vcpu "sees" a pending event
1712  * as soon as possible:
1713  * - If the vcpu thread is sleeping then it is woken up.
1714  * - If the vcpu is running on a different host_cpu then an IPI will be directed
1715  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
1716  */
1717 void
1718 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
1719 {
1720 	int hostcpu;
1721 	struct vcpu *vcpu;
1722 
1723 	vcpu = &vm->vcpu[vcpuid];
1724 
1725 	vcpu_lock(vcpu);
1726 	hostcpu = vcpu->hostcpu;
1727 	if (vcpu->state == VCPU_RUNNING) {
1728 		KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
1729 		if (hostcpu != curcpu) {
1730 			if (lapic_intr) {
1731 				vlapic_post_intr(vcpu->vlapic, hostcpu,
1732 				    vmm_ipinum);
1733 			} else {
1734 				ipi_cpu(hostcpu, vmm_ipinum);
1735 			}
1736 		} else {
1737 			/*
1738 			 * If the 'vcpu' is running on 'curcpu' then it must
1739 			 * be sending a notification to itself (e.g. SELF_IPI).
1740 			 * The pending event will be picked up when the vcpu
1741 			 * transitions back to guest context.
1742 			 */
1743 		}
1744 	} else {
1745 		KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
1746 		    "with hostcpu %d", vcpu->state, hostcpu));
1747 		if (vcpu->state == VCPU_SLEEPING)
1748 			wakeup_one(vcpu);
1749 	}
1750 	vcpu_unlock(vcpu);
1751 }
1752 
1753 struct vmspace *
1754 vm_get_vmspace(struct vm *vm)
1755 {
1756 
1757 	return (vm->vmspace);
1758 }
1759 
1760 int
1761 vm_apicid2vcpuid(struct vm *vm, int apicid)
1762 {
1763 	/*
1764 	 * XXX apic id is assumed to be numerically identical to vcpu id
1765 	 */
1766 	return (apicid);
1767 }
1768 
1769 void
1770 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
1771     vm_rendezvous_func_t func, void *arg)
1772 {
1773 	int i;
1774 
1775 	/*
1776 	 * Enforce that this function is called without any locks
1777 	 */
1778 	WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
1779 	KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
1780 	    ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
1781 
1782 restart:
1783 	mtx_lock(&vm->rendezvous_mtx);
1784 	if (vm->rendezvous_func != NULL) {
1785 		/*
1786 		 * If a rendezvous is already in progress then we need to
1787 		 * call the rendezvous handler in case this 'vcpuid' is one
1788 		 * of the targets of the rendezvous.
1789 		 */
1790 		RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
1791 		mtx_unlock(&vm->rendezvous_mtx);
1792 		vm_handle_rendezvous(vm, vcpuid);
1793 		goto restart;
1794 	}
1795 	KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
1796 	    "rendezvous is still in progress"));
1797 
1798 	RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
1799 	vm->rendezvous_req_cpus = dest;
1800 	CPU_ZERO(&vm->rendezvous_done_cpus);
1801 	vm->rendezvous_arg = arg;
1802 	vm_set_rendezvous_func(vm, func);
1803 	mtx_unlock(&vm->rendezvous_mtx);
1804 
1805 	/*
1806 	 * Wake up any sleeping vcpus and trigger a VM-exit in any running
1807 	 * vcpus so they handle the rendezvous as soon as possible.
1808 	 */
1809 	for (i = 0; i < VM_MAXCPU; i++) {
1810 		if (CPU_ISSET(i, &dest))
1811 			vcpu_notify_event(vm, i, false);
1812 	}
1813 
1814 	vm_handle_rendezvous(vm, vcpuid);
1815 }
1816 
1817 struct vatpic *
1818 vm_atpic(struct vm *vm)
1819 {
1820 	return (vm->vatpic);
1821 }
1822 
1823 struct vatpit *
1824 vm_atpit(struct vm *vm)
1825 {
1826 	return (vm->vatpit);
1827 }
1828