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