xref: /freebsd/sys/amd64/vmm/vmm.c (revision 95d45410b5100e07f6f98450bcd841a8945d4726)
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 #include <machine/vmm_instruction_emul.h>
66 
67 #include "vmm_ioport.h"
68 #include "vmm_ktr.h"
69 #include "vmm_host.h"
70 #include "vmm_mem.h"
71 #include "vmm_util.h"
72 #include "vatpic.h"
73 #include "vatpit.h"
74 #include "vhpet.h"
75 #include "vioapic.h"
76 #include "vlapic.h"
77 #include "vmm_msr.h"
78 #include "vmm_ipi.h"
79 #include "vmm_stat.h"
80 #include "vmm_lapic.h"
81 
82 #include "io/ppt.h"
83 #include "io/iommu.h"
84 
85 struct vlapic;
86 
87 /*
88  * Initialization:
89  * (a) allocated when vcpu is created
90  * (i) initialized when vcpu is created and when it is reinitialized
91  * (o) initialized the first time the vcpu is created
92  * (x) initialized before use
93  */
94 struct vcpu {
95 	struct mtx 	mtx;		/* (o) protects 'state' and 'hostcpu' */
96 	enum vcpu_state	state;		/* (o) vcpu state */
97 	int		hostcpu;	/* (o) vcpu's host cpu */
98 	struct vlapic	*vlapic;	/* (i) APIC device model */
99 	enum x2apic_state x2apic_state;	/* (i) APIC mode */
100 	uint64_t	exitintinfo;	/* (i) events pending at VM exit */
101 	int		nmi_pending;	/* (i) NMI pending */
102 	int		extint_pending;	/* (i) INTR pending */
103 	struct vm_exception exception;	/* (x) exception collateral */
104 	int	exception_pending;	/* (i) exception pending */
105 	struct savefpu	*guestfpu;	/* (a,i) guest fpu state */
106 	uint64_t	guest_xcr0;	/* (i) guest %xcr0 register */
107 	void		*stats;		/* (a,i) statistics */
108 	uint64_t guest_msrs[VMM_MSR_NUM]; /* (i) emulated MSRs */
109 	struct vm_exit	exitinfo;	/* (x) exit reason and collateral */
110 };
111 
112 #define	vcpu_lock_initialized(v) mtx_initialized(&((v)->mtx))
113 #define	vcpu_lock_init(v)	mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
114 #define	vcpu_lock(v)		mtx_lock_spin(&((v)->mtx))
115 #define	vcpu_unlock(v)		mtx_unlock_spin(&((v)->mtx))
116 #define	vcpu_assert_locked(v)	mtx_assert(&((v)->mtx), MA_OWNED)
117 
118 struct mem_seg {
119 	vm_paddr_t	gpa;
120 	size_t		len;
121 	boolean_t	wired;
122 	vm_object_t	object;
123 };
124 #define	VM_MAX_MEMORY_SEGMENTS	2
125 
126 /*
127  * Initialization:
128  * (o) initialized the first time the VM is created
129  * (i) initialized when VM is created and when it is reinitialized
130  * (x) initialized before use
131  */
132 struct vm {
133 	void		*cookie;		/* (i) cpu-specific data */
134 	void		*iommu;			/* (x) iommu-specific data */
135 	struct vhpet	*vhpet;			/* (i) virtual HPET */
136 	struct vioapic	*vioapic;		/* (i) virtual ioapic */
137 	struct vatpic	*vatpic;		/* (i) virtual atpic */
138 	struct vatpit	*vatpit;		/* (i) virtual atpit */
139 	volatile cpuset_t active_cpus;		/* (i) active vcpus */
140 	int		suspend;		/* (i) stop VM execution */
141 	volatile cpuset_t suspended_cpus; 	/* (i) suspended vcpus */
142 	volatile cpuset_t halted_cpus;		/* (x) cpus in a hard halt */
143 	cpuset_t	rendezvous_req_cpus;	/* (x) rendezvous requested */
144 	cpuset_t	rendezvous_done_cpus;	/* (x) rendezvous finished */
145 	void		*rendezvous_arg;	/* (x) rendezvous func/arg */
146 	vm_rendezvous_func_t rendezvous_func;
147 	struct mtx	rendezvous_mtx;		/* (o) rendezvous lock */
148 	int		num_mem_segs;		/* (o) guest memory segments */
149 	struct mem_seg	mem_segs[VM_MAX_MEMORY_SEGMENTS];
150 	struct vmspace	*vmspace;		/* (o) guest's address space */
151 	char		name[VM_MAX_NAMELEN];	/* (o) virtual machine name */
152 	struct vcpu	vcpu[VM_MAXCPU];	/* (i) guest vcpus */
153 };
154 
155 static int vmm_initialized;
156 
157 static struct vmm_ops *ops;
158 #define	VMM_INIT(num)	(ops != NULL ? (*ops->init)(num) : 0)
159 #define	VMM_CLEANUP()	(ops != NULL ? (*ops->cleanup)() : 0)
160 #define	VMM_RESUME()	(ops != NULL ? (*ops->resume)() : 0)
161 
162 #define	VMINIT(vm, pmap) (ops != NULL ? (*ops->vminit)(vm, pmap): NULL)
163 #define	VMRUN(vmi, vcpu, rip, pmap, rptr, sptr) \
164 	(ops != NULL ? (*ops->vmrun)(vmi, vcpu, rip, pmap, rptr, sptr) : ENXIO)
165 #define	VMCLEANUP(vmi)	(ops != NULL ? (*ops->vmcleanup)(vmi) : NULL)
166 #define	VMSPACE_ALLOC(min, max) \
167 	(ops != NULL ? (*ops->vmspace_alloc)(min, max) : NULL)
168 #define	VMSPACE_FREE(vmspace) \
169 	(ops != NULL ? (*ops->vmspace_free)(vmspace) : ENXIO)
170 #define	VMGETREG(vmi, vcpu, num, retval)		\
171 	(ops != NULL ? (*ops->vmgetreg)(vmi, vcpu, num, retval) : ENXIO)
172 #define	VMSETREG(vmi, vcpu, num, val)		\
173 	(ops != NULL ? (*ops->vmsetreg)(vmi, vcpu, num, val) : ENXIO)
174 #define	VMGETDESC(vmi, vcpu, num, desc)		\
175 	(ops != NULL ? (*ops->vmgetdesc)(vmi, vcpu, num, desc) : ENXIO)
176 #define	VMSETDESC(vmi, vcpu, num, desc)		\
177 	(ops != NULL ? (*ops->vmsetdesc)(vmi, vcpu, num, desc) : ENXIO)
178 #define	VMGETCAP(vmi, vcpu, num, retval)	\
179 	(ops != NULL ? (*ops->vmgetcap)(vmi, vcpu, num, retval) : ENXIO)
180 #define	VMSETCAP(vmi, vcpu, num, val)		\
181 	(ops != NULL ? (*ops->vmsetcap)(vmi, vcpu, num, val) : ENXIO)
182 #define	VLAPIC_INIT(vmi, vcpu)			\
183 	(ops != NULL ? (*ops->vlapic_init)(vmi, vcpu) : NULL)
184 #define	VLAPIC_CLEANUP(vmi, vlapic)		\
185 	(ops != NULL ? (*ops->vlapic_cleanup)(vmi, vlapic) : NULL)
186 
187 #define	fpu_start_emulating()	load_cr0(rcr0() | CR0_TS)
188 #define	fpu_stop_emulating()	clts()
189 
190 static MALLOC_DEFINE(M_VM, "vm", "vm");
191 CTASSERT(VMM_MSR_NUM <= 64);	/* msr_mask can keep track of up to 64 msrs */
192 
193 /* statistics */
194 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
195 
196 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
197 
198 /*
199  * Halt the guest if all vcpus are executing a HLT instruction with
200  * interrupts disabled.
201  */
202 static int halt_detection_enabled = 1;
203 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
204     &halt_detection_enabled, 0,
205     "Halt VM if all vcpus execute HLT with interrupts disabled");
206 
207 static int vmm_ipinum;
208 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
209     "IPI vector used for vcpu notifications");
210 
211 static void
212 vcpu_cleanup(struct vm *vm, int i, bool destroy)
213 {
214 	struct vcpu *vcpu = &vm->vcpu[i];
215 
216 	VLAPIC_CLEANUP(vm->cookie, vcpu->vlapic);
217 	if (destroy) {
218 		vmm_stat_free(vcpu->stats);
219 		fpu_save_area_free(vcpu->guestfpu);
220 	}
221 }
222 
223 static void
224 vcpu_init(struct vm *vm, int vcpu_id, bool create)
225 {
226 	struct vcpu *vcpu;
227 
228 	KASSERT(vcpu_id >= 0 && vcpu_id < VM_MAXCPU,
229 	    ("vcpu_init: invalid vcpu %d", vcpu_id));
230 
231 	vcpu = &vm->vcpu[vcpu_id];
232 
233 	if (create) {
234 		KASSERT(!vcpu_lock_initialized(vcpu), ("vcpu %d already "
235 		    "initialized", vcpu_id));
236 		vcpu_lock_init(vcpu);
237 		vcpu->state = VCPU_IDLE;
238 		vcpu->hostcpu = NOCPU;
239 		vcpu->guestfpu = fpu_save_area_alloc();
240 		vcpu->stats = vmm_stat_alloc();
241 	}
242 
243 	vcpu->vlapic = VLAPIC_INIT(vm->cookie, vcpu_id);
244 	vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
245 	vcpu->exitintinfo = 0;
246 	vcpu->nmi_pending = 0;
247 	vcpu->extint_pending = 0;
248 	vcpu->exception_pending = 0;
249 	vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
250 	fpu_save_area_reset(vcpu->guestfpu);
251 	vmm_stat_init(vcpu->stats);
252 	guest_msrs_init(vm, vcpu_id);
253 }
254 
255 struct vm_exit *
256 vm_exitinfo(struct vm *vm, int cpuid)
257 {
258 	struct vcpu *vcpu;
259 
260 	if (cpuid < 0 || cpuid >= VM_MAXCPU)
261 		panic("vm_exitinfo: invalid cpuid %d", cpuid);
262 
263 	vcpu = &vm->vcpu[cpuid];
264 
265 	return (&vcpu->exitinfo);
266 }
267 
268 static void
269 vmm_resume(void)
270 {
271 	VMM_RESUME();
272 }
273 
274 static int
275 vmm_init(void)
276 {
277 	int error;
278 
279 	vmm_host_state_init();
280 
281 	vmm_ipinum = vmm_ipi_alloc();
282 	if (vmm_ipinum == 0)
283 		vmm_ipinum = IPI_AST;
284 
285 	error = vmm_mem_init();
286 	if (error)
287 		return (error);
288 
289 	if (vmm_is_intel())
290 		ops = &vmm_ops_intel;
291 	else if (vmm_is_amd())
292 		ops = &vmm_ops_amd;
293 	else
294 		return (ENXIO);
295 
296 	vmm_msr_init();
297 	vmm_resume_p = vmm_resume;
298 
299 	return (VMM_INIT(vmm_ipinum));
300 }
301 
302 static int
303 vmm_handler(module_t mod, int what, void *arg)
304 {
305 	int error;
306 
307 	switch (what) {
308 	case MOD_LOAD:
309 		vmmdev_init();
310 		if (ppt_avail_devices() > 0)
311 			iommu_init();
312 		error = vmm_init();
313 		if (error == 0)
314 			vmm_initialized = 1;
315 		break;
316 	case MOD_UNLOAD:
317 		error = vmmdev_cleanup();
318 		if (error == 0) {
319 			vmm_resume_p = NULL;
320 			iommu_cleanup();
321 			if (vmm_ipinum != IPI_AST)
322 				vmm_ipi_free(vmm_ipinum);
323 			error = VMM_CLEANUP();
324 			/*
325 			 * Something bad happened - prevent new
326 			 * VMs from being created
327 			 */
328 			if (error)
329 				vmm_initialized = 0;
330 		}
331 		break;
332 	default:
333 		error = 0;
334 		break;
335 	}
336 	return (error);
337 }
338 
339 static moduledata_t vmm_kmod = {
340 	"vmm",
341 	vmm_handler,
342 	NULL
343 };
344 
345 /*
346  * vmm initialization has the following dependencies:
347  *
348  * - iommu initialization must happen after the pci passthru driver has had
349  *   a chance to attach to any passthru devices (after SI_SUB_CONFIGURE).
350  *
351  * - VT-x initialization requires smp_rendezvous() and therefore must happen
352  *   after SMP is fully functional (after SI_SUB_SMP).
353  */
354 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
355 MODULE_VERSION(vmm, 1);
356 
357 static void
358 vm_init(struct vm *vm, bool create)
359 {
360 	int i;
361 
362 	vm->cookie = VMINIT(vm, vmspace_pmap(vm->vmspace));
363 	vm->iommu = NULL;
364 	vm->vioapic = vioapic_init(vm);
365 	vm->vhpet = vhpet_init(vm);
366 	vm->vatpic = vatpic_init(vm);
367 	vm->vatpit = vatpit_init(vm);
368 
369 	CPU_ZERO(&vm->active_cpus);
370 
371 	vm->suspend = 0;
372 	CPU_ZERO(&vm->suspended_cpus);
373 
374 	for (i = 0; i < VM_MAXCPU; i++)
375 		vcpu_init(vm, i, create);
376 }
377 
378 int
379 vm_create(const char *name, struct vm **retvm)
380 {
381 	struct vm *vm;
382 	struct vmspace *vmspace;
383 
384 	/*
385 	 * If vmm.ko could not be successfully initialized then don't attempt
386 	 * to create the virtual machine.
387 	 */
388 	if (!vmm_initialized)
389 		return (ENXIO);
390 
391 	if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
392 		return (EINVAL);
393 
394 	vmspace = VMSPACE_ALLOC(VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS);
395 	if (vmspace == NULL)
396 		return (ENOMEM);
397 
398 	vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
399 	strcpy(vm->name, name);
400 	vm->num_mem_segs = 0;
401 	vm->vmspace = vmspace;
402 	mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
403 
404 	vm_init(vm, true);
405 
406 	*retvm = vm;
407 	return (0);
408 }
409 
410 static void
411 vm_free_mem_seg(struct vm *vm, struct mem_seg *seg)
412 {
413 
414 	if (seg->object != NULL)
415 		vmm_mem_free(vm->vmspace, seg->gpa, seg->len);
416 
417 	bzero(seg, sizeof(*seg));
418 }
419 
420 static void
421 vm_cleanup(struct vm *vm, bool destroy)
422 {
423 	int i;
424 
425 	ppt_unassign_all(vm);
426 
427 	if (vm->iommu != NULL)
428 		iommu_destroy_domain(vm->iommu);
429 
430 	vatpit_cleanup(vm->vatpit);
431 	vhpet_cleanup(vm->vhpet);
432 	vatpic_cleanup(vm->vatpic);
433 	vioapic_cleanup(vm->vioapic);
434 
435 	for (i = 0; i < VM_MAXCPU; i++)
436 		vcpu_cleanup(vm, i, destroy);
437 
438 	VMCLEANUP(vm->cookie);
439 
440 	if (destroy) {
441 		for (i = 0; i < vm->num_mem_segs; i++)
442 			vm_free_mem_seg(vm, &vm->mem_segs[i]);
443 
444 		vm->num_mem_segs = 0;
445 
446 		VMSPACE_FREE(vm->vmspace);
447 		vm->vmspace = NULL;
448 	}
449 }
450 
451 void
452 vm_destroy(struct vm *vm)
453 {
454 	vm_cleanup(vm, true);
455 	free(vm, M_VM);
456 }
457 
458 int
459 vm_reinit(struct vm *vm)
460 {
461 	int error;
462 
463 	/*
464 	 * A virtual machine can be reset only if all vcpus are suspended.
465 	 */
466 	if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
467 		vm_cleanup(vm, false);
468 		vm_init(vm, false);
469 		error = 0;
470 	} else {
471 		error = EBUSY;
472 	}
473 
474 	return (error);
475 }
476 
477 const char *
478 vm_name(struct vm *vm)
479 {
480 	return (vm->name);
481 }
482 
483 int
484 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
485 {
486 	vm_object_t obj;
487 
488 	if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
489 		return (ENOMEM);
490 	else
491 		return (0);
492 }
493 
494 int
495 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
496 {
497 
498 	vmm_mmio_free(vm->vmspace, gpa, len);
499 	return (0);
500 }
501 
502 boolean_t
503 vm_mem_allocated(struct vm *vm, vm_paddr_t gpa)
504 {
505 	int i;
506 	vm_paddr_t gpabase, gpalimit;
507 
508 	for (i = 0; i < vm->num_mem_segs; i++) {
509 		gpabase = vm->mem_segs[i].gpa;
510 		gpalimit = gpabase + vm->mem_segs[i].len;
511 		if (gpa >= gpabase && gpa < gpalimit)
512 			return (TRUE);		/* 'gpa' is regular memory */
513 	}
514 
515 	if (ppt_is_mmio(vm, gpa))
516 		return (TRUE);			/* 'gpa' is pci passthru mmio */
517 
518 	return (FALSE);
519 }
520 
521 int
522 vm_malloc(struct vm *vm, vm_paddr_t gpa, size_t len)
523 {
524 	int available, allocated;
525 	struct mem_seg *seg;
526 	vm_object_t object;
527 	vm_paddr_t g;
528 
529 	if ((gpa & PAGE_MASK) || (len & PAGE_MASK) || len == 0)
530 		return (EINVAL);
531 
532 	available = allocated = 0;
533 	g = gpa;
534 	while (g < gpa + len) {
535 		if (vm_mem_allocated(vm, g))
536 			allocated++;
537 		else
538 			available++;
539 
540 		g += PAGE_SIZE;
541 	}
542 
543 	/*
544 	 * If there are some allocated and some available pages in the address
545 	 * range then it is an error.
546 	 */
547 	if (allocated && available)
548 		return (EINVAL);
549 
550 	/*
551 	 * If the entire address range being requested has already been
552 	 * allocated then there isn't anything more to do.
553 	 */
554 	if (allocated && available == 0)
555 		return (0);
556 
557 	if (vm->num_mem_segs >= VM_MAX_MEMORY_SEGMENTS)
558 		return (E2BIG);
559 
560 	seg = &vm->mem_segs[vm->num_mem_segs];
561 
562 	if ((object = vmm_mem_alloc(vm->vmspace, gpa, len)) == NULL)
563 		return (ENOMEM);
564 
565 	seg->gpa = gpa;
566 	seg->len = len;
567 	seg->object = object;
568 	seg->wired = FALSE;
569 
570 	vm->num_mem_segs++;
571 
572 	return (0);
573 }
574 
575 static void
576 vm_gpa_unwire(struct vm *vm)
577 {
578 	int i, rv;
579 	struct mem_seg *seg;
580 
581 	for (i = 0; i < vm->num_mem_segs; i++) {
582 		seg = &vm->mem_segs[i];
583 		if (!seg->wired)
584 			continue;
585 
586 		rv = vm_map_unwire(&vm->vmspace->vm_map,
587 				   seg->gpa, seg->gpa + seg->len,
588 				   VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
589 		KASSERT(rv == KERN_SUCCESS, ("vm(%s) memory segment "
590 		    "%#lx/%ld could not be unwired: %d",
591 		    vm_name(vm), seg->gpa, seg->len, rv));
592 
593 		seg->wired = FALSE;
594 	}
595 }
596 
597 static int
598 vm_gpa_wire(struct vm *vm)
599 {
600 	int i, rv;
601 	struct mem_seg *seg;
602 
603 	for (i = 0; i < vm->num_mem_segs; i++) {
604 		seg = &vm->mem_segs[i];
605 		if (seg->wired)
606 			continue;
607 
608 		/* XXX rlimits? */
609 		rv = vm_map_wire(&vm->vmspace->vm_map,
610 				 seg->gpa, seg->gpa + seg->len,
611 				 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
612 		if (rv != KERN_SUCCESS)
613 			break;
614 
615 		seg->wired = TRUE;
616 	}
617 
618 	if (i < vm->num_mem_segs) {
619 		/*
620 		 * Undo the wiring before returning an error.
621 		 */
622 		vm_gpa_unwire(vm);
623 		return (EAGAIN);
624 	}
625 
626 	return (0);
627 }
628 
629 static void
630 vm_iommu_modify(struct vm *vm, boolean_t map)
631 {
632 	int i, sz;
633 	vm_paddr_t gpa, hpa;
634 	struct mem_seg *seg;
635 	void *vp, *cookie, *host_domain;
636 
637 	sz = PAGE_SIZE;
638 	host_domain = iommu_host_domain();
639 
640 	for (i = 0; i < vm->num_mem_segs; i++) {
641 		seg = &vm->mem_segs[i];
642 		KASSERT(seg->wired, ("vm(%s) memory segment %#lx/%ld not wired",
643 		    vm_name(vm), seg->gpa, seg->len));
644 
645 		gpa = seg->gpa;
646 		while (gpa < seg->gpa + seg->len) {
647 			vp = vm_gpa_hold(vm, gpa, PAGE_SIZE, VM_PROT_WRITE,
648 					 &cookie);
649 			KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
650 			    vm_name(vm), gpa));
651 
652 			vm_gpa_release(cookie);
653 
654 			hpa = DMAP_TO_PHYS((uintptr_t)vp);
655 			if (map) {
656 				iommu_create_mapping(vm->iommu, gpa, hpa, sz);
657 				iommu_remove_mapping(host_domain, hpa, sz);
658 			} else {
659 				iommu_remove_mapping(vm->iommu, gpa, sz);
660 				iommu_create_mapping(host_domain, hpa, hpa, sz);
661 			}
662 
663 			gpa += PAGE_SIZE;
664 		}
665 	}
666 
667 	/*
668 	 * Invalidate the cached translations associated with the domain
669 	 * from which pages were removed.
670 	 */
671 	if (map)
672 		iommu_invalidate_tlb(host_domain);
673 	else
674 		iommu_invalidate_tlb(vm->iommu);
675 }
676 
677 #define	vm_iommu_unmap(vm)	vm_iommu_modify((vm), FALSE)
678 #define	vm_iommu_map(vm)	vm_iommu_modify((vm), TRUE)
679 
680 int
681 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
682 {
683 	int error;
684 
685 	error = ppt_unassign_device(vm, bus, slot, func);
686 	if (error)
687 		return (error);
688 
689 	if (ppt_assigned_devices(vm) == 0) {
690 		vm_iommu_unmap(vm);
691 		vm_gpa_unwire(vm);
692 	}
693 	return (0);
694 }
695 
696 int
697 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
698 {
699 	int error;
700 	vm_paddr_t maxaddr;
701 
702 	/*
703 	 * Virtual machines with pci passthru devices get special treatment:
704 	 * - the guest physical memory is wired
705 	 * - the iommu is programmed to do the 'gpa' to 'hpa' translation
706 	 *
707 	 * We need to do this before the first pci passthru device is attached.
708 	 */
709 	if (ppt_assigned_devices(vm) == 0) {
710 		KASSERT(vm->iommu == NULL,
711 		    ("vm_assign_pptdev: iommu must be NULL"));
712 		maxaddr = vmm_mem_maxaddr();
713 		vm->iommu = iommu_create_domain(maxaddr);
714 
715 		error = vm_gpa_wire(vm);
716 		if (error)
717 			return (error);
718 
719 		vm_iommu_map(vm);
720 	}
721 
722 	error = ppt_assign_device(vm, bus, slot, func);
723 	return (error);
724 }
725 
726 void *
727 vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
728 	    void **cookie)
729 {
730 	int count, pageoff;
731 	vm_page_t m;
732 
733 	pageoff = gpa & PAGE_MASK;
734 	if (len > PAGE_SIZE - pageoff)
735 		panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
736 
737 	count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
738 	    trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
739 
740 	if (count == 1) {
741 		*cookie = m;
742 		return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
743 	} else {
744 		*cookie = NULL;
745 		return (NULL);
746 	}
747 }
748 
749 void
750 vm_gpa_release(void *cookie)
751 {
752 	vm_page_t m = cookie;
753 
754 	vm_page_lock(m);
755 	vm_page_unhold(m);
756 	vm_page_unlock(m);
757 }
758 
759 int
760 vm_gpabase2memseg(struct vm *vm, vm_paddr_t gpabase,
761 		  struct vm_memory_segment *seg)
762 {
763 	int i;
764 
765 	for (i = 0; i < vm->num_mem_segs; i++) {
766 		if (gpabase == vm->mem_segs[i].gpa) {
767 			seg->gpa = vm->mem_segs[i].gpa;
768 			seg->len = vm->mem_segs[i].len;
769 			seg->wired = vm->mem_segs[i].wired;
770 			return (0);
771 		}
772 	}
773 	return (-1);
774 }
775 
776 int
777 vm_get_memobj(struct vm *vm, vm_paddr_t gpa, size_t len,
778 	      vm_offset_t *offset, struct vm_object **object)
779 {
780 	int i;
781 	size_t seg_len;
782 	vm_paddr_t seg_gpa;
783 	vm_object_t seg_obj;
784 
785 	for (i = 0; i < vm->num_mem_segs; i++) {
786 		if ((seg_obj = vm->mem_segs[i].object) == NULL)
787 			continue;
788 
789 		seg_gpa = vm->mem_segs[i].gpa;
790 		seg_len = vm->mem_segs[i].len;
791 
792 		if (gpa >= seg_gpa && gpa < seg_gpa + seg_len) {
793 			*offset = gpa - seg_gpa;
794 			*object = seg_obj;
795 			vm_object_reference(seg_obj);
796 			return (0);
797 		}
798 	}
799 
800 	return (EINVAL);
801 }
802 
803 int
804 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
805 {
806 
807 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
808 		return (EINVAL);
809 
810 	if (reg >= VM_REG_LAST)
811 		return (EINVAL);
812 
813 	return (VMGETREG(vm->cookie, vcpu, reg, retval));
814 }
815 
816 int
817 vm_set_register(struct vm *vm, int vcpu, int reg, uint64_t val)
818 {
819 
820 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
821 		return (EINVAL);
822 
823 	if (reg >= VM_REG_LAST)
824 		return (EINVAL);
825 
826 	return (VMSETREG(vm->cookie, vcpu, reg, val));
827 }
828 
829 static boolean_t
830 is_descriptor_table(int reg)
831 {
832 
833 	switch (reg) {
834 	case VM_REG_GUEST_IDTR:
835 	case VM_REG_GUEST_GDTR:
836 		return (TRUE);
837 	default:
838 		return (FALSE);
839 	}
840 }
841 
842 static boolean_t
843 is_segment_register(int reg)
844 {
845 
846 	switch (reg) {
847 	case VM_REG_GUEST_ES:
848 	case VM_REG_GUEST_CS:
849 	case VM_REG_GUEST_SS:
850 	case VM_REG_GUEST_DS:
851 	case VM_REG_GUEST_FS:
852 	case VM_REG_GUEST_GS:
853 	case VM_REG_GUEST_TR:
854 	case VM_REG_GUEST_LDTR:
855 		return (TRUE);
856 	default:
857 		return (FALSE);
858 	}
859 }
860 
861 int
862 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
863 		struct seg_desc *desc)
864 {
865 
866 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
867 		return (EINVAL);
868 
869 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
870 		return (EINVAL);
871 
872 	return (VMGETDESC(vm->cookie, vcpu, reg, desc));
873 }
874 
875 int
876 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
877 		struct seg_desc *desc)
878 {
879 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
880 		return (EINVAL);
881 
882 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
883 		return (EINVAL);
884 
885 	return (VMSETDESC(vm->cookie, vcpu, reg, desc));
886 }
887 
888 static void
889 restore_guest_fpustate(struct vcpu *vcpu)
890 {
891 
892 	/* flush host state to the pcb */
893 	fpuexit(curthread);
894 
895 	/* restore guest FPU state */
896 	fpu_stop_emulating();
897 	fpurestore(vcpu->guestfpu);
898 
899 	/* restore guest XCR0 if XSAVE is enabled in the host */
900 	if (rcr4() & CR4_XSAVE)
901 		load_xcr(0, vcpu->guest_xcr0);
902 
903 	/*
904 	 * The FPU is now "dirty" with the guest's state so turn on emulation
905 	 * to trap any access to the FPU by the host.
906 	 */
907 	fpu_start_emulating();
908 }
909 
910 static void
911 save_guest_fpustate(struct vcpu *vcpu)
912 {
913 
914 	if ((rcr0() & CR0_TS) == 0)
915 		panic("fpu emulation not enabled in host!");
916 
917 	/* save guest XCR0 and restore host XCR0 */
918 	if (rcr4() & CR4_XSAVE) {
919 		vcpu->guest_xcr0 = rxcr(0);
920 		load_xcr(0, vmm_get_host_xcr0());
921 	}
922 
923 	/* save guest FPU state */
924 	fpu_stop_emulating();
925 	fpusave(vcpu->guestfpu);
926 	fpu_start_emulating();
927 }
928 
929 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
930 
931 static int
932 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
933     bool from_idle)
934 {
935 	int error;
936 
937 	vcpu_assert_locked(vcpu);
938 
939 	/*
940 	 * State transitions from the vmmdev_ioctl() must always begin from
941 	 * the VCPU_IDLE state. This guarantees that there is only a single
942 	 * ioctl() operating on a vcpu at any point.
943 	 */
944 	if (from_idle) {
945 		while (vcpu->state != VCPU_IDLE)
946 			msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
947 	} else {
948 		KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
949 		    "vcpu idle state"));
950 	}
951 
952 	if (vcpu->state == VCPU_RUNNING) {
953 		KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
954 		    "mismatch for running vcpu", curcpu, vcpu->hostcpu));
955 	} else {
956 		KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
957 		    "vcpu that is not running", vcpu->hostcpu));
958 	}
959 
960 	/*
961 	 * The following state transitions are allowed:
962 	 * IDLE -> FROZEN -> IDLE
963 	 * FROZEN -> RUNNING -> FROZEN
964 	 * FROZEN -> SLEEPING -> FROZEN
965 	 */
966 	switch (vcpu->state) {
967 	case VCPU_IDLE:
968 	case VCPU_RUNNING:
969 	case VCPU_SLEEPING:
970 		error = (newstate != VCPU_FROZEN);
971 		break;
972 	case VCPU_FROZEN:
973 		error = (newstate == VCPU_FROZEN);
974 		break;
975 	default:
976 		error = 1;
977 		break;
978 	}
979 
980 	if (error)
981 		return (EBUSY);
982 
983 	vcpu->state = newstate;
984 	if (newstate == VCPU_RUNNING)
985 		vcpu->hostcpu = curcpu;
986 	else
987 		vcpu->hostcpu = NOCPU;
988 
989 	if (newstate == VCPU_IDLE)
990 		wakeup(&vcpu->state);
991 
992 	return (0);
993 }
994 
995 static void
996 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
997 {
998 	int error;
999 
1000 	if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
1001 		panic("Error %d setting state to %d\n", error, newstate);
1002 }
1003 
1004 static void
1005 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
1006 {
1007 	int error;
1008 
1009 	if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
1010 		panic("Error %d setting state to %d", error, newstate);
1011 }
1012 
1013 static void
1014 vm_set_rendezvous_func(struct vm *vm, vm_rendezvous_func_t func)
1015 {
1016 
1017 	KASSERT(mtx_owned(&vm->rendezvous_mtx), ("rendezvous_mtx not locked"));
1018 
1019 	/*
1020 	 * Update 'rendezvous_func' and execute a write memory barrier to
1021 	 * ensure that it is visible across all host cpus. This is not needed
1022 	 * for correctness but it does ensure that all the vcpus will notice
1023 	 * that the rendezvous is requested immediately.
1024 	 */
1025 	vm->rendezvous_func = func;
1026 	wmb();
1027 }
1028 
1029 #define	RENDEZVOUS_CTR0(vm, vcpuid, fmt)				\
1030 	do {								\
1031 		if (vcpuid >= 0)					\
1032 			VCPU_CTR0(vm, vcpuid, fmt);			\
1033 		else							\
1034 			VM_CTR0(vm, fmt);				\
1035 	} while (0)
1036 
1037 static void
1038 vm_handle_rendezvous(struct vm *vm, int vcpuid)
1039 {
1040 
1041 	KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
1042 	    ("vm_handle_rendezvous: invalid vcpuid %d", vcpuid));
1043 
1044 	mtx_lock(&vm->rendezvous_mtx);
1045 	while (vm->rendezvous_func != NULL) {
1046 		/* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1047 		CPU_AND(&vm->rendezvous_req_cpus, &vm->active_cpus);
1048 
1049 		if (vcpuid != -1 &&
1050 		    CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1051 		    !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1052 			VCPU_CTR0(vm, vcpuid, "Calling rendezvous func");
1053 			(*vm->rendezvous_func)(vm, vcpuid, vm->rendezvous_arg);
1054 			CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1055 		}
1056 		if (CPU_CMP(&vm->rendezvous_req_cpus,
1057 		    &vm->rendezvous_done_cpus) == 0) {
1058 			VCPU_CTR0(vm, vcpuid, "Rendezvous completed");
1059 			vm_set_rendezvous_func(vm, NULL);
1060 			wakeup(&vm->rendezvous_func);
1061 			break;
1062 		}
1063 		RENDEZVOUS_CTR0(vm, vcpuid, "Wait for rendezvous completion");
1064 		mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1065 		    "vmrndv", 0);
1066 	}
1067 	mtx_unlock(&vm->rendezvous_mtx);
1068 }
1069 
1070 /*
1071  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1072  */
1073 static int
1074 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled, bool *retu)
1075 {
1076 	struct vcpu *vcpu;
1077 	const char *wmesg;
1078 	int t, vcpu_halted, vm_halted;
1079 
1080 	KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1081 
1082 	vcpu = &vm->vcpu[vcpuid];
1083 	vcpu_halted = 0;
1084 	vm_halted = 0;
1085 
1086 	vcpu_lock(vcpu);
1087 	while (1) {
1088 		/*
1089 		 * Do a final check for pending NMI or interrupts before
1090 		 * really putting this thread to sleep. Also check for
1091 		 * software events that would cause this vcpu to wakeup.
1092 		 *
1093 		 * These interrupts/events could have happened after the
1094 		 * vcpu returned from VMRUN() and before it acquired the
1095 		 * vcpu lock above.
1096 		 */
1097 		if (vm->rendezvous_func != NULL || vm->suspend)
1098 			break;
1099 		if (vm_nmi_pending(vm, vcpuid))
1100 			break;
1101 		if (!intr_disabled) {
1102 			if (vm_extint_pending(vm, vcpuid) ||
1103 			    vlapic_pending_intr(vcpu->vlapic, NULL)) {
1104 				break;
1105 			}
1106 		}
1107 
1108 		/*
1109 		 * Some Linux guests implement "halt" by having all vcpus
1110 		 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1111 		 * track of the vcpus that have entered this state. When all
1112 		 * vcpus enter the halted state the virtual machine is halted.
1113 		 */
1114 		if (intr_disabled) {
1115 			wmesg = "vmhalt";
1116 			VCPU_CTR0(vm, vcpuid, "Halted");
1117 			if (!vcpu_halted && halt_detection_enabled) {
1118 				vcpu_halted = 1;
1119 				CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1120 			}
1121 			if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1122 				vm_halted = 1;
1123 				break;
1124 			}
1125 		} else {
1126 			wmesg = "vmidle";
1127 		}
1128 
1129 		t = ticks;
1130 		vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1131 		msleep_spin(vcpu, &vcpu->mtx, wmesg, 0);
1132 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1133 		vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1134 	}
1135 
1136 	if (vcpu_halted)
1137 		CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1138 
1139 	vcpu_unlock(vcpu);
1140 
1141 	if (vm_halted)
1142 		vm_suspend(vm, VM_SUSPEND_HALT);
1143 
1144 	return (0);
1145 }
1146 
1147 static int
1148 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1149 {
1150 	int rv, ftype;
1151 	struct vm_map *map;
1152 	struct vcpu *vcpu;
1153 	struct vm_exit *vme;
1154 
1155 	vcpu = &vm->vcpu[vcpuid];
1156 	vme = &vcpu->exitinfo;
1157 
1158 	ftype = vme->u.paging.fault_type;
1159 	KASSERT(ftype == VM_PROT_READ ||
1160 	    ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1161 	    ("vm_handle_paging: invalid fault_type %d", ftype));
1162 
1163 	if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1164 		rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1165 		    vme->u.paging.gpa, ftype);
1166 		if (rv == 0)
1167 			goto done;
1168 	}
1169 
1170 	map = &vm->vmspace->vm_map;
1171 	rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
1172 
1173 	VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1174 	    "ftype = %d", rv, vme->u.paging.gpa, ftype);
1175 
1176 	if (rv != KERN_SUCCESS)
1177 		return (EFAULT);
1178 done:
1179 	/* restart execution at the faulting instruction */
1180 	vme->inst_length = 0;
1181 
1182 	return (0);
1183 }
1184 
1185 static int
1186 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1187 {
1188 	struct vie *vie;
1189 	struct vcpu *vcpu;
1190 	struct vm_exit *vme;
1191 	uint64_t gla, gpa;
1192 	struct vm_guest_paging *paging;
1193 	mem_region_read_t mread;
1194 	mem_region_write_t mwrite;
1195 	enum vm_cpu_mode cpu_mode;
1196 	int cs_d, error;
1197 
1198 	vcpu = &vm->vcpu[vcpuid];
1199 	vme = &vcpu->exitinfo;
1200 
1201 	gla = vme->u.inst_emul.gla;
1202 	gpa = vme->u.inst_emul.gpa;
1203 	cs_d = vme->u.inst_emul.cs_d;
1204 	vie = &vme->u.inst_emul.vie;
1205 	paging = &vme->u.inst_emul.paging;
1206 	cpu_mode = paging->cpu_mode;
1207 
1208 	vie_init(vie);
1209 
1210 	/* Fetch, decode and emulate the faulting instruction */
1211 	error = vmm_fetch_instruction(vm, vcpuid, paging, vme->rip,
1212 	    vme->inst_length, vie);
1213 	if (error == 1)
1214 		return (0);		/* Resume guest to handle page fault */
1215 	else if (error == -1)
1216 		return (EFAULT);
1217 	else if (error != 0)
1218 		panic("%s: vmm_fetch_instruction error %d", __func__, error);
1219 
1220 	if (vmm_decode_instruction(vm, vcpuid, gla, cpu_mode, cs_d, vie) != 0)
1221 		return (EFAULT);
1222 
1223 	/* return to userland unless this is an in-kernel emulated device */
1224 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1225 		mread = lapic_mmio_read;
1226 		mwrite = lapic_mmio_write;
1227 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1228 		mread = vioapic_mmio_read;
1229 		mwrite = vioapic_mmio_write;
1230 	} else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1231 		mread = vhpet_mmio_read;
1232 		mwrite = vhpet_mmio_write;
1233 	} else {
1234 		*retu = true;
1235 		return (0);
1236 	}
1237 
1238 	error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, mread, mwrite,
1239 	    retu);
1240 
1241 	return (error);
1242 }
1243 
1244 static int
1245 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1246 {
1247 	int i, done;
1248 	struct vcpu *vcpu;
1249 
1250 	done = 0;
1251 	vcpu = &vm->vcpu[vcpuid];
1252 
1253 	CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1254 
1255 	/*
1256 	 * Wait until all 'active_cpus' have suspended themselves.
1257 	 *
1258 	 * Since a VM may be suspended at any time including when one or
1259 	 * more vcpus are doing a rendezvous we need to call the rendezvous
1260 	 * handler while we are waiting to prevent a deadlock.
1261 	 */
1262 	vcpu_lock(vcpu);
1263 	while (1) {
1264 		if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1265 			VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1266 			break;
1267 		}
1268 
1269 		if (vm->rendezvous_func == NULL) {
1270 			VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1271 			vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1272 			msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1273 			vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1274 		} else {
1275 			VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1276 			vcpu_unlock(vcpu);
1277 			vm_handle_rendezvous(vm, vcpuid);
1278 			vcpu_lock(vcpu);
1279 		}
1280 	}
1281 	vcpu_unlock(vcpu);
1282 
1283 	/*
1284 	 * Wakeup the other sleeping vcpus and return to userspace.
1285 	 */
1286 	for (i = 0; i < VM_MAXCPU; i++) {
1287 		if (CPU_ISSET(i, &vm->suspended_cpus)) {
1288 			vcpu_notify_event(vm, i, false);
1289 		}
1290 	}
1291 
1292 	*retu = true;
1293 	return (0);
1294 }
1295 
1296 int
1297 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1298 {
1299 	int i;
1300 
1301 	if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1302 		return (EINVAL);
1303 
1304 	if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1305 		VM_CTR2(vm, "virtual machine already suspended %d/%d",
1306 		    vm->suspend, how);
1307 		return (EALREADY);
1308 	}
1309 
1310 	VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1311 
1312 	/*
1313 	 * Notify all active vcpus that they are now suspended.
1314 	 */
1315 	for (i = 0; i < VM_MAXCPU; i++) {
1316 		if (CPU_ISSET(i, &vm->active_cpus))
1317 			vcpu_notify_event(vm, i, false);
1318 	}
1319 
1320 	return (0);
1321 }
1322 
1323 void
1324 vm_exit_suspended(struct vm *vm, int vcpuid, uint64_t rip)
1325 {
1326 	struct vm_exit *vmexit;
1327 
1328 	KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1329 	    ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1330 
1331 	vmexit = vm_exitinfo(vm, vcpuid);
1332 	vmexit->rip = rip;
1333 	vmexit->inst_length = 0;
1334 	vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1335 	vmexit->u.suspended.how = vm->suspend;
1336 }
1337 
1338 void
1339 vm_exit_rendezvous(struct vm *vm, int vcpuid, uint64_t rip)
1340 {
1341 	struct vm_exit *vmexit;
1342 
1343 	KASSERT(vm->rendezvous_func != NULL, ("rendezvous not in progress"));
1344 
1345 	vmexit = vm_exitinfo(vm, vcpuid);
1346 	vmexit->rip = rip;
1347 	vmexit->inst_length = 0;
1348 	vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1349 	vmm_stat_incr(vm, vcpuid, VMEXIT_RENDEZVOUS, 1);
1350 }
1351 
1352 void
1353 vm_exit_astpending(struct vm *vm, int vcpuid, uint64_t rip)
1354 {
1355 	struct vm_exit *vmexit;
1356 
1357 	vmexit = vm_exitinfo(vm, vcpuid);
1358 	vmexit->rip = rip;
1359 	vmexit->inst_length = 0;
1360 	vmexit->exitcode = VM_EXITCODE_BOGUS;
1361 	vmm_stat_incr(vm, vcpuid, VMEXIT_ASTPENDING, 1);
1362 }
1363 
1364 int
1365 vm_run(struct vm *vm, struct vm_run *vmrun)
1366 {
1367 	int error, vcpuid;
1368 	struct vcpu *vcpu;
1369 	struct pcb *pcb;
1370 	uint64_t tscval, rip;
1371 	struct vm_exit *vme;
1372 	bool retu, intr_disabled;
1373 	pmap_t pmap;
1374 	void *rptr, *sptr;
1375 
1376 	vcpuid = vmrun->cpuid;
1377 
1378 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1379 		return (EINVAL);
1380 
1381 	if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1382 		return (EINVAL);
1383 
1384 	if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1385 		return (EINVAL);
1386 
1387 	rptr = &vm->rendezvous_func;
1388 	sptr = &vm->suspend;
1389 	pmap = vmspace_pmap(vm->vmspace);
1390 	vcpu = &vm->vcpu[vcpuid];
1391 	vme = &vcpu->exitinfo;
1392 	rip = vmrun->rip;
1393 restart:
1394 	critical_enter();
1395 
1396 	KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1397 	    ("vm_run: absurd pm_active"));
1398 
1399 	tscval = rdtsc();
1400 
1401 	pcb = PCPU_GET(curpcb);
1402 	set_pcb_flags(pcb, PCB_FULL_IRET);
1403 
1404 	restore_guest_msrs(vm, vcpuid);
1405 	restore_guest_fpustate(vcpu);
1406 
1407 	vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1408 	error = VMRUN(vm->cookie, vcpuid, rip, pmap, rptr, sptr);
1409 	vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1410 
1411 	save_guest_fpustate(vcpu);
1412 	restore_host_msrs(vm, vcpuid);
1413 
1414 	vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1415 
1416 	critical_exit();
1417 
1418 	if (error == 0) {
1419 		retu = false;
1420 		switch (vme->exitcode) {
1421 		case VM_EXITCODE_SUSPENDED:
1422 			error = vm_handle_suspend(vm, vcpuid, &retu);
1423 			break;
1424 		case VM_EXITCODE_IOAPIC_EOI:
1425 			vioapic_process_eoi(vm, vcpuid,
1426 			    vme->u.ioapic_eoi.vector);
1427 			break;
1428 		case VM_EXITCODE_RENDEZVOUS:
1429 			vm_handle_rendezvous(vm, vcpuid);
1430 			error = 0;
1431 			break;
1432 		case VM_EXITCODE_HLT:
1433 			intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1434 			error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1435 			break;
1436 		case VM_EXITCODE_PAGING:
1437 			error = vm_handle_paging(vm, vcpuid, &retu);
1438 			break;
1439 		case VM_EXITCODE_INST_EMUL:
1440 			error = vm_handle_inst_emul(vm, vcpuid, &retu);
1441 			break;
1442 		case VM_EXITCODE_INOUT:
1443 		case VM_EXITCODE_INOUT_STR:
1444 			error = vm_handle_inout(vm, vcpuid, vme, &retu);
1445 			break;
1446 		default:
1447 			retu = true;	/* handled in userland */
1448 			break;
1449 		}
1450 	}
1451 
1452 	if (error == 0 && retu == false) {
1453 		rip = vme->rip + vme->inst_length;
1454 		goto restart;
1455 	}
1456 
1457 	/* copy the exit information */
1458 	bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1459 	return (error);
1460 }
1461 
1462 int
1463 vm_exit_intinfo(struct vm *vm, int vcpuid, uint64_t info)
1464 {
1465 	struct vcpu *vcpu;
1466 	int type, vector;
1467 
1468 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1469 		return (EINVAL);
1470 
1471 	vcpu = &vm->vcpu[vcpuid];
1472 
1473 	if (info & VM_INTINFO_VALID) {
1474 		type = info & VM_INTINFO_TYPE;
1475 		vector = info & 0xff;
1476 		if (type == VM_INTINFO_NMI && vector != IDT_NMI)
1477 			return (EINVAL);
1478 		if (type == VM_INTINFO_HWEXCEPTION && vector >= 32)
1479 			return (EINVAL);
1480 		if (info & VM_INTINFO_RSVD)
1481 			return (EINVAL);
1482 	} else {
1483 		info = 0;
1484 	}
1485 	VCPU_CTR2(vm, vcpuid, "%s: info1(%#lx)", __func__, info);
1486 	vcpu->exitintinfo = info;
1487 	return (0);
1488 }
1489 
1490 enum exc_class {
1491 	EXC_BENIGN,
1492 	EXC_CONTRIBUTORY,
1493 	EXC_PAGEFAULT
1494 };
1495 
1496 #define	IDT_VE	20	/* Virtualization Exception (Intel specific) */
1497 
1498 static enum exc_class
1499 exception_class(uint64_t info)
1500 {
1501 	int type, vector;
1502 
1503 	KASSERT(info & VM_INTINFO_VALID, ("intinfo must be valid: %#lx", info));
1504 	type = info & VM_INTINFO_TYPE;
1505 	vector = info & 0xff;
1506 
1507 	/* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
1508 	switch (type) {
1509 	case VM_INTINFO_HWINTR:
1510 	case VM_INTINFO_SWINTR:
1511 	case VM_INTINFO_NMI:
1512 		return (EXC_BENIGN);
1513 	default:
1514 		/*
1515 		 * Hardware exception.
1516 		 *
1517 		 * SVM and VT-x use identical type values to represent NMI,
1518 		 * hardware interrupt and software interrupt.
1519 		 *
1520 		 * SVM uses type '3' for all exceptions. VT-x uses type '3'
1521 		 * for exceptions except #BP and #OF. #BP and #OF use a type
1522 		 * value of '5' or '6'. Therefore we don't check for explicit
1523 		 * values of 'type' to classify 'intinfo' into a hardware
1524 		 * exception.
1525 		 */
1526 		break;
1527 	}
1528 
1529 	switch (vector) {
1530 	case IDT_PF:
1531 	case IDT_VE:
1532 		return (EXC_PAGEFAULT);
1533 	case IDT_DE:
1534 	case IDT_TS:
1535 	case IDT_NP:
1536 	case IDT_SS:
1537 	case IDT_GP:
1538 		return (EXC_CONTRIBUTORY);
1539 	default:
1540 		return (EXC_BENIGN);
1541 	}
1542 }
1543 
1544 static int
1545 nested_fault(struct vm *vm, int vcpuid, uint64_t info1, uint64_t info2,
1546     uint64_t *retinfo)
1547 {
1548 	enum exc_class exc1, exc2;
1549 	int type1, vector1;
1550 
1551 	KASSERT(info1 & VM_INTINFO_VALID, ("info1 %#lx is not valid", info1));
1552 	KASSERT(info2 & VM_INTINFO_VALID, ("info2 %#lx is not valid", info2));
1553 
1554 	/*
1555 	 * If an exception occurs while attempting to call the double-fault
1556 	 * handler the processor enters shutdown mode (aka triple fault).
1557 	 */
1558 	type1 = info1 & VM_INTINFO_TYPE;
1559 	vector1 = info1 & 0xff;
1560 	if (type1 == VM_INTINFO_HWEXCEPTION && vector1 == IDT_DF) {
1561 		VCPU_CTR2(vm, vcpuid, "triple fault: info1(%#lx), info2(%#lx)",
1562 		    info1, info2);
1563 		vm_suspend(vm, VM_SUSPEND_TRIPLEFAULT);
1564 		*retinfo = 0;
1565 		return (0);
1566 	}
1567 
1568 	/*
1569 	 * Table 6-5 "Conditions for Generating a Double Fault", Intel SDM, Vol3
1570 	 */
1571 	exc1 = exception_class(info1);
1572 	exc2 = exception_class(info2);
1573 	if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
1574 	    (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
1575 		/* Convert nested fault into a double fault. */
1576 		*retinfo = IDT_DF;
1577 		*retinfo |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1578 		*retinfo |= VM_INTINFO_DEL_ERRCODE;
1579 	} else {
1580 		/* Handle exceptions serially */
1581 		*retinfo = info2;
1582 	}
1583 	return (1);
1584 }
1585 
1586 static uint64_t
1587 vcpu_exception_intinfo(struct vcpu *vcpu)
1588 {
1589 	uint64_t info = 0;
1590 
1591 	if (vcpu->exception_pending) {
1592 		info = vcpu->exception.vector & 0xff;
1593 		info |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1594 		if (vcpu->exception.error_code_valid) {
1595 			info |= VM_INTINFO_DEL_ERRCODE;
1596 			info |= (uint64_t)vcpu->exception.error_code << 32;
1597 		}
1598 	}
1599 	return (info);
1600 }
1601 
1602 int
1603 vm_entry_intinfo(struct vm *vm, int vcpuid, uint64_t *retinfo)
1604 {
1605 	struct vcpu *vcpu;
1606 	uint64_t info1, info2;
1607 	int valid;
1608 
1609 	KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU, ("invalid vcpu %d", vcpuid));
1610 
1611 	vcpu = &vm->vcpu[vcpuid];
1612 
1613 	info1 = vcpu->exitintinfo;
1614 	vcpu->exitintinfo = 0;
1615 
1616 	info2 = 0;
1617 	if (vcpu->exception_pending) {
1618 		info2 = vcpu_exception_intinfo(vcpu);
1619 		vcpu->exception_pending = 0;
1620 		VCPU_CTR2(vm, vcpuid, "Exception %d delivered: %#lx",
1621 		    vcpu->exception.vector, info2);
1622 	}
1623 
1624 	if ((info1 & VM_INTINFO_VALID) && (info2 & VM_INTINFO_VALID)) {
1625 		valid = nested_fault(vm, vcpuid, info1, info2, retinfo);
1626 	} else if (info1 & VM_INTINFO_VALID) {
1627 		*retinfo = info1;
1628 		valid = 1;
1629 	} else if (info2 & VM_INTINFO_VALID) {
1630 		*retinfo = info2;
1631 		valid = 1;
1632 	} else {
1633 		valid = 0;
1634 	}
1635 
1636 	if (valid) {
1637 		VCPU_CTR4(vm, vcpuid, "%s: info1(%#lx), info2(%#lx), "
1638 		    "retinfo(%#lx)", __func__, info1, info2, *retinfo);
1639 	}
1640 
1641 	return (valid);
1642 }
1643 
1644 int
1645 vm_get_intinfo(struct vm *vm, int vcpuid, uint64_t *info1, uint64_t *info2)
1646 {
1647 	struct vcpu *vcpu;
1648 
1649 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1650 		return (EINVAL);
1651 
1652 	vcpu = &vm->vcpu[vcpuid];
1653 	*info1 = vcpu->exitintinfo;
1654 	*info2 = vcpu_exception_intinfo(vcpu);
1655 	return (0);
1656 }
1657 
1658 int
1659 vm_inject_exception(struct vm *vm, int vcpuid, struct vm_exception *exception)
1660 {
1661 	struct vcpu *vcpu;
1662 
1663 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1664 		return (EINVAL);
1665 
1666 	if (exception->vector < 0 || exception->vector >= 32)
1667 		return (EINVAL);
1668 
1669 	/*
1670 	 * A double fault exception should never be injected directly into
1671 	 * the guest. It is a derived exception that results from specific
1672 	 * combinations of nested faults.
1673 	 */
1674 	if (exception->vector == IDT_DF)
1675 		return (EINVAL);
1676 
1677 	vcpu = &vm->vcpu[vcpuid];
1678 
1679 	if (vcpu->exception_pending) {
1680 		VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
1681 		    "pending exception %d", exception->vector,
1682 		    vcpu->exception.vector);
1683 		return (EBUSY);
1684 	}
1685 
1686 	vcpu->exception_pending = 1;
1687 	vcpu->exception = *exception;
1688 	VCPU_CTR1(vm, vcpuid, "Exception %d pending", exception->vector);
1689 	return (0);
1690 }
1691 
1692 static void
1693 vm_inject_fault(struct vm *vm, int vcpuid, struct vm_exception *exception)
1694 {
1695 	struct vm_exit *vmexit;
1696 	int error;
1697 
1698 	error = vm_inject_exception(vm, vcpuid, exception);
1699 	KASSERT(error == 0, ("vm_inject_exception error %d", error));
1700 
1701 	/*
1702 	 * A fault-like exception allows the instruction to be restarted
1703 	 * after the exception handler returns.
1704 	 *
1705 	 * By setting the inst_length to 0 we ensure that the instruction
1706 	 * pointer remains at the faulting instruction.
1707 	 */
1708 	vmexit = vm_exitinfo(vm, vcpuid);
1709 	vmexit->inst_length = 0;
1710 }
1711 
1712 void
1713 vm_inject_pf(struct vm *vm, int vcpuid, int error_code, uint64_t cr2)
1714 {
1715 	struct vm_exception pf = {
1716 		.vector = IDT_PF,
1717 		.error_code_valid = 1,
1718 		.error_code = error_code
1719 	};
1720 	int error;
1721 
1722 	VCPU_CTR2(vm, vcpuid, "Injecting page fault: error_code %#x, cr2 %#lx",
1723 	    error_code, cr2);
1724 
1725 	error = vm_set_register(vm, vcpuid, VM_REG_GUEST_CR2, cr2);
1726 	KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
1727 
1728 	vm_inject_fault(vm, vcpuid, &pf);
1729 }
1730 
1731 void
1732 vm_inject_gp(struct vm *vm, int vcpuid)
1733 {
1734 	struct vm_exception gpf = {
1735 		.vector = IDT_GP,
1736 		.error_code_valid = 1,
1737 		.error_code = 0
1738 	};
1739 
1740 	vm_inject_fault(vm, vcpuid, &gpf);
1741 }
1742 
1743 void
1744 vm_inject_ud(struct vm *vm, int vcpuid)
1745 {
1746 	struct vm_exception udf = {
1747 		.vector = IDT_UD,
1748 		.error_code_valid = 0
1749 	};
1750 
1751 	vm_inject_fault(vm, vcpuid, &udf);
1752 }
1753 
1754 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1755 
1756 int
1757 vm_inject_nmi(struct vm *vm, int vcpuid)
1758 {
1759 	struct vcpu *vcpu;
1760 
1761 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1762 		return (EINVAL);
1763 
1764 	vcpu = &vm->vcpu[vcpuid];
1765 
1766 	vcpu->nmi_pending = 1;
1767 	vcpu_notify_event(vm, vcpuid, false);
1768 	return (0);
1769 }
1770 
1771 int
1772 vm_nmi_pending(struct vm *vm, int vcpuid)
1773 {
1774 	struct vcpu *vcpu;
1775 
1776 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1777 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1778 
1779 	vcpu = &vm->vcpu[vcpuid];
1780 
1781 	return (vcpu->nmi_pending);
1782 }
1783 
1784 void
1785 vm_nmi_clear(struct vm *vm, int vcpuid)
1786 {
1787 	struct vcpu *vcpu;
1788 
1789 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1790 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1791 
1792 	vcpu = &vm->vcpu[vcpuid];
1793 
1794 	if (vcpu->nmi_pending == 0)
1795 		panic("vm_nmi_clear: inconsistent nmi_pending state");
1796 
1797 	vcpu->nmi_pending = 0;
1798 	vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1799 }
1800 
1801 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
1802 
1803 int
1804 vm_inject_extint(struct vm *vm, int vcpuid)
1805 {
1806 	struct vcpu *vcpu;
1807 
1808 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1809 		return (EINVAL);
1810 
1811 	vcpu = &vm->vcpu[vcpuid];
1812 
1813 	vcpu->extint_pending = 1;
1814 	vcpu_notify_event(vm, vcpuid, false);
1815 	return (0);
1816 }
1817 
1818 int
1819 vm_extint_pending(struct vm *vm, int vcpuid)
1820 {
1821 	struct vcpu *vcpu;
1822 
1823 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1824 		panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1825 
1826 	vcpu = &vm->vcpu[vcpuid];
1827 
1828 	return (vcpu->extint_pending);
1829 }
1830 
1831 void
1832 vm_extint_clear(struct vm *vm, int vcpuid)
1833 {
1834 	struct vcpu *vcpu;
1835 
1836 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1837 		panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1838 
1839 	vcpu = &vm->vcpu[vcpuid];
1840 
1841 	if (vcpu->extint_pending == 0)
1842 		panic("vm_extint_clear: inconsistent extint_pending state");
1843 
1844 	vcpu->extint_pending = 0;
1845 	vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
1846 }
1847 
1848 int
1849 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
1850 {
1851 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1852 		return (EINVAL);
1853 
1854 	if (type < 0 || type >= VM_CAP_MAX)
1855 		return (EINVAL);
1856 
1857 	return (VMGETCAP(vm->cookie, vcpu, type, retval));
1858 }
1859 
1860 int
1861 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
1862 {
1863 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1864 		return (EINVAL);
1865 
1866 	if (type < 0 || type >= VM_CAP_MAX)
1867 		return (EINVAL);
1868 
1869 	return (VMSETCAP(vm->cookie, vcpu, type, val));
1870 }
1871 
1872 uint64_t *
1873 vm_guest_msrs(struct vm *vm, int cpu)
1874 {
1875 	return (vm->vcpu[cpu].guest_msrs);
1876 }
1877 
1878 struct vlapic *
1879 vm_lapic(struct vm *vm, int cpu)
1880 {
1881 	return (vm->vcpu[cpu].vlapic);
1882 }
1883 
1884 struct vioapic *
1885 vm_ioapic(struct vm *vm)
1886 {
1887 
1888 	return (vm->vioapic);
1889 }
1890 
1891 struct vhpet *
1892 vm_hpet(struct vm *vm)
1893 {
1894 
1895 	return (vm->vhpet);
1896 }
1897 
1898 boolean_t
1899 vmm_is_pptdev(int bus, int slot, int func)
1900 {
1901 	int found, i, n;
1902 	int b, s, f;
1903 	char *val, *cp, *cp2;
1904 
1905 	/*
1906 	 * XXX
1907 	 * The length of an environment variable is limited to 128 bytes which
1908 	 * puts an upper limit on the number of passthru devices that may be
1909 	 * specified using a single environment variable.
1910 	 *
1911 	 * Work around this by scanning multiple environment variable
1912 	 * names instead of a single one - yuck!
1913 	 */
1914 	const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
1915 
1916 	/* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
1917 	found = 0;
1918 	for (i = 0; names[i] != NULL && !found; i++) {
1919 		cp = val = getenv(names[i]);
1920 		while (cp != NULL && *cp != '\0') {
1921 			if ((cp2 = strchr(cp, ' ')) != NULL)
1922 				*cp2 = '\0';
1923 
1924 			n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
1925 			if (n == 3 && bus == b && slot == s && func == f) {
1926 				found = 1;
1927 				break;
1928 			}
1929 
1930 			if (cp2 != NULL)
1931 				*cp2++ = ' ';
1932 
1933 			cp = cp2;
1934 		}
1935 		freeenv(val);
1936 	}
1937 	return (found);
1938 }
1939 
1940 void *
1941 vm_iommu_domain(struct vm *vm)
1942 {
1943 
1944 	return (vm->iommu);
1945 }
1946 
1947 int
1948 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
1949     bool from_idle)
1950 {
1951 	int error;
1952 	struct vcpu *vcpu;
1953 
1954 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1955 		panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
1956 
1957 	vcpu = &vm->vcpu[vcpuid];
1958 
1959 	vcpu_lock(vcpu);
1960 	error = vcpu_set_state_locked(vcpu, newstate, from_idle);
1961 	vcpu_unlock(vcpu);
1962 
1963 	return (error);
1964 }
1965 
1966 enum vcpu_state
1967 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
1968 {
1969 	struct vcpu *vcpu;
1970 	enum vcpu_state state;
1971 
1972 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1973 		panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
1974 
1975 	vcpu = &vm->vcpu[vcpuid];
1976 
1977 	vcpu_lock(vcpu);
1978 	state = vcpu->state;
1979 	if (hostcpu != NULL)
1980 		*hostcpu = vcpu->hostcpu;
1981 	vcpu_unlock(vcpu);
1982 
1983 	return (state);
1984 }
1985 
1986 int
1987 vm_activate_cpu(struct vm *vm, int vcpuid)
1988 {
1989 
1990 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1991 		return (EINVAL);
1992 
1993 	if (CPU_ISSET(vcpuid, &vm->active_cpus))
1994 		return (EBUSY);
1995 
1996 	VCPU_CTR0(vm, vcpuid, "activated");
1997 	CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
1998 	return (0);
1999 }
2000 
2001 cpuset_t
2002 vm_active_cpus(struct vm *vm)
2003 {
2004 
2005 	return (vm->active_cpus);
2006 }
2007 
2008 cpuset_t
2009 vm_suspended_cpus(struct vm *vm)
2010 {
2011 
2012 	return (vm->suspended_cpus);
2013 }
2014 
2015 void *
2016 vcpu_stats(struct vm *vm, int vcpuid)
2017 {
2018 
2019 	return (vm->vcpu[vcpuid].stats);
2020 }
2021 
2022 int
2023 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
2024 {
2025 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2026 		return (EINVAL);
2027 
2028 	*state = vm->vcpu[vcpuid].x2apic_state;
2029 
2030 	return (0);
2031 }
2032 
2033 int
2034 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
2035 {
2036 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2037 		return (EINVAL);
2038 
2039 	if (state >= X2APIC_STATE_LAST)
2040 		return (EINVAL);
2041 
2042 	vm->vcpu[vcpuid].x2apic_state = state;
2043 
2044 	vlapic_set_x2apic_state(vm, vcpuid, state);
2045 
2046 	return (0);
2047 }
2048 
2049 /*
2050  * This function is called to ensure that a vcpu "sees" a pending event
2051  * as soon as possible:
2052  * - If the vcpu thread is sleeping then it is woken up.
2053  * - If the vcpu is running on a different host_cpu then an IPI will be directed
2054  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
2055  */
2056 void
2057 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
2058 {
2059 	int hostcpu;
2060 	struct vcpu *vcpu;
2061 
2062 	vcpu = &vm->vcpu[vcpuid];
2063 
2064 	vcpu_lock(vcpu);
2065 	hostcpu = vcpu->hostcpu;
2066 	if (vcpu->state == VCPU_RUNNING) {
2067 		KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
2068 		if (hostcpu != curcpu) {
2069 			if (lapic_intr) {
2070 				vlapic_post_intr(vcpu->vlapic, hostcpu,
2071 				    vmm_ipinum);
2072 			} else {
2073 				ipi_cpu(hostcpu, vmm_ipinum);
2074 			}
2075 		} else {
2076 			/*
2077 			 * If the 'vcpu' is running on 'curcpu' then it must
2078 			 * be sending a notification to itself (e.g. SELF_IPI).
2079 			 * The pending event will be picked up when the vcpu
2080 			 * transitions back to guest context.
2081 			 */
2082 		}
2083 	} else {
2084 		KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
2085 		    "with hostcpu %d", vcpu->state, hostcpu));
2086 		if (vcpu->state == VCPU_SLEEPING)
2087 			wakeup_one(vcpu);
2088 	}
2089 	vcpu_unlock(vcpu);
2090 }
2091 
2092 struct vmspace *
2093 vm_get_vmspace(struct vm *vm)
2094 {
2095 
2096 	return (vm->vmspace);
2097 }
2098 
2099 int
2100 vm_apicid2vcpuid(struct vm *vm, int apicid)
2101 {
2102 	/*
2103 	 * XXX apic id is assumed to be numerically identical to vcpu id
2104 	 */
2105 	return (apicid);
2106 }
2107 
2108 void
2109 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
2110     vm_rendezvous_func_t func, void *arg)
2111 {
2112 	int i;
2113 
2114 	/*
2115 	 * Enforce that this function is called without any locks
2116 	 */
2117 	WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
2118 	KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
2119 	    ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
2120 
2121 restart:
2122 	mtx_lock(&vm->rendezvous_mtx);
2123 	if (vm->rendezvous_func != NULL) {
2124 		/*
2125 		 * If a rendezvous is already in progress then we need to
2126 		 * call the rendezvous handler in case this 'vcpuid' is one
2127 		 * of the targets of the rendezvous.
2128 		 */
2129 		RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
2130 		mtx_unlock(&vm->rendezvous_mtx);
2131 		vm_handle_rendezvous(vm, vcpuid);
2132 		goto restart;
2133 	}
2134 	KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
2135 	    "rendezvous is still in progress"));
2136 
2137 	RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
2138 	vm->rendezvous_req_cpus = dest;
2139 	CPU_ZERO(&vm->rendezvous_done_cpus);
2140 	vm->rendezvous_arg = arg;
2141 	vm_set_rendezvous_func(vm, func);
2142 	mtx_unlock(&vm->rendezvous_mtx);
2143 
2144 	/*
2145 	 * Wake up any sleeping vcpus and trigger a VM-exit in any running
2146 	 * vcpus so they handle the rendezvous as soon as possible.
2147 	 */
2148 	for (i = 0; i < VM_MAXCPU; i++) {
2149 		if (CPU_ISSET(i, &dest))
2150 			vcpu_notify_event(vm, i, false);
2151 	}
2152 
2153 	vm_handle_rendezvous(vm, vcpuid);
2154 }
2155 
2156 struct vatpic *
2157 vm_atpic(struct vm *vm)
2158 {
2159 	return (vm->vatpic);
2160 }
2161 
2162 struct vatpit *
2163 vm_atpit(struct vm *vm)
2164 {
2165 	return (vm->vatpit);
2166 }
2167 
2168 enum vm_reg_name
2169 vm_segment_name(int seg)
2170 {
2171 	static enum vm_reg_name seg_names[] = {
2172 		VM_REG_GUEST_ES,
2173 		VM_REG_GUEST_CS,
2174 		VM_REG_GUEST_SS,
2175 		VM_REG_GUEST_DS,
2176 		VM_REG_GUEST_FS,
2177 		VM_REG_GUEST_GS
2178 	};
2179 
2180 	KASSERT(seg >= 0 && seg < nitems(seg_names),
2181 	    ("%s: invalid segment encoding %d", __func__, seg));
2182 	return (seg_names[seg]);
2183 }
2184 
2185 
2186 /*
2187  * Return the amount of in-use and wired memory for the VM. Since
2188  * these are global stats, only return the values with for vCPU 0
2189  */
2190 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
2191 VMM_STAT_DECLARE(VMM_MEM_WIRED);
2192 
2193 static void
2194 vm_get_rescnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2195 {
2196 
2197 	if (vcpu == 0) {
2198 		vmm_stat_set(vm, vcpu, VMM_MEM_RESIDENT,
2199 	       	    PAGE_SIZE * vmspace_resident_count(vm->vmspace));
2200 	}
2201 }
2202 
2203 static void
2204 vm_get_wiredcnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2205 {
2206 
2207 	if (vcpu == 0) {
2208 		vmm_stat_set(vm, vcpu, VMM_MEM_WIRED,
2209 	      	    PAGE_SIZE * pmap_wired_count(vmspace_pmap(vm->vmspace)));
2210 	}
2211 }
2212 
2213 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
2214 VMM_STAT_FUNC(VMM_MEM_WIRED, "Wired memory", vm_get_wiredcnt);
2215