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