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