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