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