xref: /freebsd/sys/amd64/vmm/vmm.c (revision d22c735e033e47d58878a9c00aa09e90e6e83f06)
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 "vmm_msr.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 struct vcpu {
88 	int		flags;
89 	enum vcpu_state	state;
90 	struct mtx	mtx;
91 	int		hostcpu;	/* host cpuid this vcpu last ran on */
92 	uint64_t	guest_msrs[VMM_MSR_NUM];
93 	struct vlapic	*vlapic;
94 	int		 vcpuid;
95 	struct savefpu	*guestfpu;	/* guest fpu state */
96 	uint64_t	guest_xcr0;
97 	void		*stats;
98 	struct vm_exit	exitinfo;
99 	enum x2apic_state x2apic_state;
100 	int		nmi_pending;
101 	int		extint_pending;
102 	struct vm_exception exception;
103 	int		exception_pending;
104 };
105 
106 #define	vcpu_lock_init(v)	mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
107 #define	vcpu_lock(v)		mtx_lock_spin(&((v)->mtx))
108 #define	vcpu_unlock(v)		mtx_unlock_spin(&((v)->mtx))
109 #define	vcpu_assert_locked(v)	mtx_assert(&((v)->mtx), MA_OWNED)
110 
111 struct mem_seg {
112 	vm_paddr_t	gpa;
113 	size_t		len;
114 	boolean_t	wired;
115 	vm_object_t	object;
116 };
117 #define	VM_MAX_MEMORY_SEGMENTS	2
118 
119 struct vm {
120 	void		*cookie;	/* processor-specific data */
121 	void		*iommu;		/* iommu-specific data */
122 	struct vhpet	*vhpet;		/* virtual HPET */
123 	struct vioapic	*vioapic;	/* virtual ioapic */
124 	struct vatpic	*vatpic;	/* virtual atpic */
125 	struct vatpit	*vatpit;	/* virtual atpit */
126 	struct vmspace	*vmspace;	/* guest's address space */
127 	struct vcpu	vcpu[VM_MAXCPU];
128 	int		num_mem_segs;
129 	struct mem_seg	mem_segs[VM_MAX_MEMORY_SEGMENTS];
130 	char		name[VM_MAX_NAMELEN];
131 
132 	/*
133 	 * Set of active vcpus.
134 	 * An active vcpu is one that has been started implicitly (BSP) or
135 	 * explicitly (AP) by sending it a startup ipi.
136 	 */
137 	volatile cpuset_t active_cpus;
138 
139 	struct mtx	rendezvous_mtx;
140 	cpuset_t	rendezvous_req_cpus;
141 	cpuset_t	rendezvous_done_cpus;
142 	void		*rendezvous_arg;
143 	vm_rendezvous_func_t rendezvous_func;
144 
145 	int		suspend;
146 	volatile cpuset_t suspended_cpus;
147 
148 	volatile cpuset_t halted_cpus;
149 };
150 
151 static int vmm_initialized;
152 
153 static struct vmm_ops *ops;
154 #define	VMM_INIT(num)	(ops != NULL ? (*ops->init)(num) : 0)
155 #define	VMM_CLEANUP()	(ops != NULL ? (*ops->cleanup)() : 0)
156 #define	VMM_RESUME()	(ops != NULL ? (*ops->resume)() : 0)
157 
158 #define	VMINIT(vm, pmap) (ops != NULL ? (*ops->vminit)(vm, pmap): NULL)
159 #define	VMRUN(vmi, vcpu, rip, pmap, rptr, sptr) \
160 	(ops != NULL ? (*ops->vmrun)(vmi, vcpu, rip, pmap, rptr, sptr) : ENXIO)
161 #define	VMCLEANUP(vmi)	(ops != NULL ? (*ops->vmcleanup)(vmi) : NULL)
162 #define	VMSPACE_ALLOC(min, max) \
163 	(ops != NULL ? (*ops->vmspace_alloc)(min, max) : NULL)
164 #define	VMSPACE_FREE(vmspace) \
165 	(ops != NULL ? (*ops->vmspace_free)(vmspace) : ENXIO)
166 #define	VMGETREG(vmi, vcpu, num, retval)		\
167 	(ops != NULL ? (*ops->vmgetreg)(vmi, vcpu, num, retval) : ENXIO)
168 #define	VMSETREG(vmi, vcpu, num, val)		\
169 	(ops != NULL ? (*ops->vmsetreg)(vmi, vcpu, num, val) : ENXIO)
170 #define	VMGETDESC(vmi, vcpu, num, desc)		\
171 	(ops != NULL ? (*ops->vmgetdesc)(vmi, vcpu, num, desc) : ENXIO)
172 #define	VMSETDESC(vmi, vcpu, num, desc)		\
173 	(ops != NULL ? (*ops->vmsetdesc)(vmi, vcpu, num, desc) : ENXIO)
174 #define	VMGETCAP(vmi, vcpu, num, retval)	\
175 	(ops != NULL ? (*ops->vmgetcap)(vmi, vcpu, num, retval) : ENXIO)
176 #define	VMSETCAP(vmi, vcpu, num, val)		\
177 	(ops != NULL ? (*ops->vmsetcap)(vmi, vcpu, num, val) : ENXIO)
178 #define	VLAPIC_INIT(vmi, vcpu)			\
179 	(ops != NULL ? (*ops->vlapic_init)(vmi, vcpu) : NULL)
180 #define	VLAPIC_CLEANUP(vmi, vlapic)		\
181 	(ops != NULL ? (*ops->vlapic_cleanup)(vmi, vlapic) : NULL)
182 
183 #define	fpu_start_emulating()	load_cr0(rcr0() | CR0_TS)
184 #define	fpu_stop_emulating()	clts()
185 
186 static MALLOC_DEFINE(M_VM, "vm", "vm");
187 CTASSERT(VMM_MSR_NUM <= 64);	/* msr_mask can keep track of up to 64 msrs */
188 
189 /* statistics */
190 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
191 
192 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
193 
194 /*
195  * Halt the guest if all vcpus are executing a HLT instruction with
196  * interrupts disabled.
197  */
198 static int halt_detection_enabled = 1;
199 TUNABLE_INT("hw.vmm.halt_detection", &halt_detection_enabled);
200 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
201     &halt_detection_enabled, 0,
202     "Halt VM if all vcpus execute HLT with interrupts disabled");
203 
204 static int vmm_ipinum;
205 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
206     "IPI vector used for vcpu notifications");
207 
208 static void
209 vcpu_cleanup(struct vm *vm, int i)
210 {
211 	struct vcpu *vcpu = &vm->vcpu[i];
212 
213 	VLAPIC_CLEANUP(vm->cookie, vcpu->vlapic);
214 	vmm_stat_free(vcpu->stats);
215 	fpu_save_area_free(vcpu->guestfpu);
216 }
217 
218 static void
219 vcpu_init(struct vm *vm, uint32_t vcpu_id)
220 {
221 	struct vcpu *vcpu;
222 
223 	vcpu = &vm->vcpu[vcpu_id];
224 
225 	vcpu_lock_init(vcpu);
226 	vcpu->hostcpu = NOCPU;
227 	vcpu->vcpuid = vcpu_id;
228 	vcpu->vlapic = VLAPIC_INIT(vm->cookie, vcpu_id);
229 	vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
230 	vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
231 	vcpu->guestfpu = fpu_save_area_alloc();
232 	fpu_save_area_reset(vcpu->guestfpu);
233 	vcpu->stats = vmm_stat_alloc();
234 }
235 
236 struct vm_exit *
237 vm_exitinfo(struct vm *vm, int cpuid)
238 {
239 	struct vcpu *vcpu;
240 
241 	if (cpuid < 0 || cpuid >= VM_MAXCPU)
242 		panic("vm_exitinfo: invalid cpuid %d", cpuid);
243 
244 	vcpu = &vm->vcpu[cpuid];
245 
246 	return (&vcpu->exitinfo);
247 }
248 
249 static void
250 vmm_resume(void)
251 {
252 	VMM_RESUME();
253 }
254 
255 static int
256 vmm_init(void)
257 {
258 	int error;
259 
260 	vmm_host_state_init();
261 
262 	vmm_ipinum = vmm_ipi_alloc();
263 	if (vmm_ipinum == 0)
264 		vmm_ipinum = IPI_AST;
265 
266 	error = vmm_mem_init();
267 	if (error)
268 		return (error);
269 
270 	if (vmm_is_intel())
271 		ops = &vmm_ops_intel;
272 	else if (vmm_is_amd())
273 		ops = &vmm_ops_amd;
274 	else
275 		return (ENXIO);
276 
277 	vmm_msr_init();
278 	vmm_resume_p = vmm_resume;
279 
280 	return (VMM_INIT(vmm_ipinum));
281 }
282 
283 static int
284 vmm_handler(module_t mod, int what, void *arg)
285 {
286 	int error;
287 
288 	switch (what) {
289 	case MOD_LOAD:
290 		vmmdev_init();
291 		if (ppt_avail_devices() > 0)
292 			iommu_init();
293 		error = vmm_init();
294 		if (error == 0)
295 			vmm_initialized = 1;
296 		break;
297 	case MOD_UNLOAD:
298 		error = vmmdev_cleanup();
299 		if (error == 0) {
300 			vmm_resume_p = NULL;
301 			iommu_cleanup();
302 			if (vmm_ipinum != IPI_AST)
303 				vmm_ipi_free(vmm_ipinum);
304 			error = VMM_CLEANUP();
305 			/*
306 			 * Something bad happened - prevent new
307 			 * VMs from being created
308 			 */
309 			if (error)
310 				vmm_initialized = 0;
311 		}
312 		break;
313 	default:
314 		error = 0;
315 		break;
316 	}
317 	return (error);
318 }
319 
320 static moduledata_t vmm_kmod = {
321 	"vmm",
322 	vmm_handler,
323 	NULL
324 };
325 
326 /*
327  * vmm initialization has the following dependencies:
328  *
329  * - iommu initialization must happen after the pci passthru driver has had
330  *   a chance to attach to any passthru devices (after SI_SUB_CONFIGURE).
331  *
332  * - VT-x initialization requires smp_rendezvous() and therefore must happen
333  *   after SMP is fully functional (after SI_SUB_SMP).
334  */
335 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
336 MODULE_VERSION(vmm, 1);
337 
338 int
339 vm_create(const char *name, struct vm **retvm)
340 {
341 	int i;
342 	struct vm *vm;
343 	struct vmspace *vmspace;
344 
345 	/*
346 	 * If vmm.ko could not be successfully initialized then don't attempt
347 	 * to create the virtual machine.
348 	 */
349 	if (!vmm_initialized)
350 		return (ENXIO);
351 
352 	if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
353 		return (EINVAL);
354 
355 	vmspace = VMSPACE_ALLOC(VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS);
356 	if (vmspace == NULL)
357 		return (ENOMEM);
358 
359 	vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
360 	strcpy(vm->name, name);
361 	vm->vmspace = vmspace;
362 	mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
363 	vm->cookie = VMINIT(vm, vmspace_pmap(vmspace));
364 	vm->vioapic = vioapic_init(vm);
365 	vm->vhpet = vhpet_init(vm);
366 	vm->vatpic = vatpic_init(vm);
367 	vm->vatpit = vatpit_init(vm);
368 
369 	for (i = 0; i < VM_MAXCPU; i++) {
370 		vcpu_init(vm, i);
371 		guest_msrs_init(vm, i);
372 	}
373 
374 	*retvm = vm;
375 	return (0);
376 }
377 
378 static void
379 vm_free_mem_seg(struct vm *vm, struct mem_seg *seg)
380 {
381 
382 	if (seg->object != NULL)
383 		vmm_mem_free(vm->vmspace, seg->gpa, seg->len);
384 
385 	bzero(seg, sizeof(*seg));
386 }
387 
388 void
389 vm_destroy(struct vm *vm)
390 {
391 	int i;
392 
393 	ppt_unassign_all(vm);
394 
395 	if (vm->iommu != NULL)
396 		iommu_destroy_domain(vm->iommu);
397 
398 	vatpit_cleanup(vm->vatpit);
399 	vhpet_cleanup(vm->vhpet);
400 	vatpic_cleanup(vm->vatpic);
401 	vioapic_cleanup(vm->vioapic);
402 
403 	for (i = 0; i < vm->num_mem_segs; i++)
404 		vm_free_mem_seg(vm, &vm->mem_segs[i]);
405 
406 	vm->num_mem_segs = 0;
407 
408 	for (i = 0; i < VM_MAXCPU; i++)
409 		vcpu_cleanup(vm, i);
410 
411 	VMSPACE_FREE(vm->vmspace);
412 
413 	VMCLEANUP(vm->cookie);
414 
415 	free(vm, M_VM);
416 }
417 
418 const char *
419 vm_name(struct vm *vm)
420 {
421 	return (vm->name);
422 }
423 
424 int
425 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
426 {
427 	vm_object_t obj;
428 
429 	if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
430 		return (ENOMEM);
431 	else
432 		return (0);
433 }
434 
435 int
436 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
437 {
438 
439 	vmm_mmio_free(vm->vmspace, gpa, len);
440 	return (0);
441 }
442 
443 boolean_t
444 vm_mem_allocated(struct vm *vm, vm_paddr_t gpa)
445 {
446 	int i;
447 	vm_paddr_t gpabase, gpalimit;
448 
449 	for (i = 0; i < vm->num_mem_segs; i++) {
450 		gpabase = vm->mem_segs[i].gpa;
451 		gpalimit = gpabase + vm->mem_segs[i].len;
452 		if (gpa >= gpabase && gpa < gpalimit)
453 			return (TRUE);		/* 'gpa' is regular memory */
454 	}
455 
456 	if (ppt_is_mmio(vm, gpa))
457 		return (TRUE);			/* 'gpa' is pci passthru mmio */
458 
459 	return (FALSE);
460 }
461 
462 int
463 vm_malloc(struct vm *vm, vm_paddr_t gpa, size_t len)
464 {
465 	int available, allocated;
466 	struct mem_seg *seg;
467 	vm_object_t object;
468 	vm_paddr_t g;
469 
470 	if ((gpa & PAGE_MASK) || (len & PAGE_MASK) || len == 0)
471 		return (EINVAL);
472 
473 	available = allocated = 0;
474 	g = gpa;
475 	while (g < gpa + len) {
476 		if (vm_mem_allocated(vm, g))
477 			allocated++;
478 		else
479 			available++;
480 
481 		g += PAGE_SIZE;
482 	}
483 
484 	/*
485 	 * If there are some allocated and some available pages in the address
486 	 * range then it is an error.
487 	 */
488 	if (allocated && available)
489 		return (EINVAL);
490 
491 	/*
492 	 * If the entire address range being requested has already been
493 	 * allocated then there isn't anything more to do.
494 	 */
495 	if (allocated && available == 0)
496 		return (0);
497 
498 	if (vm->num_mem_segs >= VM_MAX_MEMORY_SEGMENTS)
499 		return (E2BIG);
500 
501 	seg = &vm->mem_segs[vm->num_mem_segs];
502 
503 	if ((object = vmm_mem_alloc(vm->vmspace, gpa, len)) == NULL)
504 		return (ENOMEM);
505 
506 	seg->gpa = gpa;
507 	seg->len = len;
508 	seg->object = object;
509 	seg->wired = FALSE;
510 
511 	vm->num_mem_segs++;
512 
513 	return (0);
514 }
515 
516 static void
517 vm_gpa_unwire(struct vm *vm)
518 {
519 	int i, rv;
520 	struct mem_seg *seg;
521 
522 	for (i = 0; i < vm->num_mem_segs; i++) {
523 		seg = &vm->mem_segs[i];
524 		if (!seg->wired)
525 			continue;
526 
527 		rv = vm_map_unwire(&vm->vmspace->vm_map,
528 				   seg->gpa, seg->gpa + seg->len,
529 				   VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
530 		KASSERT(rv == KERN_SUCCESS, ("vm(%s) memory segment "
531 		    "%#lx/%ld could not be unwired: %d",
532 		    vm_name(vm), seg->gpa, seg->len, rv));
533 
534 		seg->wired = FALSE;
535 	}
536 }
537 
538 static int
539 vm_gpa_wire(struct vm *vm)
540 {
541 	int i, rv;
542 	struct mem_seg *seg;
543 
544 	for (i = 0; i < vm->num_mem_segs; i++) {
545 		seg = &vm->mem_segs[i];
546 		if (seg->wired)
547 			continue;
548 
549 		/* XXX rlimits? */
550 		rv = vm_map_wire(&vm->vmspace->vm_map,
551 				 seg->gpa, seg->gpa + seg->len,
552 				 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
553 		if (rv != KERN_SUCCESS)
554 			break;
555 
556 		seg->wired = TRUE;
557 	}
558 
559 	if (i < vm->num_mem_segs) {
560 		/*
561 		 * Undo the wiring before returning an error.
562 		 */
563 		vm_gpa_unwire(vm);
564 		return (EAGAIN);
565 	}
566 
567 	return (0);
568 }
569 
570 static void
571 vm_iommu_modify(struct vm *vm, boolean_t map)
572 {
573 	int i, sz;
574 	vm_paddr_t gpa, hpa;
575 	struct mem_seg *seg;
576 	void *vp, *cookie, *host_domain;
577 
578 	sz = PAGE_SIZE;
579 	host_domain = iommu_host_domain();
580 
581 	for (i = 0; i < vm->num_mem_segs; i++) {
582 		seg = &vm->mem_segs[i];
583 		KASSERT(seg->wired, ("vm(%s) memory segment %#lx/%ld not wired",
584 		    vm_name(vm), seg->gpa, seg->len));
585 
586 		gpa = seg->gpa;
587 		while (gpa < seg->gpa + seg->len) {
588 			vp = vm_gpa_hold(vm, gpa, PAGE_SIZE, VM_PROT_WRITE,
589 					 &cookie);
590 			KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
591 			    vm_name(vm), gpa));
592 
593 			vm_gpa_release(cookie);
594 
595 			hpa = DMAP_TO_PHYS((uintptr_t)vp);
596 			if (map) {
597 				iommu_create_mapping(vm->iommu, gpa, hpa, sz);
598 				iommu_remove_mapping(host_domain, hpa, sz);
599 			} else {
600 				iommu_remove_mapping(vm->iommu, gpa, sz);
601 				iommu_create_mapping(host_domain, hpa, hpa, sz);
602 			}
603 
604 			gpa += PAGE_SIZE;
605 		}
606 	}
607 
608 	/*
609 	 * Invalidate the cached translations associated with the domain
610 	 * from which pages were removed.
611 	 */
612 	if (map)
613 		iommu_invalidate_tlb(host_domain);
614 	else
615 		iommu_invalidate_tlb(vm->iommu);
616 }
617 
618 #define	vm_iommu_unmap(vm)	vm_iommu_modify((vm), FALSE)
619 #define	vm_iommu_map(vm)	vm_iommu_modify((vm), TRUE)
620 
621 int
622 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
623 {
624 	int error;
625 
626 	error = ppt_unassign_device(vm, bus, slot, func);
627 	if (error)
628 		return (error);
629 
630 	if (ppt_assigned_devices(vm) == 0) {
631 		vm_iommu_unmap(vm);
632 		vm_gpa_unwire(vm);
633 	}
634 	return (0);
635 }
636 
637 int
638 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
639 {
640 	int error;
641 	vm_paddr_t maxaddr;
642 
643 	/*
644 	 * Virtual machines with pci passthru devices get special treatment:
645 	 * - the guest physical memory is wired
646 	 * - the iommu is programmed to do the 'gpa' to 'hpa' translation
647 	 *
648 	 * We need to do this before the first pci passthru device is attached.
649 	 */
650 	if (ppt_assigned_devices(vm) == 0) {
651 		KASSERT(vm->iommu == NULL,
652 		    ("vm_assign_pptdev: iommu must be NULL"));
653 		maxaddr = vmm_mem_maxaddr();
654 		vm->iommu = iommu_create_domain(maxaddr);
655 
656 		error = vm_gpa_wire(vm);
657 		if (error)
658 			return (error);
659 
660 		vm_iommu_map(vm);
661 	}
662 
663 	error = ppt_assign_device(vm, bus, slot, func);
664 	return (error);
665 }
666 
667 void *
668 vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
669 	    void **cookie)
670 {
671 	int count, pageoff;
672 	vm_page_t m;
673 
674 	pageoff = gpa & PAGE_MASK;
675 	if (len > PAGE_SIZE - pageoff)
676 		panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
677 
678 	count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
679 	    trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
680 
681 	if (count == 1) {
682 		*cookie = m;
683 		return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
684 	} else {
685 		*cookie = NULL;
686 		return (NULL);
687 	}
688 }
689 
690 void
691 vm_gpa_release(void *cookie)
692 {
693 	vm_page_t m = cookie;
694 
695 	vm_page_lock(m);
696 	vm_page_unhold(m);
697 	vm_page_unlock(m);
698 }
699 
700 int
701 vm_gpabase2memseg(struct vm *vm, vm_paddr_t gpabase,
702 		  struct vm_memory_segment *seg)
703 {
704 	int i;
705 
706 	for (i = 0; i < vm->num_mem_segs; i++) {
707 		if (gpabase == vm->mem_segs[i].gpa) {
708 			seg->gpa = vm->mem_segs[i].gpa;
709 			seg->len = vm->mem_segs[i].len;
710 			seg->wired = vm->mem_segs[i].wired;
711 			return (0);
712 		}
713 	}
714 	return (-1);
715 }
716 
717 int
718 vm_get_memobj(struct vm *vm, vm_paddr_t gpa, size_t len,
719 	      vm_offset_t *offset, struct vm_object **object)
720 {
721 	int i;
722 	size_t seg_len;
723 	vm_paddr_t seg_gpa;
724 	vm_object_t seg_obj;
725 
726 	for (i = 0; i < vm->num_mem_segs; i++) {
727 		if ((seg_obj = vm->mem_segs[i].object) == NULL)
728 			continue;
729 
730 		seg_gpa = vm->mem_segs[i].gpa;
731 		seg_len = vm->mem_segs[i].len;
732 
733 		if (gpa >= seg_gpa && gpa < seg_gpa + seg_len) {
734 			*offset = gpa - seg_gpa;
735 			*object = seg_obj;
736 			vm_object_reference(seg_obj);
737 			return (0);
738 		}
739 	}
740 
741 	return (EINVAL);
742 }
743 
744 int
745 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
746 {
747 
748 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
749 		return (EINVAL);
750 
751 	if (reg >= VM_REG_LAST)
752 		return (EINVAL);
753 
754 	return (VMGETREG(vm->cookie, vcpu, reg, retval));
755 }
756 
757 int
758 vm_set_register(struct vm *vm, int vcpu, int reg, uint64_t val)
759 {
760 
761 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
762 		return (EINVAL);
763 
764 	if (reg >= VM_REG_LAST)
765 		return (EINVAL);
766 
767 	return (VMSETREG(vm->cookie, vcpu, reg, val));
768 }
769 
770 static boolean_t
771 is_descriptor_table(int reg)
772 {
773 
774 	switch (reg) {
775 	case VM_REG_GUEST_IDTR:
776 	case VM_REG_GUEST_GDTR:
777 		return (TRUE);
778 	default:
779 		return (FALSE);
780 	}
781 }
782 
783 static boolean_t
784 is_segment_register(int reg)
785 {
786 
787 	switch (reg) {
788 	case VM_REG_GUEST_ES:
789 	case VM_REG_GUEST_CS:
790 	case VM_REG_GUEST_SS:
791 	case VM_REG_GUEST_DS:
792 	case VM_REG_GUEST_FS:
793 	case VM_REG_GUEST_GS:
794 	case VM_REG_GUEST_TR:
795 	case VM_REG_GUEST_LDTR:
796 		return (TRUE);
797 	default:
798 		return (FALSE);
799 	}
800 }
801 
802 int
803 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
804 		struct seg_desc *desc)
805 {
806 
807 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
808 		return (EINVAL);
809 
810 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
811 		return (EINVAL);
812 
813 	return (VMGETDESC(vm->cookie, vcpu, reg, desc));
814 }
815 
816 int
817 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
818 		struct seg_desc *desc)
819 {
820 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
821 		return (EINVAL);
822 
823 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
824 		return (EINVAL);
825 
826 	return (VMSETDESC(vm->cookie, vcpu, reg, desc));
827 }
828 
829 static void
830 restore_guest_fpustate(struct vcpu *vcpu)
831 {
832 
833 	/* flush host state to the pcb */
834 	fpuexit(curthread);
835 
836 	/* restore guest FPU state */
837 	fpu_stop_emulating();
838 	fpurestore(vcpu->guestfpu);
839 
840 	/* restore guest XCR0 if XSAVE is enabled in the host */
841 	if (rcr4() & CR4_XSAVE)
842 		load_xcr(0, vcpu->guest_xcr0);
843 
844 	/*
845 	 * The FPU is now "dirty" with the guest's state so turn on emulation
846 	 * to trap any access to the FPU by the host.
847 	 */
848 	fpu_start_emulating();
849 }
850 
851 static void
852 save_guest_fpustate(struct vcpu *vcpu)
853 {
854 
855 	if ((rcr0() & CR0_TS) == 0)
856 		panic("fpu emulation not enabled in host!");
857 
858 	/* save guest XCR0 and restore host XCR0 */
859 	if (rcr4() & CR4_XSAVE) {
860 		vcpu->guest_xcr0 = rxcr(0);
861 		load_xcr(0, vmm_get_host_xcr0());
862 	}
863 
864 	/* save guest FPU state */
865 	fpu_stop_emulating();
866 	fpusave(vcpu->guestfpu);
867 	fpu_start_emulating();
868 }
869 
870 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
871 
872 static int
873 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
874     bool from_idle)
875 {
876 	int error;
877 
878 	vcpu_assert_locked(vcpu);
879 
880 	/*
881 	 * State transitions from the vmmdev_ioctl() must always begin from
882 	 * the VCPU_IDLE state. This guarantees that there is only a single
883 	 * ioctl() operating on a vcpu at any point.
884 	 */
885 	if (from_idle) {
886 		while (vcpu->state != VCPU_IDLE)
887 			msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
888 	} else {
889 		KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
890 		    "vcpu idle state"));
891 	}
892 
893 	if (vcpu->state == VCPU_RUNNING) {
894 		KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
895 		    "mismatch for running vcpu", curcpu, vcpu->hostcpu));
896 	} else {
897 		KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
898 		    "vcpu that is not running", vcpu->hostcpu));
899 	}
900 
901 	/*
902 	 * The following state transitions are allowed:
903 	 * IDLE -> FROZEN -> IDLE
904 	 * FROZEN -> RUNNING -> FROZEN
905 	 * FROZEN -> SLEEPING -> FROZEN
906 	 */
907 	switch (vcpu->state) {
908 	case VCPU_IDLE:
909 	case VCPU_RUNNING:
910 	case VCPU_SLEEPING:
911 		error = (newstate != VCPU_FROZEN);
912 		break;
913 	case VCPU_FROZEN:
914 		error = (newstate == VCPU_FROZEN);
915 		break;
916 	default:
917 		error = 1;
918 		break;
919 	}
920 
921 	if (error)
922 		return (EBUSY);
923 
924 	vcpu->state = newstate;
925 	if (newstate == VCPU_RUNNING)
926 		vcpu->hostcpu = curcpu;
927 	else
928 		vcpu->hostcpu = NOCPU;
929 
930 	if (newstate == VCPU_IDLE)
931 		wakeup(&vcpu->state);
932 
933 	return (0);
934 }
935 
936 static void
937 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
938 {
939 	int error;
940 
941 	if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
942 		panic("Error %d setting state to %d\n", error, newstate);
943 }
944 
945 static void
946 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
947 {
948 	int error;
949 
950 	if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
951 		panic("Error %d setting state to %d", error, newstate);
952 }
953 
954 static void
955 vm_set_rendezvous_func(struct vm *vm, vm_rendezvous_func_t func)
956 {
957 
958 	KASSERT(mtx_owned(&vm->rendezvous_mtx), ("rendezvous_mtx not locked"));
959 
960 	/*
961 	 * Update 'rendezvous_func' and execute a write memory barrier to
962 	 * ensure that it is visible across all host cpus. This is not needed
963 	 * for correctness but it does ensure that all the vcpus will notice
964 	 * that the rendezvous is requested immediately.
965 	 */
966 	vm->rendezvous_func = func;
967 	wmb();
968 }
969 
970 #define	RENDEZVOUS_CTR0(vm, vcpuid, fmt)				\
971 	do {								\
972 		if (vcpuid >= 0)					\
973 			VCPU_CTR0(vm, vcpuid, fmt);			\
974 		else							\
975 			VM_CTR0(vm, fmt);				\
976 	} while (0)
977 
978 static void
979 vm_handle_rendezvous(struct vm *vm, int vcpuid)
980 {
981 
982 	KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
983 	    ("vm_handle_rendezvous: invalid vcpuid %d", vcpuid));
984 
985 	mtx_lock(&vm->rendezvous_mtx);
986 	while (vm->rendezvous_func != NULL) {
987 		/* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
988 		CPU_AND(&vm->rendezvous_req_cpus, &vm->active_cpus);
989 
990 		if (vcpuid != -1 &&
991 		    CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
992 		    !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
993 			VCPU_CTR0(vm, vcpuid, "Calling rendezvous func");
994 			(*vm->rendezvous_func)(vm, vcpuid, vm->rendezvous_arg);
995 			CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
996 		}
997 		if (CPU_CMP(&vm->rendezvous_req_cpus,
998 		    &vm->rendezvous_done_cpus) == 0) {
999 			VCPU_CTR0(vm, vcpuid, "Rendezvous completed");
1000 			vm_set_rendezvous_func(vm, NULL);
1001 			wakeup(&vm->rendezvous_func);
1002 			break;
1003 		}
1004 		RENDEZVOUS_CTR0(vm, vcpuid, "Wait for rendezvous completion");
1005 		mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1006 		    "vmrndv", 0);
1007 	}
1008 	mtx_unlock(&vm->rendezvous_mtx);
1009 }
1010 
1011 /*
1012  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1013  */
1014 static int
1015 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled, bool *retu)
1016 {
1017 	struct vcpu *vcpu;
1018 	const char *wmesg;
1019 	int t, vcpu_halted, vm_halted;
1020 
1021 	KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1022 
1023 	vcpu = &vm->vcpu[vcpuid];
1024 	vcpu_halted = 0;
1025 	vm_halted = 0;
1026 
1027 	vcpu_lock(vcpu);
1028 	while (1) {
1029 		/*
1030 		 * Do a final check for pending NMI or interrupts before
1031 		 * really putting this thread to sleep. Also check for
1032 		 * software events that would cause this vcpu to wakeup.
1033 		 *
1034 		 * These interrupts/events could have happened after the
1035 		 * vcpu returned from VMRUN() and before it acquired the
1036 		 * vcpu lock above.
1037 		 */
1038 		if (vm->rendezvous_func != NULL || vm->suspend)
1039 			break;
1040 		if (vm_nmi_pending(vm, vcpuid))
1041 			break;
1042 		if (!intr_disabled) {
1043 			if (vm_extint_pending(vm, vcpuid) ||
1044 			    vlapic_pending_intr(vcpu->vlapic, NULL)) {
1045 				break;
1046 			}
1047 		}
1048 
1049 		/*
1050 		 * Some Linux guests implement "halt" by having all vcpus
1051 		 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1052 		 * track of the vcpus that have entered this state. When all
1053 		 * vcpus enter the halted state the virtual machine is halted.
1054 		 */
1055 		if (intr_disabled) {
1056 			wmesg = "vmhalt";
1057 			VCPU_CTR0(vm, vcpuid, "Halted");
1058 			if (!vcpu_halted && halt_detection_enabled) {
1059 				vcpu_halted = 1;
1060 				CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1061 			}
1062 			if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1063 				vm_halted = 1;
1064 				break;
1065 			}
1066 		} else {
1067 			wmesg = "vmidle";
1068 		}
1069 
1070 		t = ticks;
1071 		vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1072 		msleep_spin(vcpu, &vcpu->mtx, wmesg, 0);
1073 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1074 		vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1075 	}
1076 
1077 	if (vcpu_halted)
1078 		CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1079 
1080 	vcpu_unlock(vcpu);
1081 
1082 	if (vm_halted)
1083 		vm_suspend(vm, VM_SUSPEND_HALT);
1084 
1085 	return (0);
1086 }
1087 
1088 static int
1089 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1090 {
1091 	int rv, ftype;
1092 	struct vm_map *map;
1093 	struct vcpu *vcpu;
1094 	struct vm_exit *vme;
1095 
1096 	vcpu = &vm->vcpu[vcpuid];
1097 	vme = &vcpu->exitinfo;
1098 
1099 	ftype = vme->u.paging.fault_type;
1100 	KASSERT(ftype == VM_PROT_READ ||
1101 	    ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1102 	    ("vm_handle_paging: invalid fault_type %d", ftype));
1103 
1104 	if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1105 		rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1106 		    vme->u.paging.gpa, ftype);
1107 		if (rv == 0)
1108 			goto done;
1109 	}
1110 
1111 	map = &vm->vmspace->vm_map;
1112 	rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
1113 
1114 	VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1115 	    "ftype = %d", rv, vme->u.paging.gpa, ftype);
1116 
1117 	if (rv != KERN_SUCCESS)
1118 		return (EFAULT);
1119 done:
1120 	/* restart execution at the faulting instruction */
1121 	vme->inst_length = 0;
1122 
1123 	return (0);
1124 }
1125 
1126 static int
1127 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1128 {
1129 	struct vie *vie;
1130 	struct vcpu *vcpu;
1131 	struct vm_exit *vme;
1132 	uint64_t gla, gpa;
1133 	struct vm_guest_paging *paging;
1134 	mem_region_read_t mread;
1135 	mem_region_write_t mwrite;
1136 	int error;
1137 
1138 	vcpu = &vm->vcpu[vcpuid];
1139 	vme = &vcpu->exitinfo;
1140 
1141 	gla = vme->u.inst_emul.gla;
1142 	gpa = vme->u.inst_emul.gpa;
1143 	vie = &vme->u.inst_emul.vie;
1144 	paging = &vme->u.inst_emul.paging;
1145 
1146 	vie_init(vie);
1147 
1148 	/* Fetch, decode and emulate the faulting instruction */
1149 	error = vmm_fetch_instruction(vm, vcpuid, paging, vme->rip,
1150 	    vme->inst_length, vie);
1151 	if (error == 1)
1152 		return (0);		/* Resume guest to handle page fault */
1153 	else if (error == -1)
1154 		return (EFAULT);
1155 	else if (error != 0)
1156 		panic("%s: vmm_fetch_instruction error %d", __func__, error);
1157 
1158 	if (vmm_decode_instruction(vm, vcpuid, gla, paging->cpu_mode, vie) != 0)
1159 		return (EFAULT);
1160 
1161 	/* return to userland unless this is an in-kernel emulated device */
1162 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1163 		mread = lapic_mmio_read;
1164 		mwrite = lapic_mmio_write;
1165 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1166 		mread = vioapic_mmio_read;
1167 		mwrite = vioapic_mmio_write;
1168 	} else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1169 		mread = vhpet_mmio_read;
1170 		mwrite = vhpet_mmio_write;
1171 	} else {
1172 		*retu = true;
1173 		return (0);
1174 	}
1175 
1176 	error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, mread, mwrite,
1177 	    retu);
1178 
1179 	return (error);
1180 }
1181 
1182 static int
1183 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1184 {
1185 	int i, done;
1186 	struct vcpu *vcpu;
1187 
1188 	done = 0;
1189 	vcpu = &vm->vcpu[vcpuid];
1190 
1191 	CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1192 
1193 	/*
1194 	 * Wait until all 'active_cpus' have suspended themselves.
1195 	 *
1196 	 * Since a VM may be suspended at any time including when one or
1197 	 * more vcpus are doing a rendezvous we need to call the rendezvous
1198 	 * handler while we are waiting to prevent a deadlock.
1199 	 */
1200 	vcpu_lock(vcpu);
1201 	while (1) {
1202 		if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1203 			VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1204 			break;
1205 		}
1206 
1207 		if (vm->rendezvous_func == NULL) {
1208 			VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1209 			vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1210 			msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1211 			vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1212 		} else {
1213 			VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1214 			vcpu_unlock(vcpu);
1215 			vm_handle_rendezvous(vm, vcpuid);
1216 			vcpu_lock(vcpu);
1217 		}
1218 	}
1219 	vcpu_unlock(vcpu);
1220 
1221 	/*
1222 	 * Wakeup the other sleeping vcpus and return to userspace.
1223 	 */
1224 	for (i = 0; i < VM_MAXCPU; i++) {
1225 		if (CPU_ISSET(i, &vm->suspended_cpus)) {
1226 			vcpu_notify_event(vm, i, false);
1227 		}
1228 	}
1229 
1230 	*retu = true;
1231 	return (0);
1232 }
1233 
1234 int
1235 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1236 {
1237 	int i;
1238 
1239 	if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1240 		return (EINVAL);
1241 
1242 	if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1243 		VM_CTR2(vm, "virtual machine already suspended %d/%d",
1244 		    vm->suspend, how);
1245 		return (EALREADY);
1246 	}
1247 
1248 	VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1249 
1250 	/*
1251 	 * Notify all active vcpus that they are now suspended.
1252 	 */
1253 	for (i = 0; i < VM_MAXCPU; i++) {
1254 		if (CPU_ISSET(i, &vm->active_cpus))
1255 			vcpu_notify_event(vm, i, false);
1256 	}
1257 
1258 	return (0);
1259 }
1260 
1261 void
1262 vm_exit_suspended(struct vm *vm, int vcpuid, uint64_t rip)
1263 {
1264 	struct vm_exit *vmexit;
1265 
1266 	KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1267 	    ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1268 
1269 	vmexit = vm_exitinfo(vm, vcpuid);
1270 	vmexit->rip = rip;
1271 	vmexit->inst_length = 0;
1272 	vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1273 	vmexit->u.suspended.how = vm->suspend;
1274 }
1275 
1276 int
1277 vm_run(struct vm *vm, struct vm_run *vmrun)
1278 {
1279 	int error, vcpuid;
1280 	struct vcpu *vcpu;
1281 	struct pcb *pcb;
1282 	uint64_t tscval, rip;
1283 	struct vm_exit *vme;
1284 	bool retu, intr_disabled;
1285 	pmap_t pmap;
1286 	void *rptr, *sptr;
1287 
1288 	vcpuid = vmrun->cpuid;
1289 
1290 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1291 		return (EINVAL);
1292 
1293 	if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1294 		return (EINVAL);
1295 
1296 	if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1297 		return (EINVAL);
1298 
1299 	rptr = &vm->rendezvous_func;
1300 	sptr = &vm->suspend;
1301 	pmap = vmspace_pmap(vm->vmspace);
1302 	vcpu = &vm->vcpu[vcpuid];
1303 	vme = &vcpu->exitinfo;
1304 	rip = vmrun->rip;
1305 restart:
1306 	critical_enter();
1307 
1308 	KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1309 	    ("vm_run: absurd pm_active"));
1310 
1311 	tscval = rdtsc();
1312 
1313 	pcb = PCPU_GET(curpcb);
1314 	set_pcb_flags(pcb, PCB_FULL_IRET);
1315 
1316 	restore_guest_msrs(vm, vcpuid);
1317 	restore_guest_fpustate(vcpu);
1318 
1319 	vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1320 	error = VMRUN(vm->cookie, vcpuid, rip, pmap, rptr, sptr);
1321 	vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1322 
1323 	save_guest_fpustate(vcpu);
1324 	restore_host_msrs(vm, vcpuid);
1325 
1326 	vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1327 
1328 	critical_exit();
1329 
1330 	if (error == 0) {
1331 		retu = false;
1332 		switch (vme->exitcode) {
1333 		case VM_EXITCODE_SUSPENDED:
1334 			error = vm_handle_suspend(vm, vcpuid, &retu);
1335 			break;
1336 		case VM_EXITCODE_IOAPIC_EOI:
1337 			vioapic_process_eoi(vm, vcpuid,
1338 			    vme->u.ioapic_eoi.vector);
1339 			break;
1340 		case VM_EXITCODE_RENDEZVOUS:
1341 			vm_handle_rendezvous(vm, vcpuid);
1342 			error = 0;
1343 			break;
1344 		case VM_EXITCODE_HLT:
1345 			intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1346 			error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1347 			break;
1348 		case VM_EXITCODE_PAGING:
1349 			error = vm_handle_paging(vm, vcpuid, &retu);
1350 			break;
1351 		case VM_EXITCODE_INST_EMUL:
1352 			error = vm_handle_inst_emul(vm, vcpuid, &retu);
1353 			break;
1354 		case VM_EXITCODE_INOUT:
1355 		case VM_EXITCODE_INOUT_STR:
1356 			error = vm_handle_inout(vm, vcpuid, vme, &retu);
1357 			break;
1358 		default:
1359 			retu = true;	/* handled in userland */
1360 			break;
1361 		}
1362 	}
1363 
1364 	if (error == 0 && retu == false) {
1365 		rip = vme->rip + vme->inst_length;
1366 		goto restart;
1367 	}
1368 
1369 	/* copy the exit information */
1370 	bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1371 	return (error);
1372 }
1373 
1374 int
1375 vm_inject_exception(struct vm *vm, int vcpuid, struct vm_exception *exception)
1376 {
1377 	struct vcpu *vcpu;
1378 
1379 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1380 		return (EINVAL);
1381 
1382 	if (exception->vector < 0 || exception->vector >= 32)
1383 		return (EINVAL);
1384 
1385 	vcpu = &vm->vcpu[vcpuid];
1386 
1387 	if (vcpu->exception_pending) {
1388 		VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
1389 		    "pending exception %d", exception->vector,
1390 		    vcpu->exception.vector);
1391 		return (EBUSY);
1392 	}
1393 
1394 	vcpu->exception_pending = 1;
1395 	vcpu->exception = *exception;
1396 	VCPU_CTR1(vm, vcpuid, "Exception %d pending", exception->vector);
1397 	return (0);
1398 }
1399 
1400 int
1401 vm_exception_pending(struct vm *vm, int vcpuid, struct vm_exception *exception)
1402 {
1403 	struct vcpu *vcpu;
1404 	int pending;
1405 
1406 	KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU, ("invalid vcpu %d", vcpuid));
1407 
1408 	vcpu = &vm->vcpu[vcpuid];
1409 	pending = vcpu->exception_pending;
1410 	if (pending) {
1411 		vcpu->exception_pending = 0;
1412 		*exception = vcpu->exception;
1413 		VCPU_CTR1(vm, vcpuid, "Exception %d delivered",
1414 		    exception->vector);
1415 	}
1416 	return (pending);
1417 }
1418 
1419 static void
1420 vm_inject_fault(struct vm *vm, int vcpuid, struct vm_exception *exception)
1421 {
1422 	struct vm_exit *vmexit;
1423 	int error;
1424 
1425 	error = vm_inject_exception(vm, vcpuid, exception);
1426 	KASSERT(error == 0, ("vm_inject_exception error %d", error));
1427 
1428 	/*
1429 	 * A fault-like exception allows the instruction to be restarted
1430 	 * after the exception handler returns.
1431 	 *
1432 	 * By setting the inst_length to 0 we ensure that the instruction
1433 	 * pointer remains at the faulting instruction.
1434 	 */
1435 	vmexit = vm_exitinfo(vm, vcpuid);
1436 	vmexit->inst_length = 0;
1437 }
1438 
1439 void
1440 vm_inject_pf(struct vm *vm, int vcpuid, int error_code, uint64_t cr2)
1441 {
1442 	struct vm_exception pf = {
1443 		.vector = IDT_PF,
1444 		.error_code_valid = 1,
1445 		.error_code = error_code
1446 	};
1447 	int error;
1448 
1449 	VCPU_CTR2(vm, vcpuid, "Injecting page fault: error_code %#x, cr2 %#lx",
1450 	    error_code, cr2);
1451 
1452 	error = vm_set_register(vm, vcpuid, VM_REG_GUEST_CR2, cr2);
1453 	KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
1454 
1455 	vm_inject_fault(vm, vcpuid, &pf);
1456 }
1457 
1458 void
1459 vm_inject_gp(struct vm *vm, int vcpuid)
1460 {
1461 	struct vm_exception gpf = {
1462 		.vector = IDT_GP,
1463 		.error_code_valid = 1,
1464 		.error_code = 0
1465 	};
1466 
1467 	vm_inject_fault(vm, vcpuid, &gpf);
1468 }
1469 
1470 void
1471 vm_inject_ud(struct vm *vm, int vcpuid)
1472 {
1473 	struct vm_exception udf = {
1474 		.vector = IDT_UD,
1475 		.error_code_valid = 0
1476 	};
1477 
1478 	vm_inject_fault(vm, vcpuid, &udf);
1479 }
1480 
1481 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1482 
1483 int
1484 vm_inject_nmi(struct vm *vm, int vcpuid)
1485 {
1486 	struct vcpu *vcpu;
1487 
1488 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1489 		return (EINVAL);
1490 
1491 	vcpu = &vm->vcpu[vcpuid];
1492 
1493 	vcpu->nmi_pending = 1;
1494 	vcpu_notify_event(vm, vcpuid, false);
1495 	return (0);
1496 }
1497 
1498 int
1499 vm_nmi_pending(struct vm *vm, int vcpuid)
1500 {
1501 	struct vcpu *vcpu;
1502 
1503 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1504 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1505 
1506 	vcpu = &vm->vcpu[vcpuid];
1507 
1508 	return (vcpu->nmi_pending);
1509 }
1510 
1511 void
1512 vm_nmi_clear(struct vm *vm, int vcpuid)
1513 {
1514 	struct vcpu *vcpu;
1515 
1516 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1517 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1518 
1519 	vcpu = &vm->vcpu[vcpuid];
1520 
1521 	if (vcpu->nmi_pending == 0)
1522 		panic("vm_nmi_clear: inconsistent nmi_pending state");
1523 
1524 	vcpu->nmi_pending = 0;
1525 	vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1526 }
1527 
1528 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
1529 
1530 int
1531 vm_inject_extint(struct vm *vm, int vcpuid)
1532 {
1533 	struct vcpu *vcpu;
1534 
1535 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1536 		return (EINVAL);
1537 
1538 	vcpu = &vm->vcpu[vcpuid];
1539 
1540 	vcpu->extint_pending = 1;
1541 	vcpu_notify_event(vm, vcpuid, false);
1542 	return (0);
1543 }
1544 
1545 int
1546 vm_extint_pending(struct vm *vm, int vcpuid)
1547 {
1548 	struct vcpu *vcpu;
1549 
1550 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1551 		panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1552 
1553 	vcpu = &vm->vcpu[vcpuid];
1554 
1555 	return (vcpu->extint_pending);
1556 }
1557 
1558 void
1559 vm_extint_clear(struct vm *vm, int vcpuid)
1560 {
1561 	struct vcpu *vcpu;
1562 
1563 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1564 		panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1565 
1566 	vcpu = &vm->vcpu[vcpuid];
1567 
1568 	if (vcpu->extint_pending == 0)
1569 		panic("vm_extint_clear: inconsistent extint_pending state");
1570 
1571 	vcpu->extint_pending = 0;
1572 	vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
1573 }
1574 
1575 int
1576 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
1577 {
1578 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1579 		return (EINVAL);
1580 
1581 	if (type < 0 || type >= VM_CAP_MAX)
1582 		return (EINVAL);
1583 
1584 	return (VMGETCAP(vm->cookie, vcpu, type, retval));
1585 }
1586 
1587 int
1588 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
1589 {
1590 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1591 		return (EINVAL);
1592 
1593 	if (type < 0 || type >= VM_CAP_MAX)
1594 		return (EINVAL);
1595 
1596 	return (VMSETCAP(vm->cookie, vcpu, type, val));
1597 }
1598 
1599 uint64_t *
1600 vm_guest_msrs(struct vm *vm, int cpu)
1601 {
1602 	return (vm->vcpu[cpu].guest_msrs);
1603 }
1604 
1605 struct vlapic *
1606 vm_lapic(struct vm *vm, int cpu)
1607 {
1608 	return (vm->vcpu[cpu].vlapic);
1609 }
1610 
1611 struct vioapic *
1612 vm_ioapic(struct vm *vm)
1613 {
1614 
1615 	return (vm->vioapic);
1616 }
1617 
1618 struct vhpet *
1619 vm_hpet(struct vm *vm)
1620 {
1621 
1622 	return (vm->vhpet);
1623 }
1624 
1625 boolean_t
1626 vmm_is_pptdev(int bus, int slot, int func)
1627 {
1628 	int found, i, n;
1629 	int b, s, f;
1630 	char *val, *cp, *cp2;
1631 
1632 	/*
1633 	 * XXX
1634 	 * The length of an environment variable is limited to 128 bytes which
1635 	 * puts an upper limit on the number of passthru devices that may be
1636 	 * specified using a single environment variable.
1637 	 *
1638 	 * Work around this by scanning multiple environment variable
1639 	 * names instead of a single one - yuck!
1640 	 */
1641 	const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
1642 
1643 	/* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
1644 	found = 0;
1645 	for (i = 0; names[i] != NULL && !found; i++) {
1646 		cp = val = getenv(names[i]);
1647 		while (cp != NULL && *cp != '\0') {
1648 			if ((cp2 = strchr(cp, ' ')) != NULL)
1649 				*cp2 = '\0';
1650 
1651 			n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
1652 			if (n == 3 && bus == b && slot == s && func == f) {
1653 				found = 1;
1654 				break;
1655 			}
1656 
1657 			if (cp2 != NULL)
1658 				*cp2++ = ' ';
1659 
1660 			cp = cp2;
1661 		}
1662 		freeenv(val);
1663 	}
1664 	return (found);
1665 }
1666 
1667 void *
1668 vm_iommu_domain(struct vm *vm)
1669 {
1670 
1671 	return (vm->iommu);
1672 }
1673 
1674 int
1675 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
1676     bool from_idle)
1677 {
1678 	int error;
1679 	struct vcpu *vcpu;
1680 
1681 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1682 		panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
1683 
1684 	vcpu = &vm->vcpu[vcpuid];
1685 
1686 	vcpu_lock(vcpu);
1687 	error = vcpu_set_state_locked(vcpu, newstate, from_idle);
1688 	vcpu_unlock(vcpu);
1689 
1690 	return (error);
1691 }
1692 
1693 enum vcpu_state
1694 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
1695 {
1696 	struct vcpu *vcpu;
1697 	enum vcpu_state state;
1698 
1699 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1700 		panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
1701 
1702 	vcpu = &vm->vcpu[vcpuid];
1703 
1704 	vcpu_lock(vcpu);
1705 	state = vcpu->state;
1706 	if (hostcpu != NULL)
1707 		*hostcpu = vcpu->hostcpu;
1708 	vcpu_unlock(vcpu);
1709 
1710 	return (state);
1711 }
1712 
1713 int
1714 vm_activate_cpu(struct vm *vm, int vcpuid)
1715 {
1716 
1717 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1718 		return (EINVAL);
1719 
1720 	if (CPU_ISSET(vcpuid, &vm->active_cpus))
1721 		return (EBUSY);
1722 
1723 	VCPU_CTR0(vm, vcpuid, "activated");
1724 	CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
1725 	return (0);
1726 }
1727 
1728 cpuset_t
1729 vm_active_cpus(struct vm *vm)
1730 {
1731 
1732 	return (vm->active_cpus);
1733 }
1734 
1735 cpuset_t
1736 vm_suspended_cpus(struct vm *vm)
1737 {
1738 
1739 	return (vm->suspended_cpus);
1740 }
1741 
1742 void *
1743 vcpu_stats(struct vm *vm, int vcpuid)
1744 {
1745 
1746 	return (vm->vcpu[vcpuid].stats);
1747 }
1748 
1749 int
1750 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
1751 {
1752 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1753 		return (EINVAL);
1754 
1755 	*state = vm->vcpu[vcpuid].x2apic_state;
1756 
1757 	return (0);
1758 }
1759 
1760 int
1761 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
1762 {
1763 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1764 		return (EINVAL);
1765 
1766 	if (state >= X2APIC_STATE_LAST)
1767 		return (EINVAL);
1768 
1769 	vm->vcpu[vcpuid].x2apic_state = state;
1770 
1771 	vlapic_set_x2apic_state(vm, vcpuid, state);
1772 
1773 	return (0);
1774 }
1775 
1776 /*
1777  * This function is called to ensure that a vcpu "sees" a pending event
1778  * as soon as possible:
1779  * - If the vcpu thread is sleeping then it is woken up.
1780  * - If the vcpu is running on a different host_cpu then an IPI will be directed
1781  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
1782  */
1783 void
1784 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
1785 {
1786 	int hostcpu;
1787 	struct vcpu *vcpu;
1788 
1789 	vcpu = &vm->vcpu[vcpuid];
1790 
1791 	vcpu_lock(vcpu);
1792 	hostcpu = vcpu->hostcpu;
1793 	if (vcpu->state == VCPU_RUNNING) {
1794 		KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
1795 		if (hostcpu != curcpu) {
1796 			if (lapic_intr) {
1797 				vlapic_post_intr(vcpu->vlapic, hostcpu,
1798 				    vmm_ipinum);
1799 			} else {
1800 				ipi_cpu(hostcpu, vmm_ipinum);
1801 			}
1802 		} else {
1803 			/*
1804 			 * If the 'vcpu' is running on 'curcpu' then it must
1805 			 * be sending a notification to itself (e.g. SELF_IPI).
1806 			 * The pending event will be picked up when the vcpu
1807 			 * transitions back to guest context.
1808 			 */
1809 		}
1810 	} else {
1811 		KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
1812 		    "with hostcpu %d", vcpu->state, hostcpu));
1813 		if (vcpu->state == VCPU_SLEEPING)
1814 			wakeup_one(vcpu);
1815 	}
1816 	vcpu_unlock(vcpu);
1817 }
1818 
1819 struct vmspace *
1820 vm_get_vmspace(struct vm *vm)
1821 {
1822 
1823 	return (vm->vmspace);
1824 }
1825 
1826 int
1827 vm_apicid2vcpuid(struct vm *vm, int apicid)
1828 {
1829 	/*
1830 	 * XXX apic id is assumed to be numerically identical to vcpu id
1831 	 */
1832 	return (apicid);
1833 }
1834 
1835 void
1836 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
1837     vm_rendezvous_func_t func, void *arg)
1838 {
1839 	int i;
1840 
1841 	/*
1842 	 * Enforce that this function is called without any locks
1843 	 */
1844 	WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
1845 	KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
1846 	    ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
1847 
1848 restart:
1849 	mtx_lock(&vm->rendezvous_mtx);
1850 	if (vm->rendezvous_func != NULL) {
1851 		/*
1852 		 * If a rendezvous is already in progress then we need to
1853 		 * call the rendezvous handler in case this 'vcpuid' is one
1854 		 * of the targets of the rendezvous.
1855 		 */
1856 		RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
1857 		mtx_unlock(&vm->rendezvous_mtx);
1858 		vm_handle_rendezvous(vm, vcpuid);
1859 		goto restart;
1860 	}
1861 	KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
1862 	    "rendezvous is still in progress"));
1863 
1864 	RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
1865 	vm->rendezvous_req_cpus = dest;
1866 	CPU_ZERO(&vm->rendezvous_done_cpus);
1867 	vm->rendezvous_arg = arg;
1868 	vm_set_rendezvous_func(vm, func);
1869 	mtx_unlock(&vm->rendezvous_mtx);
1870 
1871 	/*
1872 	 * Wake up any sleeping vcpus and trigger a VM-exit in any running
1873 	 * vcpus so they handle the rendezvous as soon as possible.
1874 	 */
1875 	for (i = 0; i < VM_MAXCPU; i++) {
1876 		if (CPU_ISSET(i, &dest))
1877 			vcpu_notify_event(vm, i, false);
1878 	}
1879 
1880 	vm_handle_rendezvous(vm, vcpuid);
1881 }
1882 
1883 struct vatpic *
1884 vm_atpic(struct vm *vm)
1885 {
1886 	return (vm->vatpic);
1887 }
1888 
1889 struct vatpit *
1890 vm_atpit(struct vm *vm)
1891 {
1892 	return (vm->vatpit);
1893 }
1894 
1895 enum vm_reg_name
1896 vm_segment_name(int seg)
1897 {
1898 	static enum vm_reg_name seg_names[] = {
1899 		VM_REG_GUEST_ES,
1900 		VM_REG_GUEST_CS,
1901 		VM_REG_GUEST_SS,
1902 		VM_REG_GUEST_DS,
1903 		VM_REG_GUEST_FS,
1904 		VM_REG_GUEST_GS
1905 	};
1906 
1907 	KASSERT(seg >= 0 && seg < nitems(seg_names),
1908 	    ("%s: invalid segment encoding %d", __func__, seg));
1909 	return (seg_names[seg]);
1910 }
1911