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