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